repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
iankunneke/TIY-Assignmnts
Make Something Beautiful/Make Something Beautiful/Score.swift
1
365
// // Score.swift // Make Something Beautiful // // Created by ian kunneke on 8/8/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // import Foundation class Score { var gameScore: Int = 0 func addToScore(points: Int) { gameScore = gameScore + points } func clearScore() { gameScore = 0 } }
cc0-1.0
vector-im/vector-ios
RiotSwiftUI/Modules/Template/TemplateAdvancedRoomsExample/TemplateRoomList/MockTemplateRoomListScreenState.swift
1
1836
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import SwiftUI /// Using an enum for the screen allows you define the different state cases with /// the relevant associated data for each case. @available(iOS 14.0, *) enum MockTemplateRoomListScreenState: MockScreenState, CaseIterable { // A case for each state you want to represent // with specific, minimal associated data that will allow you // mock that screen. case noRooms case rooms /// The associated screen var screenType: Any.Type { TemplateRoomList.self } /// Generate the view struct for the screen state. var screenView: ([Any], AnyView) { let service: MockTemplateRoomListService switch self { case .noRooms: service = MockTemplateRoomListService(rooms: []) case .rooms: service = MockTemplateRoomListService() } let viewModel = TemplateRoomListViewModel(templateRoomListService: service) // can simulate service and viewModel actions here if needs be. return ( [service, viewModel], AnyView(TemplateRoomList(viewModel: viewModel.context) .addDependency(MockAvatarService.example)) ) } }
apache-2.0
rokity/GCM-Sample
ios/appinvites/AppInvitesExampleSwift/ViewController.swift
61
3471
// // Copyright (c) Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit // Match the ObjC symbol name inside Main.storyboard. @objc(ViewController) // [START viewcontroller_interfaces] class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate, GINInviteDelegate { // [END viewcontroller_interfaces] // [START viewcontroller_vars] @IBOutlet weak var signOutButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var inviteButton: UIButton! @IBOutlet weak var statusText: UILabel! // [END viewcontroller_vars] // [START viewdidload] override func viewWillAppear(animated: Bool) { GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().signInSilently() toggleAuthUI() } // [END viewdidload] // [START signin_handler] func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) { if (error == nil) { // User Successfully signed in. statusText.text = "Signed in as \(user.profile.name)" toggleAuthUI() } else { println("\(error.localizedDescription)") toggleAuthUI() } } // [END signin_handler] // [START signout_tapped] @IBAction func signOutTapped(sender: AnyObject) { GIDSignIn.sharedInstance().signOut() statusText.text = "Signed out" toggleAuthUI() } // [END signout_tapped] // [START disconnect_tapped] @IBAction func disconnectTapped(sender: AnyObject) { GIDSignIn.sharedInstance().disconnect() statusText.text = "Disconnected" toggleAuthUI() } func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) { toggleAuthUI() } // [END disconnect_tapped] // [START invite_tapped] @IBAction func inviteTapped(sender: AnyObject) { let invite = GINInvite.inviteDialog() invite.setMessage("Message") invite.setTitle("Title") invite.setDeepLink("/invite") invite.open() } // [END invite_tapped] // [START toggle_auth] func toggleAuthUI() { if (GIDSignIn.sharedInstance().hasAuthInKeychain()) { // Signed in signOutButton.enabled = true disconnectButton.enabled = true inviteButton.enabled = true } else { signOutButton.enabled = false disconnectButton.enabled = false inviteButton.enabled = false self.performSegueWithIdentifier("SignedOutScreen", sender:self) } } // [END toggle_auth] // [START invite_finished] func inviteFinishedWithInvitations(invitationIds: [AnyObject]!, error: NSError!) { if (error != nil) { println("Failed: " + error.localizedDescription) } else { println("Invitations sent") } } // [END invite_finished] // Sets the status bar to white. override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
apache-2.0
delannoyk/RetinAssets
RetinAssets/utils/array_extension/ArrayExtension.swift
1
380
// // ArrayExtension.swift // RetinAssets // // Created by Kevin DELANNOY on 19/05/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import Cocoa extension Array { func flattern<U>(identity: ([Element]) -> [[U]]) -> [U] { let x: [[U]] = identity(self) return x.reduce([], combine: +) } } func identity<T>(x: T) -> T { return x }
mit
chunkyguy/try-metal
01_HelloMetal/HelloMetal/HelloMetal macOS/GameViewController.swift
1
685
// // GameViewController.swift // HelloMetal macOS // // Created by Sid on 19/01/2019. // Copyright © 2019 whackylabs. All rights reserved. // import Cocoa import MetalKit // Our macOS specific view controller class GameViewController: NSViewController { var renderer: Renderer? override func viewDidLoad() { super.viewDidLoad() let metalView = view as? MTKView assert(metalView != nil) renderer = Renderer(metalView: metalView!) assert(renderer != nil) renderer?.setUp() } override func viewDidAppear() { super.viewDidAppear() renderer?.render() } }
mit
jjochen/photostickers
MessagesExtension/Views/AddIconView.swift
1
447
// // AddMoreIconView.swift // PhotoStickers // // Created by Jochen Pfeiffer on 09.04.17. // Copyright © 2017 Jochen Pfeiffer. All rights reserved. // import UIKit class AddIconView: UIControl { override var isHighlighted: Bool { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { StyleKit.drawAddIcon(frame: rect, resizing: .aspectFit, highlighted: isHighlighted) } }
mit
jsho32/Conversion-Calculator-iOS
Conversion-Calculator/ViewController.swift
1
522
// // ViewController.swift // Conversion-Calculator // // Created by Justin Shores on 6/23/15. // Copyright © 2015 Justin Shores. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Data/Implementations/Standard/BarChartDataSet.swift
6
5861
// // BarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet { private func initialize() { self.highlightColor = NSUIColor.black self.calcStackSize(yVals as! [BarChartDataEntry]) self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]) } public required init() { super.init() initialize() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) initialize() } // MARK: - Data functions and accessors /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 /// the overall entry count, including counting each stack-value individually private var _entryCountStacks = 0 /// Calculates the total number of entries this DataSet represents, including /// stacks. All values belonging to a stack are calculated separately. private func calcEntryCountIncludingStacks(_ yVals: [BarChartDataEntry]!) { _entryCountStacks = 0 for i in 0 ..< yVals.count { let vals = yVals[i].values if (vals == nil) { _entryCountStacks += 1 } else { _entryCountStacks += vals!.count } } } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(_ yVals: [BarChartDataEntry]!) { for i in 0 ..< yVals.count { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } open override func calcMinMax(start : Int, end: Int) { let yValCount = _yVals.count if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in stride(from: start, through: endValue, by: 1) { if let e = _yVals[i] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the maximum number of bars that can be stacked upon another in this DataSet. open var stackSize: Int { return _stackSize } /// - returns: true if this DataSet is stacked (stacksize > 1) or not. open var isStacked: Bool { return _stackSize > 1 ? true : false } /// - returns: the overall entry count, including counting each stack-value individually open var entryCountStacks: Int { return _entryCountStacks } /// array of labels used to describe the different values of the stacked bars open var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) open var barSpace: CGFloat = 0.15 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. open var barBorderWidth : CGFloat = 0.0 /// the color drawing borders around the bars. open var barBorderColor = NSUIColor.black /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) open var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> Any { let copy = super.copyWithZone(zone) as! BarChartDataSet copy._stackSize = _stackSize copy._entryCountStacks = _entryCountStacks copy.stackLabels = stackLabels copy.barSpace = barSpace copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
mit
timothypmiller/Autocomplete
Autocomplete/IconsStyleKit.swift
1
6101
// // IconsStyleKit.swift // Autocomplete // // Created by Timothy P Miller on 4/28/15. // Copyright (c) 2015 Timothy P Miller. All rights reserved. // // Generated by PaintCode (www.paintcodeapp.com) // import UIKit open class IconsStyleKit : NSObject { //// Cache fileprivate struct Cache { static var imageOfCanvas2: UIImage? static var canvas2Targets: [AnyObject]? static var imageOfCanvas4: UIImage? static var canvas4Targets: [AnyObject]? } //// Drawing Methods open class func drawCanvas2() { //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 0.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 5.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 5.5, y: 18.5)) bezierPath.addLine(to: CGPoint(x: 9.5, y: 18.5)) bezierPath.addLine(to: CGPoint(x: 9.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 9.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 9.5, y: 6.5)) bezierPath.addLine(to: CGPoint(x: 14.5, y: 6.5)) bezierPath.addLine(to: CGPoint(x: 14.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 20.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 20.5, y: 12.5)) bezierPath.addLine(to: CGPoint(x: 24.5, y: 12.5)) bezierPath.addLine(to: CGPoint(x: 24.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 27.5, y: 4.5)) bezierPath.addLine(to: CGPoint(x: 29.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 34.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: 34.5, y: 27.5)) UIColor.black.setStroke() bezierPath.lineWidth = 1 bezierPath.stroke() } open class func drawCanvas4() { //// Bezier 2 Drawing let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: 0.5, y: 2.5)) bezier2Path.addCurve(to: CGPoint(x: 33.5, y: 2.5), controlPoint1: CGPoint(x: 33.5, y: 2.5), controlPoint2: CGPoint(x: 33.5, y: 2.5)) UIColor.black.setStroke() bezier2Path.lineWidth = 1 bezier2Path.stroke() //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 0.5, y: 31.5)) bezierPath.addCurve(to: CGPoint(x: 33.5, y: 31.5), controlPoint1: CGPoint(x: 33.5, y: 31.5), controlPoint2: CGPoint(x: 33.5, y: 31.5)) UIColor.black.setStroke() bezierPath.lineWidth = 1 bezierPath.stroke() //// Group //// Oval Drawing let ovalPath = UIBezierPath(ovalIn: CGRect(x: 15.5, y: 4.5, width: 18, height: 25)) UIColor.black.setStroke() ovalPath.lineWidth = 1 ovalPath.stroke() //// Oval 2 Drawing let oval2Path = UIBezierPath(ovalIn: CGRect(x: 20.5, y: 8.5, width: 8, height: 10)) UIColor.black.setStroke() oval2Path.lineWidth = 1 oval2Path.stroke() //// Bezier 3 Drawing let bezier3Path = UIBezierPath() bezier3Path.move(to: CGPoint(x: 21.93, y: 17.66)) bezier3Path.addCurve(to: CGPoint(x: 16.79, y: 22.92), controlPoint1: CGPoint(x: 16.79, y: 22.92), controlPoint2: CGPoint(x: 16.79, y: 22.92)) UIColor.black.setStroke() bezier3Path.lineWidth = 1 bezier3Path.stroke() //// Bezier 4 Drawing let bezier4Path = UIBezierPath() bezier4Path.move(to: CGPoint(x: 28.36, y: 18.97)) bezier4Path.addCurve(to: CGPoint(x: 30.93, y: 24.24), controlPoint1: CGPoint(x: 30.93, y: 24.24), controlPoint2: CGPoint(x: 30.93, y: 24.24)) UIColor.black.setStroke() bezier4Path.lineWidth = 1 bezier4Path.stroke() //// Star Drawing let starPath = UIBezierPath() starPath.move(to: CGPoint(x: 5.5, y: 13.25)) starPath.addLine(to: CGPoint(x: 7.35, y: 15.95)) starPath.addLine(to: CGPoint(x: 10.49, y: 16.88)) starPath.addLine(to: CGPoint(x: 8.5, y: 19.47)) starPath.addLine(to: CGPoint(x: 8.59, y: 22.75)) starPath.addLine(to: CGPoint(x: 5.5, y: 21.65)) starPath.addLine(to: CGPoint(x: 2.41, y: 22.75)) starPath.addLine(to: CGPoint(x: 2.5, y: 19.47)) starPath.addLine(to: CGPoint(x: 0.51, y: 16.88)) starPath.addLine(to: CGPoint(x: 3.65, y: 15.95)) starPath.close() UIColor.black.setStroke() starPath.lineWidth = 1 starPath.stroke() } //// Generated Images open class var imageOfCanvas2: UIImage { if Cache.imageOfCanvas2 != nil { return Cache.imageOfCanvas2! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 34, height: 34), false, 0) IconsStyleKit.drawCanvas2() Cache.imageOfCanvas2 = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfCanvas2! } open class var imageOfCanvas4: UIImage { if Cache.imageOfCanvas4 != nil { return Cache.imageOfCanvas4! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 34, height: 34), false, 0) IconsStyleKit.drawCanvas4() Cache.imageOfCanvas4 = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfCanvas4! } //// Customization Infrastructure @IBOutlet var canvas2Targets: [AnyObject]! { get { return Cache.canvas2Targets } set { Cache.canvas2Targets = newValue for target: AnyObject in newValue { target.setImage(IconsStyleKit.imageOfCanvas2) } } } @IBOutlet var canvas4Targets: [AnyObject]! { get { return Cache.canvas4Targets } set { Cache.canvas4Targets = newValue for target: AnyObject in newValue { target.setImage(IconsStyleKit.imageOfCanvas4) } } } } @objc protocol StyleKitSettableImage { func setImage(_ image: UIImage!) } @objc protocol StyleKitSettableSelectedImage { func setSelectedImage(_ image: UIImage!) }
mit
WhisperSystems/Signal-iOS
SignalServiceKit/src/Messages/Interactions/TSUnreadIndicatorInteraction+SDS.swift
1
7309
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import GRDB import SignalCoreKit // NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py. // Do not manually edit it, instead run `sds_codegen.sh`. // MARK: - Typed Convenience Methods @objc public extension TSUnreadIndicatorInteraction { // NOTE: This method will fail if the object has unexpected type. class func anyFetchUnreadIndicatorInteraction(uniqueId: String, transaction: SDSAnyReadTransaction) -> TSUnreadIndicatorInteraction? { assert(uniqueId.count > 0) guard let object = anyFetch(uniqueId: uniqueId, transaction: transaction) else { return nil } guard let instance = object as? TSUnreadIndicatorInteraction else { owsFailDebug("Object has unexpected type: \(type(of: object))") return nil } return instance } // NOTE: This method will fail if the object has unexpected type. func anyUpdateUnreadIndicatorInteraction(transaction: SDSAnyWriteTransaction, block: (TSUnreadIndicatorInteraction) -> Void) { anyUpdate(transaction: transaction) { (object) in guard let instance = object as? TSUnreadIndicatorInteraction else { owsFailDebug("Object has unexpected type: \(type(of: object))") return } block(instance) } } } // MARK: - SDSSerializer // The SDSSerializer protocol specifies how to insert and update the // row that corresponds to this model. class TSUnreadIndicatorInteractionSerializer: SDSSerializer { private let model: TSUnreadIndicatorInteraction public required init(model: TSUnreadIndicatorInteraction) { self.model = model } // MARK: - Record func asRecord() throws -> SDSRecord { let id: Int64? = model.sortId > 0 ? Int64(model.sortId) : nil let recordType: SDSRecordType = .unreadIndicatorInteraction let uniqueId: String = model.uniqueId // Base class properties let receivedAtTimestamp: UInt64 = model.receivedAtTimestamp let timestamp: UInt64 = model.timestamp let threadUniqueId: String = model.uniqueThreadId // Subclass properties let attachmentIds: Data? = nil let authorId: String? = nil let authorPhoneNumber: String? = nil let authorUUID: String? = nil let beforeInteractionId: String? = nil let body: String? = nil let callSchemaVersion: UInt? = nil let callType: RPRecentCallType? = nil let configurationDurationSeconds: UInt32? = nil let configurationIsEnabled: Bool? = nil let contactId: String? = nil let contactShare: Data? = nil let createdByRemoteName: String? = nil let createdInExistingGroup: Bool? = nil let customMessage: String? = nil let envelopeData: Data? = nil let errorMessageSchemaVersion: UInt? = nil let errorType: TSErrorMessageType? = nil let expireStartedAt: UInt64? = nil let expiresAt: UInt64? = nil let expiresInSeconds: UInt32? = nil let groupMetaMessage: TSGroupMetaMessage? = nil let hasAddToContactsOffer: Bool? = nil let hasAddToProfileWhitelistOffer: Bool? = nil let hasBlockOffer: Bool? = nil let hasLegacyMessageState: Bool? = nil let hasSyncedTranscript: Bool? = nil let incomingMessageSchemaVersion: UInt? = nil let infoMessageSchemaVersion: UInt? = nil let isFromLinkedDevice: Bool? = nil let isLocalChange: Bool? = nil let isViewOnceComplete: Bool? = nil let isViewOnceMessage: Bool? = nil let isVoiceMessage: Bool? = nil let legacyMessageState: TSOutgoingMessageState? = nil let legacyWasDelivered: Bool? = nil let linkPreview: Data? = nil let messageId: String? = nil let messageSticker: Data? = nil let messageType: TSInfoMessageType? = nil let mostRecentFailureText: String? = nil let outgoingMessageSchemaVersion: UInt? = nil let preKeyBundle: Data? = nil let protocolVersion: UInt? = nil let quotedMessage: Data? = nil let read: Bool? = nil let recipientAddress: Data? = nil let recipientAddressStates: Data? = nil let schemaVersion: UInt? = nil let sender: Data? = nil let serverTimestamp: UInt64? = nil let sourceDeviceId: UInt32? = nil let storedMessageState: TSOutgoingMessageState? = nil let storedShouldStartExpireTimer: Bool? = nil let unknownProtocolVersionMessageSchemaVersion: UInt? = nil let unregisteredAddress: Data? = nil let verificationState: OWSVerificationState? = nil let wasReceivedByUD: Bool? = nil return InteractionRecord(id: id, recordType: recordType, uniqueId: uniqueId, receivedAtTimestamp: receivedAtTimestamp, timestamp: timestamp, threadUniqueId: threadUniqueId, attachmentIds: attachmentIds, authorId: authorId, authorPhoneNumber: authorPhoneNumber, authorUUID: authorUUID, beforeInteractionId: beforeInteractionId, body: body, callSchemaVersion: callSchemaVersion, callType: callType, configurationDurationSeconds: configurationDurationSeconds, configurationIsEnabled: configurationIsEnabled, contactId: contactId, contactShare: contactShare, createdByRemoteName: createdByRemoteName, createdInExistingGroup: createdInExistingGroup, customMessage: customMessage, envelopeData: envelopeData, errorMessageSchemaVersion: errorMessageSchemaVersion, errorType: errorType, expireStartedAt: expireStartedAt, expiresAt: expiresAt, expiresInSeconds: expiresInSeconds, groupMetaMessage: groupMetaMessage, hasAddToContactsOffer: hasAddToContactsOffer, hasAddToProfileWhitelistOffer: hasAddToProfileWhitelistOffer, hasBlockOffer: hasBlockOffer, hasLegacyMessageState: hasLegacyMessageState, hasSyncedTranscript: hasSyncedTranscript, incomingMessageSchemaVersion: incomingMessageSchemaVersion, infoMessageSchemaVersion: infoMessageSchemaVersion, isFromLinkedDevice: isFromLinkedDevice, isLocalChange: isLocalChange, isViewOnceComplete: isViewOnceComplete, isViewOnceMessage: isViewOnceMessage, isVoiceMessage: isVoiceMessage, legacyMessageState: legacyMessageState, legacyWasDelivered: legacyWasDelivered, linkPreview: linkPreview, messageId: messageId, messageSticker: messageSticker, messageType: messageType, mostRecentFailureText: mostRecentFailureText, outgoingMessageSchemaVersion: outgoingMessageSchemaVersion, preKeyBundle: preKeyBundle, protocolVersion: protocolVersion, quotedMessage: quotedMessage, read: read, recipientAddress: recipientAddress, recipientAddressStates: recipientAddressStates, schemaVersion: schemaVersion, sender: sender, serverTimestamp: serverTimestamp, sourceDeviceId: sourceDeviceId, storedMessageState: storedMessageState, storedShouldStartExpireTimer: storedShouldStartExpireTimer, unknownProtocolVersionMessageSchemaVersion: unknownProtocolVersionMessageSchemaVersion, unregisteredAddress: unregisteredAddress, verificationState: verificationState, wasReceivedByUD: wasReceivedByUD) } }
gpl-3.0
devlucky/Kakapo
Examples/NewsFeed/NewsFeed/AppDelegate.swift
1
2129
// // AppDelegate.swift // NewsFeed // // Created by Alex Manzella on 08/07/16. // Copyright © 2016 devlucky. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { startMockingNetwork() 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:. } }
mit
barbosa/clappr-ios
Example/Tests/ContainerTests.swift
1
18164
import Quick import Nimble import Clappr class ContainerTests: QuickSpec { override func spec() { describe("Container") { var container: Container! var playback: StubPlayback! let options = [kSourceUrl : "http://globo.com/video.mp4"] beforeEach() { playback = StubPlayback(options: options) container = Container(playback: playback) } describe("Initialization") { it("Should have the playback as subview after rendered") { container.render() expect(playback.superview) == container } it("Should have a constructor that receive options") { let options = ["aOption" : "option"] let container = Container(playback: playback, options: options) let option = container.options["aOption"] as! String expect(option) == "option" } } describe("Destroy") { it("Should be removed from superview and destroy playback when destroy is called") { let wrapperView = UIView() wrapperView.addSubview(container) container.destroy() expect(playback.superview).to(beNil()) expect(container.superview).to(beNil()) } it("Should stop listening to events after destroy is called") { var callbackWasCalled = false container.on("some-event") { _ in callbackWasCalled = true } container.destroy() container.trigger("some-event") expect(callbackWasCalled) == false } } describe("Event Binding") { var eventWasTriggered = false let eventCallback: EventCallback = { _ in eventWasTriggered = true } beforeEach{ eventWasTriggered = false } it("Should trigger container progress event when playback progress event happens") { let expectedStart: Float = 0.7, expectedEnd: Float = 15.4, expectedDuration: NSTimeInterval = 10 var start: Float!, end: Float!, duration: NSTimeInterval! container.once(ContainerEvent.Progress.rawValue) { userInfo in start = userInfo?["start_position"] as! Float end = userInfo?["end_position"] as! Float duration = userInfo?["duration"] as! NSTimeInterval } let userInfo: EventUserInfo = ["start_position": expectedStart, "end_position": expectedEnd, "duration": expectedDuration] playback.trigger(PlaybackEvent.Progress.rawValue, userInfo: userInfo) expect(start) == expectedStart expect(end) == expectedEnd expect(duration) == expectedDuration } it("Should trigger container time updated event when playback respective event happens") { let expectedPosition: Float = 10.3, expectedDuration: NSTimeInterval = 12.7 var position: Float!, duration: NSTimeInterval! container.once(ContainerEvent.TimeUpdated.rawValue) { userInfo in position = userInfo?["position"] as! Float duration = userInfo?["duration"] as! NSTimeInterval } let userInfo: EventUserInfo = ["position": expectedPosition, "duration": expectedDuration] playback.trigger(PlaybackEvent.TimeUpdated.rawValue, userInfo: userInfo) expect(position) == expectedPosition expect(duration) == expectedDuration } it("Should trigger container loaded metadata event when playback respective event happens") { let expectedDuration: NSTimeInterval = 20.0 var duration: NSTimeInterval! container.once(ContainerEvent.LoadedMetadata.rawValue) { userInfo in duration = userInfo?["duration"] as! NSTimeInterval } let userInfo: EventUserInfo = ["duration": expectedDuration] playback.trigger(PlaybackEvent.LoadedMetadata.rawValue, userInfo: userInfo) expect(duration) == expectedDuration } it("Should trigger container bit rate event when playback respective event happens") { let expectedBitRate: NSTimeInterval = 11.0 var bitRate: NSTimeInterval! container.once(ContainerEvent.BitRate.rawValue) { userInfo in bitRate = userInfo?["bit_rate"] as! NSTimeInterval } let userInfo: EventUserInfo = ["bit_rate": expectedBitRate] playback.trigger(PlaybackEvent.BitRate.rawValue, userInfo: userInfo) expect(bitRate) == expectedBitRate } it("Should trigger container DVR state event when playback respective event happens with params") { var dvrInUse = false container.once(ContainerEvent.PlaybackDVRStateChanged.rawValue) { userInfo in dvrInUse = userInfo?["dvr_in_use"] as! Bool } let userInfo: EventUserInfo = ["dvr_in_use": true] playback.trigger(PlaybackEvent.DVRStateChanged.rawValue, userInfo: userInfo) expect(dvrInUse).to(beTrue()) } it("Should trigger container Error event when playback respective event happens with params") { var error = "" container.once(ContainerEvent.Error.rawValue) { userInfo in error = userInfo?["error"] as! String } let userInfo: EventUserInfo = ["error": "Error"] playback.trigger(PlaybackEvent.Error.rawValue, userInfo: userInfo) expect(error) == "Error" } it("Should update container dvrInUse property on playback DVRSTateChanged event") { let userInfo: EventUserInfo = ["dvr_in_use": true] expect(container.dvrInUse).to(beFalse()) playback.trigger(PlaybackEvent.DVRStateChanged.rawValue, userInfo: userInfo) expect(container.dvrInUse).to(beTrue()) } it("Should be ready after playback ready event is triggered") { expect(container.ready) == false playback.trigger(PlaybackEvent.Ready.rawValue) expect(container.ready) == true } it("Should trigger buffering event after playback respective event is triggered") { container.on(ContainerEvent.Buffering.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.Buffering.rawValue) expect(eventWasTriggered) == true } it("Should trigger buffer full event after playback respective event is triggered") { container.on(ContainerEvent.BufferFull.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.BufferFull.rawValue) expect(eventWasTriggered) == true } it("Should trigger settings event after playback respective event is triggered") { container.on(ContainerEvent.SettingsUpdated.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.SettingsUpdated.rawValue) expect(eventWasTriggered) == true } it("Should trigger HD updated event after playback respective event is triggered") { container.on(ContainerEvent.HighDefinitionUpdated.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.HighDefinitionUpdated.rawValue) expect(eventWasTriggered) == true } it("Should trigger State Changed event after playback respective event is triggered") { container.on(ContainerEvent.PlaybackStateChanged.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.StateChanged.rawValue) expect(eventWasTriggered) == true } it("Should trigger Media Control Disabled event after playback respective event is triggered") { container.on(ContainerEvent.MediaControlDisabled.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.MediaControlDisabled.rawValue) expect(eventWasTriggered) == true } it("Should trigger Media Control Enabled event after playback respective event is triggered") { container.on(ContainerEvent.MediaControlEnabled.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.MediaControlEnabled.rawValue) expect(eventWasTriggered) == true } it("Should update mediaControlEnabled property after playback MediaControleEnabled or Disabled is triggered") { playback.trigger(PlaybackEvent.MediaControlEnabled.rawValue) expect(container.mediaControlEnabled).to(beTrue()) playback.trigger(PlaybackEvent.MediaControlDisabled.rawValue) expect(container.mediaControlEnabled).to(beFalse()) } it("Should trigger Ended event after playback respective event is triggered") { container.on(ContainerEvent.Ended.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.Ended.rawValue) expect(eventWasTriggered) == true } it("Should trigger Play event after playback respective event is triggered") { container.on(ContainerEvent.Play.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.Play.rawValue) expect(eventWasTriggered) == true } it("Should trigger Pause event after playback respective event is triggered") { container.on(ContainerEvent.Pause.rawValue, callback: eventCallback) playback.trigger(PlaybackEvent.Pause.rawValue) expect(eventWasTriggered) == true } it("Should trigger it's Stop event after stop is called") { container.on(ContainerEvent.Stop.rawValue, callback: eventCallback) container.stop() expect(eventWasTriggered) == true } context("Bindings with mocked playback") { class MockedSettingsPlayback: Playback { var stopWasCalled = false , playWasCalled = false, pauseWasCalled = false override var settings: [String: AnyObject] { return ["foo": "bar"] } override var isPlaying: Bool { return true } override func stop() { stopWasCalled = true } override func pause() { pauseWasCalled = true } override func play() { playWasCalled = true } } var mockedPlayback: MockedSettingsPlayback! beforeEach() { mockedPlayback = MockedSettingsPlayback(options: options) container = Container(playback: mockedPlayback) } it("Should update it's settings after playback's settings update event") { mockedPlayback.trigger(PlaybackEvent.SettingsUpdated.rawValue) let fooSetting = container.settings["foo"] as? String expect(fooSetting) == "bar" } it("Should update it's settings after playback's DVR State changed event") { mockedPlayback.trigger(PlaybackEvent.DVRStateChanged.rawValue) let fooSetting = container.settings["foo"] as? String expect(fooSetting) == "bar" } it("Should call playback's stop method after calling respective method on container") { container.stop() expect(mockedPlayback.stopWasCalled).to(beTrue()) } it("Should call playback's play method after calling respective method on container") { container.play() expect(mockedPlayback.playWasCalled).to(beTrue()) } it("Should call playback's pause method after calling respective method on container") { container.pause() expect(mockedPlayback.pauseWasCalled).to(beTrue()) } it("Should return playback 'isPlaying' status when respective property is accessed") { expect(container.isPlaying) == mockedPlayback.isPlaying } } } describe("Plugins") { class FakeUIContainerPlugin: UIContainerPlugin {} class AnotherUIContainerPlugin: UIContainerPlugin {} it("Should be able to add a new container UIPlugin") { container.addPlugin(FakeUIContainerPlugin()) expect(container.plugins).toNot(beEmpty()) } it("Should be able to check if has a plugin with given class") { container.addPlugin(FakeUIContainerPlugin()) expect(container.hasPlugin(FakeUIContainerPlugin)).to(beTrue()) } it("Should return false if plugin isn't on container") { container.addPlugin(FakeUIContainerPlugin()) expect(container.hasPlugin(AnotherUIContainerPlugin)).to(beFalse()) } it("Should add self reference on the plugin") { let plugin = FakeUIContainerPlugin() container.addPlugin(plugin) expect(plugin.container) == container } it("Should add plugin as subview after rendered") { let plugin = FakeUIContainerPlugin() container.addPlugin(plugin) container.render() expect(plugin.superview) == container } } describe("Source") { it("Should be able to load a source") { let container = Container(playback: NoOpPlayback(options: [:])) expect(container.playback.pluginName) == "NoOp" container.load("http://globo.com/video.mp4") expect(container.playback.pluginName) == "AVPlayback" expect(container.playback.superview) == container } it("Should be able to load a source with mime type") { let container = Container(playback: NoOpPlayback(options: [:])) expect(container.playback.pluginName) == "NoOp" container.load("http://globo.com/video", mimeType: "video/mp4") expect(container.playback.pluginName) == "AVPlayback" expect(container.playback.superview) == container } } } } class StubPlayback: Playback { override var pluginName: String { return "stubPlayback" } } }
bsd-3-clause
TrustWallet/trust-wallet-ios
Trust/Core/Initializers/SkipBackupFilesInitializer.swift
1
692
// Copyright DApps Platform Inc. All rights reserved. import Foundation struct SkipBackupFilesInitializer: Initializer { let urls: [URL] init(paths: [URL]) { self.urls = paths } func perform() { urls.forEach { addSkipBackupAttributeToItemAtURL($0) } } @discardableResult func addSkipBackupAttributeToItemAtURL(_ url: URL) -> Bool { let url = NSURL.fileURL(withPath: url.path) as NSURL do { try url.setResourceValue(true, forKey: .isExcludedFromBackupKey) try url.setResourceValue(false, forKey: .isUbiquitousItemKey) return true } catch { return false } } }
gpl-3.0
zoul/Movies
MovieKit/WebServiceTests.swift
1
564
import XCTest @testable import MovieKit class WebServiceTests: XCTestCase { func testRequestBuilding() { let resource = Resource<Void>( url: URL(string: "http://www.example.com/")!, parse: { _ in return }, urlParams: ["tag": "foo/bar"]) let webService = WebService(apiKey: "foo:bar") let request = webService.urlRequestForResource(resource) XCTAssertEqual(request.url?.absoluteString, "http://www.example.com/?api_key=foo%3Abar&tag=foo%2Fbar") XCTAssertEqual(request.httpMethod, "GET") } }
mit
cbrentharris/swift
validation-test/compiler_crashers/27843-llvm-foldingset-swift-classtype-nodeequals.swift
1
276
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S<T{let:{class b.protocol P{func f func f:T.C
apache-2.0
RyoAbe/PARTNER
PARTNER/PARTNER/Core/Operation/GetUserOperation.swift
1
574
// // GetUserOperation.swift // PARTNER // // Created by RyoAbe on 2015/01/01. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import UIKit class GetUserOperation: BaseOperation { var userId: String! init(userId : String){ super.init() self.userId = userId self.executeSerialBlock = { var error: NSError? if let user = PFUser.query()!.getObjectWithId(userId, error: &error) { return .Success(user) } return .Failure(NSError.code(.NotFoundUser)) } } }
gpl-3.0
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/Snapshot/SnapshotContainerView.swift
1
2212
// // SnapshotContainerView.swift // CollectionViewPagingLayout // // Created by Amir on 07/03/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit public class SnapshotContainerView: UIView { // MARK: Properties public let snapshots: [UIView] public let identifier: String public let snapshotSize: CGSize public let pieceSizeRatio: CGSize private weak var targetView: UIView? // MARK: Lifecycle public init?(targetView: UIView, pieceSizeRatio: CGSize, identifier: String) { var snapshots: [UIView] = [] self.pieceSizeRatio = pieceSizeRatio guard pieceSizeRatio.width > 0, pieceSizeRatio.height > 0 else { return nil } var x: CGFloat = 0 var y: CGFloat = 0 var width = pieceSizeRatio.width * targetView.frame.width var height = pieceSizeRatio.height * targetView.frame.height if width > targetView.frame.width { width = targetView.frame.width } if height > targetView.frame.height { height = targetView.frame.height } while true { if y >= targetView.frame.height { break } let frame = CGRect(x: x, y: y, width: min(width, targetView.frame.width - x), height: min(height, targetView.frame.height - y)) if let view = targetView.resizableSnapshotView(from: frame, afterScreenUpdates: true, withCapInsets: .zero) { view.frame = frame snapshots.append(view) } x += width if x >= targetView.frame.width { x = 0 y += height } } if snapshots.isEmpty { return nil } self.targetView = targetView self.identifier = identifier self.snapshots = snapshots snapshotSize = targetView.bounds.size super.init(frame: targetView.frame) snapshots.forEach { self.addSubview($0) } } required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } }
mit
crazypoo/PTools
Pods/JXSegmentedView/Sources/Number/JXSegmentedNumberCell.swift
1
1731
// // JXSegmentedNumberCell.swift // JXSegmentedView // // Created by jiaxin on 2018/12/28. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit open class JXSegmentedNumberCell: JXSegmentedTitleCell { public let numberLabel = UILabel() open override func commonInit() { super.commonInit() numberLabel.isHidden = true numberLabel.textAlignment = .center numberLabel.layer.masksToBounds = true contentView.addSubview(numberLabel) } open override func layoutSubviews() { super.layoutSubviews() guard let myItemModel = itemModel as? JXSegmentedNumberItemModel else { return } numberLabel.sizeToFit() let height = myItemModel.numberHeight numberLabel.layer.cornerRadius = height/2 numberLabel.bounds.size = CGSize(width: numberLabel.bounds.size.width + myItemModel.numberWidthIncrement, height: height) numberLabel.center = CGPoint(x: titleLabel.frame.maxX + myItemModel.numberOffset.x, y: titleLabel.frame.minY + myItemModel.numberOffset.y) } open override func reloadData(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) { super.reloadData(itemModel: itemModel, selectedType: selectedType ) guard let myItemModel = itemModel as? JXSegmentedNumberItemModel else { return } numberLabel.backgroundColor = myItemModel.numberBackgroundColor numberLabel.textColor = myItemModel.numberTextColor numberLabel.text = myItemModel.numberString numberLabel.font = myItemModel.numberFont numberLabel.isHidden = myItemModel.number == 0 setNeedsLayout() } }
mit
swift-lang/swift-k
examples/misc/array_wildcard.swift
2
175
type file; app (file t) echo_wildcard (string s[]) { echo s[*] stdout=@filename(t); } string greetings[] = ["how","are","you"]; file hw = echo_wildcard(greetings);
apache-2.0
gtranchedone/NFYU
NFYUTests/MocksAndStubs/BaseViewController+TestExtensions.swift
1
3492
// // BaseViewController+TestExtensions.swift // NFYU // // Created by Gianluca Tranchedone on 01/11/2015. // Copyright © 2015 Gianluca Tranchedone. All rights reserved. // import UIKit @testable import NFYU struct TestExtensionNotifications { static let DidAttemptSegue = "TestExtensionNotificationsDidAttemptSegue" static let DidAttemptPresentingViewController = "TestExtensionNotificationsDidAttemptPresentingViewController" static let DidAttemptDismissingViewController = "TestExtensionNotificationsDidAttemptDismissingViewController" } struct TestExtensionNotificationsKeys { static let SegueSender = "TestExtensionNotificationsKeysSegueSender" static let SegueIdentifier = "TestExtensionNotificationsKeysSegueIdentifier" static let PresentedViewController = "TestExtensionNotificationsKeysPresentedViewController" } extension BaseViewController { override open func performSegue(withIdentifier identifier: String, sender: Any?) { var userInfo: [String : AnyObject] = [TestExtensionNotificationsKeys.SegueIdentifier: identifier as AnyObject] if let sender = sender { userInfo[TestExtensionNotificationsKeys.SegueSender] = sender as AnyObject? } NotificationCenter.default.post(name: Notification.Name(rawValue: TestExtensionNotifications.DidAttemptSegue), object: self, userInfo: userInfo) } override open func dismiss(animated flag: Bool, completion: (() -> Void)?) { NotificationCenter.default.post(name: Notification.Name(rawValue: TestExtensionNotifications.DidAttemptDismissingViewController), object: self) } override open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { let userInfo: [String : UIViewController] = [TestExtensionNotificationsKeys.PresentedViewController: viewControllerToPresent] let notificationName = TestExtensionNotifications.DidAttemptPresentingViewController NotificationCenter.default.post(name: Notification.Name(rawValue: notificationName), object: self, userInfo: userInfo) } } // TODO: delete me when BaseTableViewController is subclass of BaseViewController extension BaseTableViewController { override open func performSegue(withIdentifier identifier: String, sender: Any?) { var userInfo: [String : AnyObject] = [TestExtensionNotificationsKeys.SegueIdentifier: identifier as AnyObject] if let sender = sender { userInfo[TestExtensionNotificationsKeys.SegueSender] = sender as AnyObject? } NotificationCenter.default.post(name: Notification.Name(rawValue: TestExtensionNotifications.DidAttemptSegue), object: self, userInfo: userInfo) } override open func dismiss(animated flag: Bool, completion: (() -> Void)?) { NotificationCenter.default.post(name: Notification.Name(rawValue: TestExtensionNotifications.DidAttemptDismissingViewController), object: self) } override open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { let userInfo: [String : UIViewController] = [TestExtensionNotificationsKeys.PresentedViewController: viewControllerToPresent] let notificationName = TestExtensionNotifications.DidAttemptPresentingViewController NotificationCenter.default.post(name: Notification.Name(rawValue: notificationName), object: self, userInfo: userInfo) } }
mit
rock-n-code/Kashmir
Kashmir/iOS/Features/Cell/Extensions/CellExtensions.swift
1
2520
// // CellExtensions.swift // Kashmir_iOS // // Created by Javier Cicchelli on 19/01/2018. // Copyright © 2018 Rock & Code. All rights reserved. // import UIKit public extension Cell where Self: UITableViewCell { // MARK: Static /** Registers a nib object containing the cell into a table. - parameter tableView: A table view in which to register the nib object. */ static func registerNib(in tableView: UITableView) { let bundle = Bundle(for: self) let nib = UINib(nibName: nibName, bundle: bundle) tableView.register(nib, forCellReuseIdentifier: reuseIdentifier) } /** Returns a reusable table view cell object dequeued from a specified index in a table view. - parameters: - tableView: A table view from where to dequeue the reusable cell. - indexPath: The index path specifying the location of the cell. - throws: A `CellError` error is thrown during the dequeuing of the cell. - returns: A dequeued table view cell object. */ static func dequeue(from tableView: UITableView, at indexPath: IndexPath) throws -> Self { guard let dequededCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? Self else { throw CellError.dequeueFailed } return dequededCell } } public extension Cell where Self: UICollectionViewCell { // MARK: Static /** Registers a nib object containing the cell into a collection. - parameter collectionView: A collection view in which to register the nib object. */ static func registerNib(in collectionView: UICollectionView) { let bundle = Bundle(for: self) let nib = UINib(nibName: nibName, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier) } /** Returns a reusable collection view cell object dequeued from a specified index in a collection view. - parameters: - collectionView: A collection view from where to dequeue the reusable cell. - indexPath: The index path specifying the location of the cell. - throws: A `CellError` error is thrown during the dequeuing of the cell. - returns: A dequeued collection view cell object. */ static func dequeue(from collectionView: UICollectionView, at indexPath: IndexPath) throws -> Self { guard let dequededCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? Self else { throw CellError.dequeueFailed } return dequededCell } }
mit
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Apple/UIKit/UITextView+Extensions.swift
1
6018
// // UITextView+Extensions.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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 UIKit // MARK: - UITextView extension /// This extesion adds some useful functions to UITextView. public extension UITextView { // MARK: - Functions /// Create an UITextView and set some parameters. /// /// - Parameters: /// - frame: TextView frame. /// - text: TextView text. /// - font: TextView text font. /// - textColor: TextView text color. /// - alignment: TextView text alignment. /// - dataDetectorTypes: TextView data detector types. /// - editable: Set if TextView is editable. /// - selectable: Set if TextView is selectable. /// - returnKeyType: TextView return key type. /// - keyboardType: TextView keyboard type. /// - secure: Set if the TextView is secure or not. /// - autocapitalizationType: TextView text capitalization. /// - keyboardAppearance: TextView keyboard appearence. /// - enablesReturnKeyAutomatically: Set if the TextView has to automatically enables the return key. /// - autocorrectionType: TextView auto correction type. /// - delegate: TextView delegate. Set nil if it has no delegate. convenience init(frame: CGRect, text: String, font: UIFont, textColor: UIColor, alignment: NSTextAlignment, dataDetectorTypes: UIDataDetectorTypes, editable: Bool, selectable: Bool, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, autocorrectionType: UITextAutocorrectionType, delegate: UITextViewDelegate?) { self.init(frame: frame) self.text = text self.autocorrectionType = autocorrectionType self.textAlignment = alignment self.keyboardType = keyboardType self.autocapitalizationType = autocapitalizationType self.textColor = textColor self.returnKeyType = returnKeyType self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically isSecureTextEntry = secure self.keyboardAppearance = keyboardAppearance self.font = font self.delegate = delegate self.dataDetectorTypes = dataDetectorTypes isEditable = editable isSelectable = selectable } /// Create an UITextView and set some parameters. /// /// - Parameters: /// - frame: TextView frame. /// - text: TextView text. /// - font: TextView text font name. /// - fontSize: TextView text size. /// - textColor: TextView text color. /// - alignment: TextView text alignment. /// - dataDetectorTypes: TextView data detector types. /// - editable: Set if TextView is editable. /// - selectable: Set if TextView is selectable. /// - returnKeyType: TextView return key type. /// - keyboardType: TextView keyboard type. /// - secure: Set if the TextView is secure or not. /// - autocapitalizationType: TextView text capitalization. /// - keyboardAppearance: TextView keyboard appearence. /// - enablesReturnKeyAutomatically: Set if the TextView has to automatically enables the return key. /// - autocorrectionType: TextView auto correction type. /// - delegate: TextView delegate. Set nil if it has no delegate. convenience init(frame: CGRect, text: String, font: FontName, fontSize: CGFloat, textColor: UIColor, alignment: NSTextAlignment, dataDetectorTypes: UIDataDetectorTypes, editable: Bool, selectable: Bool, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, autocorrectionType: UITextAutocorrectionType, delegate: UITextViewDelegate?) { self.init(frame: frame) self.text = text self.autocorrectionType = autocorrectionType textAlignment = alignment self.keyboardType = keyboardType self.autocapitalizationType = autocapitalizationType self.textColor = textColor self.returnKeyType = returnKeyType self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically isSecureTextEntry = secure self.keyboardAppearance = keyboardAppearance self.font = UIFont(fontName: font, size: fontSize) self.delegate = delegate self.dataDetectorTypes = dataDetectorTypes isEditable = editable isSelectable = selectable } /// Paste the pasteboard text to UITextView func pasteFromPasteboard() { text = UIPasteboard.getString() } /// Copy UITextView text to pasteboard func copyToPasteboard() { UIPasteboard.copy(text: text) } }
mit
Swift-Squirrel/Squirrel
Sources/Squirrel/HTTPHeaderElement.swift
1
7009
// // HTTPHeaders.swift // Micros // // Created by Filip Klembara on 6/26/17. // // /// HTTP header /// /// - contentLength: Content length /// - contentEncoding: Content encoding /// - contentType: Content type /// - location: Location public enum HTTPHeaderElement { case contentLength(size: Int) case contentEncoding(HTTPHeaderElement.Encoding) case contentType(HTTPHeaderElement.ContentType) case location(location: String) case range(UInt, UInt) case contentRange(start: UInt, end: UInt, from: UInt) case connection(HTTPHeaderElement.Connection) } // MARK: - Hashable extension HTTPHeaderElement: Hashable { /// Hash value public var hashValue: Int { switch self { case .contentType: return 0 case .contentEncoding: return 1 case .contentLength: return 2 case .location: return 3 case .range: return 4 case .contentRange: return 5 case .connection: return 6 } } /// Check string equality /// /// - Parameters: /// - lhs: lhs /// - rhs: rhs /// - Returns: `lhs.description == rhs.description` public static func == (lhs: HTTPHeaderElement, rhs: HTTPHeaderElement) -> Bool { return lhs.description == rhs.description } } // MARK: - Sub enums public extension HTTPHeaderElement { /// Connection /// /// - keepAlive /// - close public enum Connection: String, CustomStringConvertible { /// rawValue of case public var description: String { return rawValue } case keepAlive = "keep-alive" case close } /// Encoding /// /// - gzip /// - deflate public enum Encoding: String, CustomStringConvertible { case gzip case deflate /// Returns raw value public var description: String { return self.rawValue } } /// Content type enum ContentType: String, CustomStringConvertible { // Image case png case jpeg case svg = "svg+xml" //Text case html case plain case css // Application case js = "javascript" case json = "json" case formUrlencoded = "x-www-form-urlencoded" case forceDownload = "force-download" // multipart case formData = "form-data" // video case mp4 case ogg case mov = "quicktime" case webm case wmv = "x-ms-wmv" case avi = "x-msvideo" /// MIME representation public var description: String { let mime: String switch self { case .png, .jpeg, .svg: mime = "image" case .html, .plain, .css: mime = "text" case .js, .json, .formUrlencoded, .forceDownload: mime = "application" case .formData: mime = "multipart" case .mp4, .ogg, .mov, .webm, .wmv, .avi: mime = "video" } return "\(mime)/\(rawValue)" } } } // MARK: - Getting values from HTTPHeader extension HTTPHeaderElement: CustomStringConvertible { /// <key>: <value> description public var description: String { let (key, value) = keyValue return "\(key): \(value)" } /// Returns key and value public var keyValue: (key: String, value: String) { let key: HTTPHeaderKey let value: String switch self { case .contentLength(let size): key = .contentLength value = size.description case .contentEncoding(let encoding): key = .contentEncoding value = encoding.description case .contentType(let type): key = .contentType value = type.description case .location(let location): key = .location value = location case .range(let bottom, let top): key = .range value = "bytes=\(bottom)-\(top)" case .contentRange(let start, let end, let from): key = .contentRange value = "bytes \(start)-\(end)/\(from)" case .connection(let con): key = .connection value = con.description } return (key.description, value) } } /// Request-line in HTTP request public enum RequestLine { /// HTTP Method /// /// - post: POST /// - get: GET /// - put: PUT /// - delete: DELETE /// - head: HEAD /// - option: OPTIONS /// - patch: PATCH public enum Method: String, CustomStringConvertible { case post = "POST" case get = "GET" case put = "PUT" case delete = "DELETE" case head = "HEAD" case options = "OPTIONS" case patch = "PATCH" /// Uppercased rawValue public var description: String { return rawValue } } /// HTTP protocol /// /// - http11: 1.1 public enum HTTPProtocol: String, CustomStringConvertible { case http11 = "HTTP/1.1" init?(rawHTTPValue value: String) { guard value == "HTTP/1.1" else { return nil } self = .http11 } /// Returns `rawValue` /// - Note: Value is uppercased public var description: String { return rawValue } } } /// Check if pattern match value /// /// - Parameters: /// - pattern: pattern /// - value: value /// - Returns: if pattern matches value public func ~= (pattern: HTTPHeaderElement.ContentType, value: String) -> Bool { guard let valueType = value.split(separator: "/", maxSplits: 1).last? .split(separator: ";").first?.split(separator: " ").first, let patternValue = HTTPHeaderElement.ContentType(rawValue: valueType.description) else { return false } guard patternValue == pattern else { return false } return true } /// Check lowercased equality /// /// - Parameters: /// - lhs: lhs /// - rhs: rhs /// - Returns: If string representation in lowercased is same public func == (lhs: String?, rhs: HTTPHeaderElement.ContentType) -> Bool { return lhs?.lowercased() == rhs.description.lowercased() } /// Check lowercased equality /// /// - Parameters: /// - lhs: lhs /// - rhs: rhs /// - Returns: If string representation in lowercased is same public func == (lhs: String?, rhs: HTTPHeaderElement.Connection) -> Bool { return lhs?.lowercased() == rhs.description.lowercased() } /// Check lowercased equality /// /// - Parameters: /// - lhs: lhs /// - rhs: rhs /// - Returns: If string representation in lowercased is same public func == (lhs: String?, rhs: HTTPHeaderElement.Encoding) -> Bool { return lhs?.lowercased() == rhs.description.lowercased() }
apache-2.0
15cm/AMM
AMM/Menu/TaskMenuItemViewController.swift
1
2794
// // AMMTaskMenuItemViewController.swift // AMM // // Created by Sinkerine on 30/01/2017. // Copyright © 2017 sinkerine. All rights reserved. // import Cocoa class TaskMenuItemViewController: NSViewController { @objc var task: Aria2Task = Aria2Task() @IBOutlet var viewDark: NSView! init() { super.init(nibName: NSNib.Name(rawValue: "TaskMenuItemViewController"), bundle: nil) } init?(task: Aria2Task) { self.task = task super.init(nibName: NSNib.Name(rawValue: "TaskMenuItemViewController"), bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { if AMMPreferences.instance.darkModeEnabled { self.view = viewDark } super.viewDidLoad() // Do view setup here. } } // KVO bindings extension Aria2Task { @objc dynamic var statusIcon: NSImage { switch status { case .active: return #imageLiteral(resourceName: "fa-download") case .paused: return #imageLiteral(resourceName: "fa-pause") case .complete: return #imageLiteral(resourceName: "fa-check") case .stopped: return #imageLiteral(resourceName: "fa-stop") case .error: return #imageLiteral(resourceName: "iconmoon-cross") case .unknown: return #imageLiteral(resourceName: "fa-question") default: return #imageLiteral(resourceName: "fa-question") } } @objc dynamic class func keyPathsForValuesAffectingStatusIcon() -> Set<String> { return Set(["statusRawValue"]) } @objc dynamic var percentage: Double { return totalLength == 0 ? 0 : Double(completedLength) / Double(totalLength) * 100 } @objc dynamic class func keyPathsForValuesAffectingPercentage() -> Set<String> { return Set(["completedLength", "totalLength"]) } @objc dynamic var downloadSpeedReadable: String { return Aria2.getReadable(length: downloadSpeed) + "/s" } @objc dynamic class func keyPathsForValuesAffectingDownloadSpeedReadable() -> Set<String> { return Set(["downloadSpeed"]) } @objc dynamic var uploadSpeedReadable: String { return Aria2.getReadable(length: uploadSpeed) + "/s" } @objc dynamic class func keyPathsForValuesAffectingUploadSpeedReadable() -> Set<String> { return Set(["uploadSpeed"]) } @objc dynamic var totalLengthReadable: String { return Aria2.getReadable(length: totalLength) } @objc dynamic class func keyPathsForValuesAffectingTotalLengthReadable() -> Set<String> { return Set(["totalLength"]) } }
gpl-3.0
MrSuperJJ/JJSwiftNews
JJSwiftNews/Util/JJError.swift
1
828
// // JJError.swift // JJSwiftNews // // Created by 叶佳骏 on 2017/7/31. // Copyright © 2017年 yejiajun. All rights reserved. // import Foundation enum JJError: Error { case networkError case dataInconsistentError case jsonParsedError case noMoreDataError(String) case requetFailedError(String) internal var description: String { get { switch self { case .networkError: return "网络似乎不给力" case .dataInconsistentError: return "数据不一致" case .jsonParsedError: return "JSON解析错误" case .noMoreDataError: return "数据异常" case .requetFailedError: return "访问异常" } } } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/27506-swift-modulefile-gettype.swift
11
430
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse var b{typealias F=[Void{let a{for b=c
apache-2.0
wikimedia/wikipedia-ios
Wikipedia/Code/WMFContentGroupKind+FeedCustomization.swift
1
825
extension WMFContentGroupKind { var isInFeed: Bool { guard isGlobal else { return !feedContentController.contentLanguageCodes(for: self).isEmpty } return feedContentController.isGlobalContentGroupKind(inFeed: self) } var isCustomizable: Bool { return WMFExploreFeedContentController.customizableContentGroupKindNumbers().contains(NSNumber(value: rawValue)) } var isGlobal: Bool { return WMFExploreFeedContentController.globalContentGroupKindNumbers().contains(NSNumber(value: rawValue)) } var contentLanguageCodes: [String] { return feedContentController.contentLanguageCodes(for: self) } private var feedContentController: WMFExploreFeedContentController { return MWKDataStore.shared().feedContentController } }
mit
matsprea/omim
iphone/Maps/Core/Theme/Colors.swift
1
8309
class DayColors: IColors { var clear = UIColor.clear var primaryDark = UIColor(24, 128, 68, alpha100) var primary = UIColor(32, 152, 82, alpha100) var secondary = UIColor(45, 137, 83, alpha100) // Light green color var primaryLight = UIColor(36, 180, 98, alpha100) var menuBackground = UIColor(255, 255, 255, alpha90) var downloadBadgeBackground = UIColor(255, 55, 35, alpha100) // Background color && press color var pressBackground = UIColor(245, 245, 245, alpha100) // Red color (use for status closed in place page) var red = UIColor(230, 15, 35, alpha100) var errorPink = UIColor(246, 60, 51, alpha12) // Orange color (use for status 15 min in place page) var orange = UIColor(255, 120, 5, alpha100) // Blue color (use for links and phone numbers) var linkBlue = UIColor(30, 150, 240, alpha100) var linkBlueHighlighted = UIColor(30, 150, 240, alpha30) var linkBlueDark = UIColor(25, 135, 215, alpha100) var buttonRed = UIColor(244, 67, 67, alpha100) var buttonRedHighlighted = UIColor(183, 28, 28, alpha100) var blackPrimaryText = UIColor(0, 0, 0, alpha87) var blackSecondaryText = UIColor(0, 0, 0, alpha54) var blackHintText = UIColor(0, 0, 0, alpha26) var blackDividers = UIColor(0, 0, 0, alpha12) var solidDividers = UIColor(224, 224, 224, alpha100) var white = UIColor(255, 255, 255, alpha100) var whitePrimaryText = UIColor(255, 255, 255, alpha87); var whitePrimaryTextHighlighted = UIColor(255, 255, 255, alpha30); var whiteSecondaryText = UIColor(255, 255, 255, alpha54) var whiteHintText = UIColor(255, 255, 255, alpha30) var buttonDisabledBlueText = UIColor(3, 122, 255, alpha26) var alertBackground = UIColor(255, 255, 255, alpha90) var blackOpaque = UIColor(0, 0, 0, alpha04) var toastBackground = UIColor(255, 255, 255, alpha87) var statusBarBackground = UIColor(255, 255, 255, alpha36) var bannerBackground = UIColor(242, 245, 212, alpha100) var searchPromoBackground = UIColor(249, 251, 231, alpha100) var border = UIColor(0, 0, 0, alpha04) var discountBackground = UIColor(240, 100, 60, alpha100) var discountText = UIColor(60, 64, 68, alpha100) var bookmarkSubscriptionBackground = UIColor(240, 252, 255, alpha100) var bookmarkSubscriptionScrollBackground = UIColor(137, 217, 255, alpha100) var bookmarkSubscriptionFooterBackground = UIColor(47, 58, 73, alpha100) var bookingBackground = UIColor(25, 69, 125, alpha100) var opentableBackground = UIColor(218, 55, 67, alpha100) var transparentGreen = UIColor(233, 244, 233, alpha26) var ratingRed = UIColor(229, 57, 53, alpha100) var ratingOrange = UIColor(244, 81, 30, alpha100) var ratingYellow = UIColor(245, 176, 39, alpha100) var ratingLightGreen = UIColor(124, 179, 66, alpha100) var ratingGreen = UIColor(67, 160, 71, alpha100) var bannerButtonBackground = UIColor(60, 140, 60, alpha70) var facebookButtonBackground = UIColor(59, 89, 152, alpha100); var facebookButtonBackgroundDisabled = UIColor(59, 89, 152, alpha70); var allPassSubscriptionTitle = UIColor(0, 0, 0, alpha100) var allPassSubscriptionSubTitle = UIColor(0, 0, 0, alpha87) var allPassSubscriptionDescription = UIColor(255, 255, 255, alpha100) var allPassSubscriptionMonthlyBackground = UIColor(224, 224, 224, alpha80) var allPassSubscriptionYearlyBackground = UIColor(30, 150, 240, alpha100) var allPassSubscriptionMonthlyTitle = UIColor(255, 255, 255, alpha100) var allPassSubscriptionDiscountBackground = UIColor(245, 210, 12, alpha100) var allPassSubscriptionTermsTitle = UIColor(255, 255, 255, alpha70) var fadeBackground = UIColor(0, 0, 0, alpha80) var blackStatusBarBackground = UIColor(0, 0, 0, alpha80) var elevationPreviewTint = UIColor(193, 209, 224, alpha30) var elevationPreviewSelector = UIColor(red: 0.757, green: 0.82, blue: 0.878, alpha: 1) var shadow = UIColor(0, 0, 0, alpha100) var chartLine = UIColor(red: 0.118, green: 0.588, blue: 0.941, alpha: 1) var chartShadow = UIColor(red: 0.118, green: 0.588, blue: 0.941, alpha: 0.12) var cityColor = UIColor(red: 0.4, green: 0.225, blue: 0.75, alpha: 1) var outdoorColor = UIColor(red: 0.235, green: 0.549, blue: 0.235, alpha: 1) } class NightColors: IColors { var clear = UIColor.clear var primaryDark = UIColor(25, 30, 35, alpha100) var primary = UIColor(45, 50, 55, alpha100) var secondary = UIColor(0x25, 0x28, 0x2b, alpha100) // Light green color var primaryLight = UIColor(65, 70, 75, alpha100) var menuBackground = UIColor(45, 50, 55, alpha90) var downloadBadgeBackground = UIColor(230, 70, 60, alpha100) // Background color && press color var pressBackground = UIColor(50, 54, 58, alpha100) // Red color (use for status closed in place page) var red = UIColor(230, 70, 60, alpha100) var errorPink = UIColor(246, 60, 51, alpha26) // Orange color (use for status 15 min in place page) var orange = UIColor(250, 190, 10, alpha100) // Blue color (use for links and phone numbers) var linkBlue = UIColor(80, 195, 240, alpha100) var linkBlueHighlighted = UIColor(60, 155, 190, alpha30) var linkBlueDark = UIColor(75, 185, 230, alpha100) var buttonRed = UIColor(244, 67, 67, alpha100) var buttonRedHighlighted = UIColor(183, 28, 28, alpha100) var blackPrimaryText = UIColor(255, 255, 255, alpha90) var blackSecondaryText = UIColor(255, 255, 255, alpha70) var blackHintText = UIColor(255, 255, 255, alpha30) var blackDividers = UIColor(255, 255, 255, alpha12) var solidDividers = UIColor(84, 86, 90, alpha100) var white = UIColor(60, 64, 68, alpha100) var whitePrimaryText = UIColor(255, 255, 255, alpha87) var whitePrimaryTextHighlighted = UIColor(255, 255, 255, alpha30) var whiteSecondaryText = UIColor(0, 0, 0, alpha70) var whiteHintText = UIColor(0, 0, 0, alpha26) var buttonDisabledBlueText = UIColor(255, 230, 140, alpha30) var alertBackground = UIColor(60, 64, 68, alpha90) var blackOpaque = UIColor(255, 255, 255, alpha04) var toastBackground = UIColor(0, 0, 0, alpha87) var statusBarBackground = UIColor(0, 0, 0, alpha32) var bannerBackground = UIColor(255, 255, 255, alpha54) var searchPromoBackground = UIColor(71, 75, 79, alpha100) var border = UIColor(255, 255, 255, alpha04) var discountBackground = UIColor(240, 100, 60, alpha100) var discountText = UIColor(60, 64, 68, alpha100) var bookmarkSubscriptionBackground = UIColor(60, 64, 68, alpha100) var bookmarkSubscriptionScrollBackground = UIColor(137, 217, 255, alpha100) var bookmarkSubscriptionFooterBackground = UIColor(47, 58, 73, alpha100) var bookingBackground = UIColor(25, 69, 125, alpha100) var opentableBackground = UIColor(218, 55, 67, alpha100) var transparentGreen = UIColor(233, 244, 233, alpha26) var ratingRed = UIColor(229, 57, 53, alpha100) var ratingOrange = UIColor(244, 81, 30, alpha100) var ratingYellow = UIColor(245, 176, 39, alpha100) var ratingLightGreen = UIColor(124, 179, 66, alpha100) var ratingGreen = UIColor(67, 160, 71, alpha100) var bannerButtonBackground = UIColor(89, 115, 128, alpha70) var facebookButtonBackground = UIColor(59, 89, 152, alpha100); var facebookButtonBackgroundDisabled = UIColor(59, 89, 152, alpha70); var allPassSubscriptionTitle = UIColor(0, 0, 0, alpha100) var allPassSubscriptionSubTitle = UIColor(0, 0, 0, alpha87) var allPassSubscriptionDescription = UIColor(255, 255, 255, alpha100) var allPassSubscriptionMonthlyBackground = UIColor(224, 224, 224, alpha80) var allPassSubscriptionYearlyBackground = UIColor(30, 150, 240, alpha100) var allPassSubscriptionMonthlyTitle = UIColor(255, 255, 255, alpha100) var allPassSubscriptionDiscountBackground = UIColor(245, 210, 12, alpha100) var allPassSubscriptionTermsTitle = UIColor(255, 255, 255, alpha70) var fadeBackground = UIColor(0, 0, 0, alpha80) var blackStatusBarBackground = UIColor(0, 0, 0, alpha80) var elevationPreviewTint = UIColor(0, 0, 0, alpha54) var elevationPreviewSelector = UIColor(red: 0.404, green: 0.439, blue: 0.475, alpha: 1) var shadow = UIColor.clear var chartLine = UIColor(red: 0.294, green: 0.725, blue: 0.902, alpha: 1) var chartShadow = UIColor(red: 0.294, green: 0.725, blue: 0.902, alpha: 0.12) var cityColor = UIColor(152, 103, 252, alpha100) var outdoorColor = UIColor(147, 191, 57, alpha100) }
apache-2.0
AgaKhanFoundation/WCF-iOS
Steps4Impact/Settings/Cells/SettingsProfileCell.swift
1
3330
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 UIKit struct SettingsProfileCellContext: CellContext { let identifier: String = SettingsProfileCell.identifier let imageURL: URL? let name: String let teamName: String let membership: String } class SettingsProfileCell: ConfigurableTableViewCell { static let identifier = "SettingsProfileCell" private let profileImageView = WebImageView() private let nameLabel = UILabel(typography: .title) private let teamNameLabel = UILabel(typography: .smallRegular) private let membershipLabel = UILabel(typography: .smallRegular) override func commonInit() { super.commonInit() profileImageView.clipsToBounds = true contentView.backgroundColor = Style.Colors.white contentView.addSubview(profileImageView) { $0.height.width.equalTo(Style.Size.s64) $0.centerY.equalToSuperview() $0.leading.equalToSuperview().inset(Style.Padding.p32) } let stackView = UIStackView() stackView.axis = .vertical stackView.addArrangedSubviews(nameLabel, teamNameLabel, membershipLabel) contentView.addSubview(stackView) { $0.top.bottom.trailing.equalToSuperview().inset(Style.Padding.p16) $0.leading.equalTo(profileImageView.snp.trailing).offset(Style.Padding.p32) } } override func layoutSubviews() { super.layoutSubviews() profileImageView.layer.cornerRadius = profileImageView.frame.height / 2 } override func prepareForReuse() { super.prepareForReuse() profileImageView.stopLoading() } func configure(context: CellContext) { guard let context = context as? SettingsProfileCellContext else { return } nameLabel.text = context.name teamNameLabel.text = context.teamName membershipLabel.text = context.membership profileImageView.fadeInImage(imageURL: context.imageURL, placeHolderImage: Assets.placeholder.image) } }
bsd-3-clause
nubbel/swift-tensorflow
Sources/gdr.pb.swift
2
4255
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: tensorflow/contrib/gdr/gdr.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public struct Tensorflow_RemoteMemoryRegion: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".RemoteMemoryRegion" public var host: String = String() public var port: String = String() public var addr: UInt64 = 0 public var rkey: UInt32 = 0 public var tensorKey: UInt32 = 0 public var checksum: UInt64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.host) case 2: try decoder.decodeSingularStringField(value: &self.port) case 3: try decoder.decodeSingularUInt64Field(value: &self.addr) case 4: try decoder.decodeSingularUInt32Field(value: &self.rkey) case 5: try decoder.decodeSingularUInt32Field(value: &self.tensorKey) case 6: try decoder.decodeSingularUInt64Field(value: &self.checksum) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.host.isEmpty { try visitor.visitSingularStringField(value: self.host, fieldNumber: 1) } if !self.port.isEmpty { try visitor.visitSingularStringField(value: self.port, fieldNumber: 2) } if self.addr != 0 { try visitor.visitSingularUInt64Field(value: self.addr, fieldNumber: 3) } if self.rkey != 0 { try visitor.visitSingularUInt32Field(value: self.rkey, fieldNumber: 4) } if self.tensorKey != 0 { try visitor.visitSingularUInt32Field(value: self.tensorKey, fieldNumber: 5) } if self.checksum != 0 { try visitor.visitSingularUInt64Field(value: self.checksum, fieldNumber: 6) } try unknownFields.traverse(visitor: &visitor) } } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "tensorflow" extension Tensorflow_RemoteMemoryRegion: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "host"), 2: .same(proto: "port"), 3: .same(proto: "addr"), 4: .same(proto: "rkey"), 5: .standard(proto: "tensor_key"), 6: .same(proto: "checksum"), ] public func _protobuf_generated_isEqualTo(other: Tensorflow_RemoteMemoryRegion) -> Bool { if self.host != other.host {return false} if self.port != other.port {return false} if self.addr != other.addr {return false} if self.rkey != other.rkey {return false} if self.tensorKey != other.tensorKey {return false} if self.checksum != other.checksum {return false} if unknownFields != other.unknownFields {return false} return true } }
mit
64characters/Telephone
UseCasesTests/CallHistoriesHistoryRemoveUseCaseTests.swift
2
1424
// // CallHistoriesHistoryRemoveUseCaseTests.swift // Telephone // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UseCases import UseCasesTestDoubles import XCTest final class CallHistoriesHistoryRemoveUseCaseTests: XCTestCase { func testCallsRemoveAllOnHistoryOnDidRemoveAccount() { let uuid = "any-uuid" let history = CallHistorySpy() let sut = CallHistoriesHistoryRemoveUseCase(histories: CallHistoriesSpy(histories: [uuid: history])) sut.didRemoveAccount(withUUID: uuid) XCTAssertTrue(history.didCallRemoveAll) } func testRemovesHistoryOnDidRemoveAccount() { let uuid = "any-uuid" let histories = CallHistoriesSpy(histories: [uuid: CallHistorySpy()]) let sut = CallHistoriesHistoryRemoveUseCase(histories: histories) sut.didRemoveAccount(withUUID: uuid) XCTAssertTrue(histories.didCallRemove) XCTAssertEqual(histories.invokedUUID, uuid) } }
gpl-3.0
arietis/codility-swift
15.4.swift
1
721
public func solution(inout A : [Int]) -> Int { // write your code in Swift 2.2 (Linux) let n = A.count var back = 0 var front = n - 1 func absSum(a: Int, b: Int) -> Int { return abs(a + b) } var mi = absSum(A[back], b: A[front]) A.sortInPlace() func minAbsSum(a: Int, b: Int, min: Int) -> Int { return absSum(a, b: b) < min ? absSum(a, b: b) : min } while back != front && mi > 0 { mi = minAbsSum(A[back], b: A[front], min: mi) if absSum(A[back + 1], b: A[front]) < absSum(A[back], b: A[front - 1]) { back += 1 } else { front -= 1 } } return minAbsSum(A[back], b: A[front], min: mi) }
mit
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Generators/Physical Models/Flute/AKFlute.swift
1
4636
// // AKFlute.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// STK Flutee /// /// - Parameters: /// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. /// - amplitude: Amplitude /// public class AKFlute: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKFluteAudioUnit? internal var token: AUParameterObserverToken? private var frequencyParameter: AUParameter? private var amplitudeParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. public var frequency: Double = 110 { willSet { if frequency != newValue { frequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// Amplitude public var amplitude: Double = 0.5 { willSet { if amplitude != newValue { amplitudeParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize the mandolin with defaults override convenience init() { self.init(frequency: 110) } /// Initialize the STK Flute model /// /// - Parameters: /// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. /// - amplitude: Amplitude /// public init( frequency: Double = 440, amplitude: Double = 0.5) { self.frequency = frequency self.amplitude = amplitude var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x666c7574 /*'flut'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKFluteAudioUnit.self, asComponentDescription: description, name: "Local AKFlute", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKFluteAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } frequencyParameter = tree.valueForKey("frequency") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.frequencyParameter!.address { self.frequency = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } } } internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) } /// Trigger the sound with an optional set of parameters /// - frequency: Frequency in Hz /// - amplitude amplitude: Volume /// public func trigger(frequency frequency: Double, amplitude: Double = 1) { self.frequency = frequency self.amplitude = amplitude self.internalAU!.start() self.internalAU!.triggerFrequency(Float(frequency), amplitude: Float(amplitude)) } /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
hyperoslo/Sync
Tests/Sync/NSPersistentContainerTests.swift
1
5848
import XCTest import CoreData import Sync class NSPersistentContainerTests: XCTestCase { func testPersistentContainer() { if #available(iOS 10, *) { let expectation = self.expectation(description: "testSkipTestMode") let momdModelURL = Bundle(for: NSPersistentContainerTests.self).url(forResource: "Camelcase", withExtension: "momd")! let model = NSManagedObjectModel(contentsOf: momdModelURL)! let persistentContainer = NSPersistentContainer(name: "Camelcase", managedObjectModel: model) try! persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) let objects = Helper.objectsFromJSON("camelcase.json") as! [[String: Any]] persistentContainer.sync(objects, inEntityNamed: "NormalUser", predicate: nil) { error in let result = Helper.fetchEntity("NormalUser", inContext: persistentContainer.viewContext) XCTAssertEqual(result.count, 1) if let first = result.first { XCTAssertEqual(first.value(forKey: "etternavn") as? String, "Nuñez") XCTAssertEqual(first.value(forKey: "firstName") as? String, "Elvis") XCTAssertEqual(first.value(forKey: "fullName") as? String, "Elvis Nuñez") XCTAssertEqual(first.value(forKey: "numberOfChildren") as? Int, 1) XCTAssertEqual(first.value(forKey: "remoteID") as? String, "1") } else { XCTFail() } expectation.fulfill() } self.waitForExpectations(timeout: 150.0, handler: nil) } } func testPersistentContainerExtension() { if #available(iOS 10, *) { let expectation = self.expectation(description: "testSkipTestMode") let persistentContainer = Helper.persistentStoreWithModelName("Camelcase") let objects = Helper.objectsFromJSON("camelcase.json") as! [[String: Any]] persistentContainer.sync(objects, inEntityNamed: "NormalUser") { error in let result = Helper.fetchEntity("NormalUser", inContext: persistentContainer.viewContext) XCTAssertEqual(result.count, 1) if let first = result.first { XCTAssertEqual(first.value(forKey: "etternavn") as? String, "Nuñez") XCTAssertEqual(first.value(forKey: "firstName") as? String, "Elvis") XCTAssertEqual(first.value(forKey: "fullName") as? String, "Elvis Nuñez") XCTAssertEqual(first.value(forKey: "numberOfChildren") as? Int, 1) XCTAssertEqual(first.value(forKey: "remoteID") as? String, "1") } else { XCTFail() } expectation.fulfill() } self.waitForExpectations(timeout: 150.0, handler: nil) } } func testInsertOrUpdate() { if #available(iOS 10, *) { let expectation = self.expectation(description: "testSkipTestMode") let persistentContainer = Helper.persistentStoreWithModelName("Tests") let json = ["id": 1] persistentContainer.insertOrUpdate(json, inEntityNamed: "User") { result in switch result { case .success: XCTAssertEqual(1, Helper.countForEntity("User", inContext: persistentContainer.viewContext)) case .failure: XCTFail() } expectation.fulfill() } self.waitForExpectations(timeout: 150.0, handler: nil) } } func testUpdate() { if #available(iOS 10, *) { let expectation = self.expectation(description: "testSkipTestMode") let persistentContainer = Helper.persistentStoreWithModelName("id") let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: persistentContainer.viewContext) user.setValue("id", forKey: "id") try! persistentContainer.viewContext.save() XCTAssertEqual(1, Helper.countForEntity("User", inContext: persistentContainer.viewContext)) persistentContainer.update("id", with: ["name": "bossy"], inEntityNamed: "User") { result in switch result { case .success(let id): XCTAssertEqual(id as? String, "id") XCTAssertEqual(1, Helper.countForEntity("User", inContext: persistentContainer.viewContext)) persistentContainer.viewContext.refresh(user, mergeChanges: false) XCTAssertEqual(user.value(forKey: "name") as? String, "bossy") case .failure: XCTFail() } expectation.fulfill() } self.waitForExpectations(timeout: 150.0, handler: nil) } } func testDelete() { let expectation = self.expectation(description: "testSkipTestMode") let persistentContainer = Helper.persistentStoreWithModelName("id") let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: persistentContainer.viewContext) user.setValue("id", forKey: "id") try! persistentContainer.viewContext.save() XCTAssertEqual(1, Helper.countForEntity("User", inContext: persistentContainer.viewContext)) persistentContainer.delete("id", inEntityNamed: "User") { error in XCTAssertEqual(0, Helper.countForEntity("User", inContext: persistentContainer.viewContext)) expectation.fulfill() } self.waitForExpectations(timeout: 150.0, handler: nil) } }
mit
benlangmuir/swift
test/Serialization/multi-file-nested-type-simple.swift
22
895
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file.swiftmodule -primary-file %s %S/Inputs/multi-file-nested-types.swift // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file-2.swiftmodule %s -primary-file %S/Inputs/multi-file-nested-types.swift // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file.swiftmodule %t/multi-file-2.swiftmodule -o %t -print-stats 2>&1 | %FileCheck %s // Switch the order of the files. // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file-2.swiftmodule %t/multi-file.swiftmodule -o %t -print-stats 2>&1 | %FileCheck %s // REQUIRES: asserts // CHECK: 4 Serialization - # of nested types resolved without full lookup public func useTypes( _: Outer.Inner, _: Outer.InnerAlias, _: OuterClass.Inner, _: OuterClass.InnerAlias) {}
apache-2.0
CharlinFeng/Reflect
Reflect/Parse4.swift
1
961
// // test4.swift // Reflect // // Created by 成林 on 15/8/23. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation let Student4Dict = ["id":1, "name": "jack", "age": 26,"func": "zoom"] as [String : Any] /** 主要测试以下功能 */ // 模型中有多余的key // 字段映射 // 字段忽略 class Student4: Reflect { var hostID: Int var name:String var age: Int var hobby: String var funcType: String required init() { hostID = 0 name = "" age = 0 hobby = "" funcType = "" } override func mappingDict() -> [String : String]? { return ["hostID": "id", "funcType": "func"] } override func ignorePropertiesForParse() -> [String]? { return ["funcType"] } class func parse(){ let stu4 = Student4.parse(dict: Student4Dict as NSDictionary) print(stu4) } }
mit
kconner/KMCGeigerCounter
ExampleApplication/TableViewController.swift
1
985
// // TableViewController.swift // ExampleApplication // // Created by Kevin Conner on 9/1/18. // Copyright © 2018 Kevin Conner. All rights reserved. // import UIKit final class TableViewController: UITableViewController { @IBOutlet var cellTypeSegmentedControl: UISegmentedControl! // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellType = CellType(rawValue: cellTypeSegmentedControl.selectedSegmentIndex) ?? .expensive let cellIdentifier = cellType.cellIdentifier let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) if let rowConfiguringCell = cell as? RowConfiguring { rowConfiguringCell.configure(at: indexPath.row) } return cell } }
mit
gsempe/ADVOperation
Source/UserNotificationCondition.swift
1
4262
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if os(iOS) import UIKit /** A condition for verifying that we can present alerts to the user via `UILocalNotification` and/or remote notifications. */ struct UserNotificationCondition: OperationCondition { enum Behavior { /// Merge the new `UIUserNotificationSettings` with the `currentUserNotificationSettings`. case Merge /// Replace the `currentUserNotificationSettings` with the new `UIUserNotificationSettings`. case Replace } static let name = "UserNotification" static let currentSettings = "CurrentUserNotificationSettings" static let desiredSettings = "DesiredUserNotificationSettigns" static let isMutuallyExclusive = false let settings: UIUserNotificationSettings let application: UIApplication let behavior: Behavior /** The designated initializer. - parameter settings: The `UIUserNotificationSettings` you wish to be registered. - parameter application: The `UIApplication` on which the `settings` should be registered. - parameter behavior: The way in which the `settings` should be applied to the `application`. By default, this value is `.Merge`, which means that the `settings` will be combined with the existing settings on the `application`. You may also specify `.Replace`, which means the `settings` will overwrite the exisiting settings. */ init(settings: UIUserNotificationSettings, application: UIApplication, behavior: Behavior = .Merge) { self.settings = settings self.application = application self.behavior = behavior } func dependencyForOperation(operation: Operation) -> NSOperation? { return UserNotificationPermissionOperation(settings: settings, application: application, behavior: behavior) } func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { let result: OperationConditionResult let current = application.currentUserNotificationSettings() switch (current, settings) { case (let current?, let settings) where current.contains(settings): result = .Satisfied default: let error = NSError(code: .ConditionFailed, userInfo: [ OperationConditionKey: self.dynamicType.name, self.dynamicType.currentSettings: current ?? NSNull(), self.dynamicType.desiredSettings: settings ]) result = .Failed(error) } completion(result) } } /** A private `Operation` subclass to register a `UIUserNotificationSettings` object with a `UIApplication`, prompting the user for permission if necessary. */ private class UserNotificationPermissionOperation: Operation { let settings: UIUserNotificationSettings let application: UIApplication let behavior: UserNotificationCondition.Behavior init(settings: UIUserNotificationSettings, application: UIApplication, behavior: UserNotificationCondition.Behavior) { self.settings = settings self.application = application self.behavior = behavior super.init() addCondition(AlertPresentation()) } override func execute() { dispatch_async(dispatch_get_main_queue()) { let current = self.application.currentUserNotificationSettings() let settingsToRegister: UIUserNotificationSettings switch (current, self.behavior) { case (let currentSettings?, .Merge): settingsToRegister = currentSettings.settingsByMerging(self.settings) default: settingsToRegister = self.settings } self.application.registerUserNotificationSettings(settingsToRegister) } } } #endif
unlicense
jianghongbing/APIReferenceDemo
UIKit/UIView/UIView/AppDelegate.swift
1
2174
// // AppDelegate.swift // UIView // // Created by pantosoft on 2017/7/6. // Copyright © 2017年 jianghongbing. 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:. } }
mit
wireapp/wire-ios
Wire-iOS/Sources/Authentication/Interface/Helpers/UIAlertController+TOS.swift
1
2403
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import SafariServices import UIKit extension UIAlertController { static func requestTOSApproval(over controller: UIViewController, forTeamAccount: Bool, completion: @escaping (_ approved: Bool) -> Void) { let alert = UIAlertController(title: "registration.terms_of_use.terms.title".localized, message: "registration.terms_of_use.terms.message".localized, preferredStyle: .alert) let viewAction = UIAlertAction(title: "registration.terms_of_use.terms.view".localized, style: .default) { [weak controller] _ in let url = URL.wr_termsOfServicesURL.appendingLocaleParameter let webViewController: BrowserViewController webViewController = BrowserViewController(url: url) webViewController.completion = { [weak controller] in if let controller = controller { UIAlertController.requestTOSApproval(over: controller, forTeamAccount: forTeamAccount, completion: completion) } } controller?.present(webViewController, animated: true) } alert.addAction(viewAction) let cancelAction = UIAlertAction(title: "general.cancel".localized, style: .cancel) { _ in completion(false) } alert.addAction(cancelAction) let acceptAction = UIAlertAction(title: "registration.terms_of_use.accept".localized, style: .default) { _ in completion(true) } alert.addAction(acceptAction) alert.preferredAction = acceptAction controller.present(alert, animated: true, completion: nil) } }
gpl-3.0
whiteath/ReadFoundationSource
TestFoundation/TestXMLDocument.swift
2
26120
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif import CoreFoundation class TestXMLDocument : XCTestCase { static var allTests: [(String, (TestXMLDocument) -> () throws -> Void)] { #if os(OSX) || os(iOS) return [ ("test_basicCreation", test_basicCreation), ("test_nextPreviousNode", test_nextPreviousNode), ("test_xpath", test_xpath), ("test_elementCreation", test_elementCreation), ("test_elementChildren", test_elementChildren), ("test_stringValue", test_stringValue), ("test_objectValue", test_objectValue), ("test_attributes", test_attributes), ("test_comments", test_comments), ("test_processingInstruction", test_processingInstruction), ("test_parseXMLString", test_parseXMLString), ("test_prefixes", test_prefixes), // ("test_validation_success", test_validation_success), // ("test_validation_failure", test_validation_failure), ("test_dtd", test_dtd), ("test_documentWithDTD", test_documentWithDTD), ("test_dtd_attributes", test_dtd_attributes), ("test_documentWithEncodingSetDoesntCrash", test_documentWithEncodingSetDoesntCrash), ("test_nodeFindingWithNamespaces", test_nodeFindingWithNamespaces), ("test_createElement", test_createElement), ("test_addNamespace", test_addNamespace), ("test_removeNamespace", test_removeNamespace), ] #else // On Linux, currently the tests that rely on NSError are segfaulting in swift_dynamicCast return [ ("test_basicCreation", test_basicCreation), ("test_nextPreviousNode", test_nextPreviousNode), ("test_xpath", test_xpath), ("test_elementCreation", test_elementCreation), ("test_elementChildren", test_elementChildren), ("test_stringValue", test_stringValue), ("test_objectValue", test_objectValue), ("test_attributes", test_attributes), ("test_comments", test_comments), ("test_processingInstruction", test_processingInstruction), ("test_parseXMLString", test_parseXMLString), ("test_prefixes", test_prefixes), // ("test_validation_success", test_validation_success), // ("test_validation_failure", test_validation_failure), ("test_dtd", test_dtd), // ("test_documentWithDTD", test_documentWithDTD), ("test_dtd_attributes", test_dtd_attributes), ("test_documentWithEncodingSetDoesntCrash", test_documentWithEncodingSetDoesntCrash), ("test_nodeFindingWithNamespaces", test_nodeFindingWithNamespaces), ("test_createElement", test_createElement), ("test_addNamespace", test_addNamespace), ("test_removeNamespace", test_removeNamespace), ] #endif } func test_basicCreation() { let doc = XMLDocument(rootElement: nil) XCTAssert(doc.version == "1.0", "expected 1.0, got \(String(describing: doc.version))") doc.version = "1.1" XCTAssert(doc.version == "1.1", "expected 1.1, got \(String(describing: doc.version))") let node = XMLElement(name: "Hello", uri: "http://www.example.com") doc.setRootElement(node) let element = doc.rootElement()! XCTAssert(element === node) } func test_createElement() throws { let element = try XMLElement(xmlString: "<D:propfind xmlns:D=\"DAV:\"><D:prop></D:prop></D:propfind>") XCTAssert(element.name! == "D:propfind") XCTAssert(element.rootDocument == nil) if let namespace = element.namespaces?.first { XCTAssert(namespace.prefix == "D") XCTAssert(namespace.stringValue == "DAV:") } else { XCTFail("Namespace was not parsed correctly") } if let child = element.elements(forName: "D:prop").first { XCTAssert(child.localName == "prop") XCTAssert(child.prefix == "D") XCTAssert(child.name == "D:prop") } else { XCTFail("Child element was not parsed correctly!") } } func test_nextPreviousNode() { let doc = XMLDocument(rootElement: nil) let node = XMLElement(name: "Hello", uri: "http://www.example.com") let fooNode = XMLElement(name: "Foo") let barNode = XMLElement(name: "Bar") let bazNode = XMLElement(name: "Baz") doc.setRootElement(node) node.addChild(fooNode) fooNode.addChild(bazNode) node.addChild(barNode) XCTAssert(doc.next === node) XCTAssert(doc.next?.next === fooNode) XCTAssert(doc.next?.next?.next === bazNode) XCTAssert(doc.next?.next?.next?.next === barNode) XCTAssert(barNode.previous === bazNode) XCTAssert(barNode.previous?.previous === fooNode) XCTAssert(barNode.previous?.previous?.previous === node) XCTAssert(barNode.previous?.previous?.previous?.previous === doc) } func test_xpath() throws { let doc = XMLDocument(rootElement: nil) let foo = XMLElement(name: "foo") let bar1 = XMLElement(name: "bar") let bar2 = XMLElement(name: "bar") let bar3 = XMLElement(name: "bar") let baz = XMLElement(name: "baz") doc.setRootElement(foo) foo.addChild(bar1) foo.addChild(bar2) foo.addChild(bar3) bar2.addChild(baz) XCTAssertEqual(baz.xPath, "/foo/bar[2]/baz") let baz2 = XMLElement(name: "/baz") bar2.addChild(baz2) XCTAssertEqual(baz.xPath, "/foo/bar[2]/baz") XCTAssertEqual(try! doc.nodes(forXPath:baz.xPath!).first, baz) let nodes = try! doc.nodes(forXPath:"/foo/bar") XCTAssertEqual(nodes.count, 3) XCTAssertEqual(nodes[0], bar1) XCTAssertEqual(nodes[1], bar2) XCTAssertEqual(nodes[2], bar3) let xmlString = """ <?xml version="1.0" encoding="utf-8" standalone="yes"?> <D:propfind xmlns:D="DAV:"> <D:prop> <D:getlastmodified></D:getlastmodified> <D:getcontentlength></D:getcontentlength> <D:creationdate></D:creationdate> <D:resourcetype></D:resourcetype> </D:prop> </D:propfind> """ let namespaceDoc = try XMLDocument(xmlString: xmlString, options: []) let propNodes = try namespaceDoc.nodes(forXPath: "//D:prop") if let propNode = propNodes.first { XCTAssert(propNode.name == "D:prop") } else { XCTAssert(false, "propNode should have existed, but was nil") } } func test_elementCreation() { let element = XMLElement(name: "test", stringValue: "This is my value") XCTAssertEqual(element.xmlString, "<test>This is my value</test>") XCTAssertEqual(element.children?.count, 1) } func test_elementChildren() { let element = XMLElement(name: "root") let foo = XMLElement(name: "foo") let bar = XMLElement(name: "bar") let bar2 = bar.copy() as! XMLElement element.addChild(foo) element.addChild(bar) element.addChild(bar2) XCTAssertEqual(element.elements(forName:"bar"), [bar, bar2]) XCTAssertFalse(element.elements(forName:"foo").contains(bar)) XCTAssertFalse(element.elements(forName:"foo").contains(bar2)) let baz = XMLElement(name: "baz") element.insertChild(baz, at: 2) XCTAssertEqual(element.children?[2], baz) foo.detach() bar.detach() element.insertChildren([foo, bar], at: 1) XCTAssertEqual(element.children?[1], foo) XCTAssertEqual(element.children?[2], bar) XCTAssertEqual(element.children?[0], baz) let faz = XMLElement(name: "faz") element.replaceChild(at: 2, with: faz) XCTAssertEqual(element.children?[2], faz) for node in [foo, bar, baz, bar2, faz] { node.detach() } XCTAssert(element.children?.count == 0) element.setChildren([foo, bar, baz, bar2, faz]) XCTAssert(element.children?.count == 5) } func test_stringValue() { let element = XMLElement(name: "root") let foo = XMLElement(name: "foo") element.addChild(foo) element.stringValue = "Hello!<evil/>" XCTAssertEqual(element.xmlString, "<root>Hello!&lt;evil/&gt;</root>") XCTAssertEqual(element.stringValue, "Hello!<evil/>", element.stringValue ?? "stringValue unexpectedly nil") element.stringValue = nil // let doc = XMLDocument(rootElement: element) // xmlCreateIntSubset(xmlDocPtr(doc._xmlNode), "test.dtd", nil, nil) // xmlAddDocEntity(xmlDocPtr(doc._xmlNode), "author", Int32(XML_INTERNAL_GENERAL_ENTITY.rawValue), nil, nil, "Robert Thompson") // let author = XMLElement(name: "author") // doc.rootElement()?.addChild(author) // author.setStringValue("&author;", resolvingEntities: true) // XCTAssertEqual(author.stringValue, "Robert Thompson", author.stringValue ?? "") } func test_objectValue() { let element = XMLElement(name: "root") let dict: [String: String] = ["hello": "world"] element.objectValue = dict /// - Todo: verify this behavior // id to Any conversion changed descriptions so this now is "<root>[\"hello\": \"world\"]</root>" // XCTAssertEqual(element.xmlString, "<root>{\n hello = world;\n}</root>", element.xmlString) } func test_attributes() { let element = XMLElement(name: "root") let attribute = XMLNode.attribute(withName: "color", stringValue: "#ff00ff") as! XMLNode element.addAttribute(attribute) XCTAssertEqual(element.xmlString, "<root color=\"#ff00ff\"></root>", element.xmlString) element.removeAttribute(forName:"color") XCTAssertEqual(element.xmlString, "<root></root>", element.xmlString) element.addAttribute(attribute) let otherAttribute = XMLNode.attribute(withName: "foo", stringValue: "bar") as! XMLNode element.addAttribute(otherAttribute) guard let attributes = element.attributes else { XCTFail() return } XCTAssertEqual(attributes.count, 2) XCTAssertEqual(attributes.first, attribute) XCTAssertEqual(attributes.last, otherAttribute) let barAttribute = XMLNode.attribute(withName: "bar", stringValue: "buz") as! XMLNode let bazAttribute = XMLNode.attribute(withName: "baz", stringValue: "fiz") as! XMLNode element.attributes = [barAttribute, bazAttribute] XCTAssertEqual(element.attributes?.count, 2) XCTAssertEqual(element.attributes?.first, barAttribute) XCTAssertEqual(element.attributes?.last, bazAttribute) element.setAttributesWith(["hello": "world", "foobar": "buzbaz"]) XCTAssertEqual(element.attribute(forName:"hello")?.stringValue, "world", "\(element.attribute(forName:"hello")?.stringValue as Optional)") XCTAssertEqual(element.attribute(forName:"foobar")?.stringValue, "buzbaz", "\(element.attributes ?? [])") } func test_comments() { let element = XMLElement(name: "root") let comment = XMLNode.comment(withStringValue:"Here is a comment") as! XMLNode element.addChild(comment) XCTAssertEqual(element.xmlString, "<root><!--Here is a comment--></root>") } func test_processingInstruction() { let document = XMLDocument(rootElement: XMLElement(name: "root")) let pi = XMLNode.processingInstruction(withName:"xml-stylesheet", stringValue: "type=\"text/css\" href=\"style.css\"") as! XMLNode document.addChild(pi) XCTAssertEqual(pi.xmlString, "<?xml-stylesheet type=\"text/css\" href=\"style.css\"?>") } func test_parseXMLString() throws { let string = "<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE test.dtd [\n <!ENTITY author \"Robert Thompson\">\n ]><root><author>&author;</author></root>" let doc = try XMLDocument(xmlString: string, options: [.nodeLoadExternalEntitiesNever]) XCTAssert(doc.childCount == 1) XCTAssertEqual(doc.rootElement()?.children?[0].stringValue, "Robert Thompson") guard let testDataURL = testBundle().url(forResource: "NSXMLDocumentTestData", withExtension: "xml") else { XCTFail("Could not find XML test data") return } let newDoc = try XMLDocument(contentsOf: testDataURL, options: []) XCTAssertEqual(newDoc.rootElement()?.name, "root") let root = newDoc.rootElement()! let children = root.children! XCTAssertEqual(children[0].stringValue, "Hello world", children[0].stringValue!) XCTAssertEqual(children[1].children?[0].stringValue, "I'm here", (children[1].children?[0].stringValue)!) doc.insertChild(XMLElement(name: "body"), at: 1) XCTAssertEqual(doc.children?[1].name, "body") XCTAssertEqual(doc.children?[2].name, "root", (doc.children?[2].name)!) } func test_prefixes() { let element = XMLElement(name: "xml:root") XCTAssertEqual(element.prefix, "xml") XCTAssertEqual(element.localName, "root") } func test_addNamespace() { let doc = XMLDocument(rootElement: XMLElement(name: "Foo")) let ns = XMLNode.namespace(withName: "F", stringValue: "http://example.com/fakenamespace") as! XMLNode doc.rootElement()?.addNamespace(ns) XCTAssert((doc.rootElement()?.namespaces ?? []).map({ $0.stringValue ?? "foo" }).contains(ns.stringValue ?? "bar"), "namespaces didn't include the added namespace!") XCTAssert(doc.rootElement()?.uri == "http://example.com/fakenamespace", "uri was \(doc.rootElement()?.uri ?? "null") instead of http://example.com/fakenamespace") let otherNS = XMLNode.namespace(withName: "R", stringValue: "http://example.com/rnamespace") as! XMLNode doc.rootElement()?.addNamespace(otherNS) XCTAssert((doc.rootElement()?.namespaces ?? []).map({ $0.stringValue ?? "foo" }).contains(ns.stringValue ?? "bar"), "lost original namespace") XCTAssert((doc.rootElement()?.namespaces ?? []).map({ $0.stringValue ?? "foo" }).contains(otherNS.stringValue ?? "bar"), "Lost new namespace") doc.rootElement()?.addNamespace(XMLNode.namespace(withName: "R", stringValue: "http://example.com/rnamespace") as! XMLNode) XCTAssert(doc.rootElement()?.namespaces?.count == 2, "incorrectly added a namespace with duplicate name!") let otherDoc = XMLDocument(rootElement: XMLElement(name: "Bar")) otherDoc.rootElement()?.namespaces = [XMLNode.namespace(withName: "R", stringValue: "http://example.com/rnamespace") as! XMLNode, XMLNode.namespace(withName: "F", stringValue: "http://example.com/fakenamespace") as! XMLNode] XCTAssert(otherDoc.rootElement()?.namespaces?.count == 2) XCTAssert(otherDoc.rootElement()?.namespaces?.flatMap({ $0.name })[0] == "R" && otherDoc.rootElement()?.namespaces?.flatMap({ $0.name })[1] == "F") otherDoc.rootElement()?.namespaces = nil XCTAssert((otherDoc.rootElement()?.namespaces?.count ?? 0) == 0) } func test_removeNamespace() { let doc = XMLDocument(rootElement: XMLElement(name: "Foo")) let ns = XMLNode.namespace(withName: "F", stringValue: "http://example.com/fakenamespace") as! XMLNode let otherNS = XMLNode.namespace(withName: "R", stringValue: "http://example.com/rnamespace") as! XMLNode doc.rootElement()?.addNamespace(ns) doc.rootElement()?.addNamespace(otherNS) XCTAssert(doc.rootElement()?.namespaces?.count == 2) doc.rootElement()?.removeNamespace(forPrefix: "F") XCTAssert(doc.rootElement()?.namespaces?.count == 1) XCTAssert(doc.rootElement()?.namespaces?.first?.name == "R") } /* * <rdar://31567922> Re-enable these tests in a way that does not depend on the internet. func test_validation_success() throws { let validString = "<?xml version=\"1.0\" standalone=\"yes\"?><!DOCTYPE foo [ <!ELEMENT foo (#PCDATA)> ]><foo>Hello world</foo>" do { let doc = try XMLDocument(xmlString: validString, options: []) try doc.validate() } catch { XCTFail("\(error)") } let plistDocString = "<?xml version='1.0' encoding='utf-8'?><!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"> <plist version='1.0'><dict><key>MyKey</key><string>Hello!</string></dict></plist>" let plistDoc = try XMLDocument(xmlString: plistDocString, options: []) do { try plistDoc.validate() XCTAssert(plistDoc.rootElement()?.name == "plist") let plist = try PropertyListSerialization.propertyList(from: plistDoc.xmlData, options: [], format: nil) as! [String: Any] XCTAssert((plist["MyKey"] as? String) == "Hello!") } catch let nsError as NSError { XCTFail("\(nsError.userInfo)") } } func test_validation_failure() throws { let xmlString = "<?xml version=\"1.0\" standalone=\"yes\"?><!DOCTYPE foo [ <!ELEMENT img EMPTY> ]><foo><img>not empty</img></foo>" do { let doc = try XMLDocument(xmlString: xmlString, options: []) try doc.validate() XCTFail("Should have thrown") } catch let nsError as NSError { XCTAssert(nsError.code == XMLParser.ErrorCode.internalError.rawValue) XCTAssert(nsError.domain == XMLParser.errorDomain) XCTAssert((nsError.userInfo[NSLocalizedDescriptionKey] as! String).contains("Element img was declared EMPTY this one has content")) } let plistDocString = "<?xml version='1.0' encoding='utf-8'?><!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"> <plist version='1.0'><dict><key>MyKey</key><string>Hello!</string><key>MyBooleanThing</key><true>foobar</true></dict></plist>" let plistDoc = try XMLDocument(xmlString: plistDocString, options: []) do { try plistDoc.validate() XCTFail("Should have thrown!") } catch let error as NSError { XCTAssert((error.userInfo[NSLocalizedDescriptionKey] as! String).contains("Element true was declared EMPTY this one has content")) } }*/ func test_dtd() throws { let node = XMLNode.dtdNode(withXMLString:"<!ELEMENT foo (#PCDATA)>") as! XMLDTDNode XCTAssert(node.name == "foo") let dtd = try XMLDTD(contentsOf: testBundle().url(forResource: "PropertyList-1.0", withExtension: "dtd")!, options: []) // dtd.systemID = testBundle().URLForResource("PropertyList-1.0", withExtension: "dtd")?.absoluteString dtd.name = "plist" // dtd.publicID = "-//Apple//DTD PLIST 1.0//EN" let plistNode = dtd.elementDeclaration(forName:"plist") XCTAssert(plistNode?.name == "plist") let plistObjectNode = dtd.entityDeclaration(forName:"plistObject") XCTAssert(plistObjectNode?.name == "plistObject") XCTAssert(plistObjectNode?.stringValue == "(array | data | date | dict | real | integer | string | true | false )") let plistAttribute = dtd.attributeDeclaration(forName:"version", elementName: "plist") XCTAssert(plistAttribute?.name == "version") let doc = try XMLDocument(xmlString: "<?xml version='1.0' encoding='utf-8'?><plist version='1.0'><dict><key>hello</key><string>world</string></dict></plist>", options: []) doc.dtd = dtd do { try doc.validate() } catch let error as NSError { XCTFail("\(error.userInfo)") } let amp = XMLDTD.predefinedEntityDeclaration(forName:"amp") XCTAssert(amp?.name == "amp", amp?.name ?? "") XCTAssert(amp?.stringValue == "&", amp?.stringValue ?? "") if let entityNode = XMLNode.dtdNode(withXMLString:"<!ENTITY author 'Robert Thompson'>") as? XMLDTDNode { XCTAssert(entityNode.name == "author") XCTAssert(entityNode.stringValue == "Robert Thompson") } let elementDecl = XMLDTDNode(kind: .elementDeclaration) elementDecl.name = "MyElement" elementDecl.stringValue = "(#PCDATA | array)*" XCTAssert(elementDecl.stringValue == "(#PCDATA | array)*", elementDecl.stringValue ?? "nil string value") XCTAssert(elementDecl.name == "MyElement") } func test_documentWithDTD() throws { let doc = try XMLDocument(contentsOf: testBundle().url(forResource: "NSXMLDTDTestData", withExtension: "xml")!, options: []) let dtd = doc.dtd XCTAssert(dtd?.name == "root") let notation = dtd?.notationDeclaration(forName:"myNotation") notation?.detach() XCTAssert(notation?.name == "myNotation") XCTAssert(notation?.systemID == "http://www.example.com", notation?.systemID ?? "nil system id!") do { try doc.validate() } catch { XCTFail("\(error)") } let root = dtd?.elementDeclaration(forName:"root") root?.stringValue = "(#PCDATA)" do { try doc.validate() XCTFail("should have thrown") } catch let error as NSError { XCTAssert(error.code == XMLParser.ErrorCode.internalError.rawValue) } catch { XCTFail("\(error)") } } func test_dtd_attributes() throws { let doc = try XMLDocument(contentsOf: testBundle().url(forResource: "NSXMLDTDTestData", withExtension: "xml")!, options: []) let dtd = doc.dtd! let attrDecl = dtd.attributeDeclaration(forName: "print", elementName: "foo")! XCTAssert(attrDecl.dtdKind == .enumerationAttribute) } func test_documentWithEncodingSetDoesntCrash() throws { weak var weakDoc: XMLDocument? = nil func makeSureDocumentIsAllocatedAndFreed() { let doc = XMLDocument(rootElement: XMLElement(name: "test")) doc.characterEncoding = "UTF-8" weakDoc = doc } makeSureDocumentIsAllocatedAndFreed() XCTAssertNil(weakDoc, "document not freed even through it should have") } func test_nodeFindingWithNamespaces() throws { let xmlString = """ <?xml version="1.0" encoding="utf-8" standalone="yes"?> <D:propfind xmlns:D="DAV:"> <D:prop> <D:getlastmodified></D:getlastmodified> <D:getcontentlength></D:getcontentlength> <D:creationdate></D:creationdate> <D:resourcetype></D:resourcetype> </D:prop> </D:propfind> """ let doc = try XMLDocument(xmlString: xmlString, options: []) let namespace = (doc.rootElement()?.namespaces?.first)! XCTAssert(namespace.kind == .namespace, "The node was not a namespace but was a \(namespace.kind)") XCTAssert(namespace.stringValue == "DAV:", "expected a string value of DAV: got \(namespace.stringValue as Any)") XCTAssert(namespace.name == "D", "expected a name of D, got \(namespace.name as Any)") let newNS = XMLNode.namespace(withName: "R", stringValue: "http://apple.com") as! XMLNode XCTAssert(newNS.name == "R", "expected name R, got name \(newNS.name as Any)") XCTAssert(newNS.stringValue == "http://apple.com", "expected stringValue http://apple.com, got stringValue \(newNS.stringValue as Any)") newNS.stringValue = "FOO:" XCTAssert(newNS.stringValue == "FOO:") newNS.name = "F" XCTAssert(newNS.name == "F") let root = doc.rootElement()! XCTAssert(root.localName == "propfind") XCTAssert(root.name == "D:propfind") XCTAssert(root.prefix == "D") let node = doc.findFirstChild(named: "prop") XCTAssert(node != nil, "failed to find existing node") XCTAssert(node?.localName == "prop") XCTAssert(doc.rootElement()?.elements(forLocalName: "prop", uri: "DAV:").first?.name == "D:prop", "failed to get elements, got \(doc.rootElement()?.elements(forLocalName: "prop", uri: "DAV:").first as Any)") } } fileprivate extension XMLNode { fileprivate func findFirstChild(named name: String) -> XMLNode? { guard let children = self.children else { return nil } for child in children { if let childName = child.localName { if childName == name { return child } } if let result = child.findFirstChild(named: name) { return result } } return nil } }
apache-2.0
exponent/exponent
ios/vendored/sdk44/@stripe/stripe-react-native/ios/ApplePayButtonManager.swift
2
304
import Foundation @objc(ABI44_0_0ApplePayButtonManager) class ApplePayButtonManager: ABI44_0_0RCTViewManager { override func view() -> UIView! { return ApplePayButtonView(frame: CGRect.init()) } override class func requiresMainQueueSetup() -> Bool { return true } }
bsd-3-clause
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/examples/BigHills/BigHills/Source/Controller/BigHillsViewController.swift
1
5670
// // BigHillsViewController.swift // BigHills // import CoreData import MapKit import UIKit class BigHillsViewController: UIViewController, HillDetailViewControllerDelegate, MKMapViewDelegate, NSFetchedResultsControllerDelegate { // MARK: IBAction @IBAction private func addHill(_ sender: AnyObject) { performSegue(withIdentifier: "CreateHillSegue", sender:self) } @IBAction private func deleteSelectedHill(_ sender: AnyObject) { if let hill = mapView.selectedAnnotations.last as? Hill { do { try HillService.shared.deleteHill(hill) } catch let error { fatalError("Failed to delete selected hill \(error)") } } } @IBAction private func connectTheDots(_ sender: AnyObject) { if let somePolylineOverlay = polylineOverlay { mapView.remove(somePolylineOverlay) polylineOverlay = nil connectTheDotsButton.title = "Connect the Dots" } else { // Add the overlay if let visibleHills = mapView.annotations(in: mapView.visibleMapRect) as? Set<Hill> { if visibleHills.isEmpty { let alertController = UIAlertController(title: "No Hills!", message: "There are no hills on screen to connect", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } else { var points = visibleHills.reduce([]) { (workingPoints, element) in return workingPoints + [element.coordinate] } let polylineOverlay = MKPolyline(coordinates: &points, count: points.count) mapView.add(polylineOverlay) self.polylineOverlay = polylineOverlay connectTheDotsButton.title = "Remove Overlay" } } } } // MARK: IBAction (Unwind Segue) @IBAction private func createHillFinished(_ sender: UIStoryboardSegue) { // Intentionally left blank } // MARK: HillDetailViewController func hillDetailViewController(_ viewController: HillDetailViewController, didChange hill: Hill) { mapView.deselectAnnotation(hill, animated: false) mapView.selectAnnotation(hill, animated: false) } // MARK: MKMapViewDelegate func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView: MKAnnotationView if let someAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "HillAnnotation") { annotationView = someAnnotationView } else { let pinAnnotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:"HillAnnotation") pinAnnotationView.pinTintColor = .green pinAnnotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) annotationView = pinAnnotationView } annotationView.annotation = annotation annotationView.canShowCallout = true annotationView.isDraggable = true return annotationView; } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let somePolyline = overlay as! MKPolyline let polyLineRenderer = MKPolylineRenderer(polyline: somePolyline) polyLineRenderer.strokeColor = UIColor.green polyLineRenderer.lineWidth = 5.0 polyLineRenderer.alpha = 0.5 return polyLineRenderer } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let someHill = view.annotation as? Hill { selectedHill = someHill performSegue(withIdentifier: "HillDetailSegue", sender:self) } } // MARK: NSFetchedResultsControllerDelegate func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if let hill = anObject as? Hill { if type == .delete { mapView.removeAnnotation(hill) } else if type == .insert { mapView.addAnnotation(hill) } } } // MARK: Private func updateFetchedResultsController() { fetchedResultsController = try? HillService.shared.hillsFetchedResultsController(with: self) if let someObjects = fetchedResultsController?.fetchedObjects { mapView.addAnnotations(someObjects) } } // MARK: View Management override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case .some("HillDetailSegue"): let hillDetailViewController = segue.destination as! HillDetailViewController hillDetailViewController.selectedHill = selectedHill hillDetailViewController.delegate = self case .some("CreateHillSegue"): let navigationController = segue.destination as! UINavigationController let hillDetailViewController = navigationController.topViewController as! HillDetailViewController hillDetailViewController.updateHill(withLatitude: mapView.centerCoordinate.latitude, andLongitude: mapView.centerCoordinate.longitude) hillDetailViewController.delegate = self default: super.prepare(for: segue, sender: sender) } } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() mapView.visibleMapRect = BigHillsViewController.defaultMapRect updateFetchedResultsController() } // MARK: Properties (IBOutlet) @IBOutlet private var mapView: MKMapView! @IBOutlet private var connectTheDotsButton: UIBarButtonItem! // MARK: Properties (Private) private var fetchedResultsController: NSFetchedResultsController<Hill>? private var polylineOverlay: MKPolyline? private var selectedHill: Hill? private var observationToken: AnyObject? // MARK: Properties (Private Static Constant) private static let defaultMapRect = MKMapRect(origin: MKMapPoint(x: 41984000.0, y: 97083392.0), size: MKMapSize(width: 655360.0, height: 942080.0)) }
gpl-3.0
Monnoroch/Cuckoo
Generator/Dependencies/SourceKitten/Source/SourceKittenFramework/Dictionary+Merge.swift
1
699
// // Dictionary+Merge.swift // SourceKitten // // Created by JP Simard on 2015-01-08. // Copyright (c) 2015 SourceKitten. All rights reserved. // /** Returns a new dictionary by adding the entries of dict2 into dict1, overriding if the key exists. - parameter dict1: Dictionary to merge into. - parameter dict2: Dictionary to merge from (optional). - returns: A new dictionary by adding the entries of dict2 into dict1, overriding if the key exists. */ internal func merge<K,V>(_ dict1: [K: V], _ dict2: [K: V]?) -> [K: V] { var mergedDict = dict1 if let dict2 = dict2 { for (key, value) in dict2 { mergedDict[key] = value } } return mergedDict }
mit
volodg/LotterySRV
Sources/App/Controllers/LocationsController.swift
1
684
// // LocationsController.swift // Bits // // Created by Volodymyr Gorbenko on 18/6/17. // class LocationsController: ResourceRepresentable { required init() {} /// When users call 'GET' on '/lotteries' /// it should return an index of all available posts func index(req: Request) throws -> ResponseRepresentable { return try Location.all().makeJSON() } func makeResource() -> Resource<Lottery> { return Resource(index: index) } } /// Since PostController doesn't require anything to /// be initialized we can conform it to EmptyInitializable. /// /// This will allow it to be passed by type. extension LocationsController: EmptyInitializable { }
mit
up-n-down/Up-N-Down
Finder Sync Extension/FIFinderSyncControllerExtensions.swift
1
832
// // FIFinderSyncController.swift // Up N Down // // Created by Thomas Paul Mann on 16/10/2016. // Copyright © 2016 Thomas Paul Mann. All rights reserved. // import FinderSync extension FIFinderSyncController { /// Register the badge for further usage. func register(_ badge: Badge) { self.setBadgeImage(badge.image, label: badge.identifier, forBadgeIdentifier: badge.identifier) } var selectedItemsRepresentation: String { var selectedItems = "" if let selectedItemURLs = self.selectedItemURLs() { if selectedItemURLs.count == 1 { selectedItems = "”\(selectedItemURLs[0].lastPathComponent)”" } else { selectedItems.append("\(selectedItemURLs.count) Items") } } return selectedItems } }
gpl-3.0
jiayoufang/LearnSwift
SwiftTips/SwiftTips/MyPrintClass.swift
1
378
// // MyPrintClass.swift // SwiftTips // // Created by fangjiayou on 2016/12/9. // Copyright © 2016年 Ivan. All rights reserved. // import Foundation class MyPrintClass { var num: Int init() { num = 1 } } extension MyPrintClass: CustomDebugStringConvertible{ var debugDescription: String{ return "MyPrintClass Num : \(self.num)" } }
mit
tsolomko/SWCompression
Sources/LZMA/LZMADecoder.swift
1
11825
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData struct LZMADecoder { private let byteReader: LittleEndianByteReader var properties = LZMAProperties() var uncompressedSize = -1 /// An array for storing output data. var out = [UInt8]() // `out` array also serves as dictionary and out window. private var dictStart = 0 private var dictEnd = 0 private var dictSize: Int { return self.properties.dictionarySize } private var lc: Int { return self.properties.lc } private var lp: Int { return self.properties.lp } private var pb: Int { return self.properties.pb } private var rangeDecoder = LZMARangeDecoder() private var posSlotDecoder = [LZMABitTreeDecoder]() private var alignDecoder = LZMABitTreeDecoder(numBits: LZMAConstants.numAlignBits) private var lenDecoder = LZMALenDecoder() private var repLenDecoder = LZMALenDecoder() /** For literal decoding we need `1 << (lc + lp)` amount of tables. Each table contains 0x300 probabilities. */ private var literalProbs = [[Int]]() /** Array with all probabilities: - 0..<192: isMatch - 193..<205: isRep - 205..<217: isRepG0 - 217..<229: isRepG1 - 229..<241: isRepG2 - 241..<433: isRep0Long */ private var probabilities = [Int]() private var posDecoders = [Int]() // 'Distance history table'. private var rep0 = 0 private var rep1 = 0 private var rep2 = 0 private var rep3 = 0 /// Used to select exact variable from 'IsRep', 'IsRepG0', 'IsRepG1' and 'IsRepG2' arrays. private var state = 0 init(_ byteReader: LittleEndianByteReader) { self.byteReader = byteReader } /// Resets state properties and various sub-decoders of LZMA decoder. mutating func resetStateAndDecoders() { self.state = 0 self.rep0 = 0 self.rep1 = 0 self.rep2 = 0 self.rep3 = 0 self.probabilities = Array(repeating: LZMAConstants.probInitValue, count: 2 * 192 + 4 * 12) self.literalProbs = Array(repeating: Array(repeating: LZMAConstants.probInitValue, count: 0x300), count: 1 << (lc + lp)) self.posSlotDecoder = [] for _ in 0..<LZMAConstants.numLenToPosStates { self.posSlotDecoder.append(LZMABitTreeDecoder(numBits: 6)) } self.alignDecoder = LZMABitTreeDecoder(numBits: LZMAConstants.numAlignBits) self.posDecoders = Array(repeating: LZMAConstants.probInitValue, count: 1 + LZMAConstants.numFullDistances - LZMAConstants.endPosModelIndex) self.lenDecoder = LZMALenDecoder() self.repLenDecoder = LZMALenDecoder() } mutating func resetDictionary() { self.dictStart = self.dictEnd } /// Main LZMA (algorithm) decoder function. mutating func decode() throws { // First, we need to initialize Rande Decoder. self.rangeDecoder = try LZMARangeDecoder(byteReader) // Main decoding cycle. while true { // If uncompressed size was defined and everything is unpacked then stop. if uncompressedSize == 0 && rangeDecoder.isFinishedOK { break } let posState = out.count & ((1 << pb) - 1) if rangeDecoder.decode(bitWithProb: &probabilities[(state << LZMAConstants.numPosBitsMax) + posState]) == 0 { if uncompressedSize == 0 { throw LZMAError.exceededUncompressedSize } // DECODE LITERAL: /// Previous literal (zero, if there was none). let prevByte = dictEnd == 0 ? 0 : self.byte(at: 1).toInt() /// Decoded symbol. Initial value is 1. var symbol = 1 /** Index of table with literal probabilities. It is based on the context which consists of: - `lc` high bits of from previous literal. If there were none, i.e. it is the first literal, then this part is skipped. - `lp` low bits from current position in output. */ let litState = ((out.count & ((1 << lp) - 1)) << lc) + (prevByte >> (8 - lc)) // If state is greater than 7 we need to do additional decoding with 'matchByte'. if state >= 7 { /** Byte in output at position that is the `distance` bytes before current position, where the `distance` is the distance from the latest decoded match. */ var matchByte = self.byte(at: rep0 + 1) repeat { let matchBit = ((matchByte >> 7) & 1).toInt() matchByte <<= 1 let bit = rangeDecoder.decode(bitWithProb: &literalProbs[litState][((1 + matchBit) << 8) + symbol]) symbol = (symbol << 1) | bit if matchBit != bit { break } } while symbol < 0x100 } while symbol < 0x100 { symbol = (symbol << 1) | rangeDecoder.decode(bitWithProb: &literalProbs[litState][symbol]) } let byte = (symbol - 0x100).toUInt8() uncompressedSize -= 1 self.put(byte) // END. // Finally, we need to update `state`. if state < 4 { state = 0 } else if state < 10 { state -= 3 } else { state -= 6 } continue } var len: Int if rangeDecoder.decode(bitWithProb: &probabilities[193 + state]) != 0 { // REP MATCH CASE if uncompressedSize == 0 { throw LZMAError.exceededUncompressedSize } if dictEnd == 0 { throw LZMAError.windowIsEmpty } if rangeDecoder.decode(bitWithProb: &probabilities[205 + state]) == 0 { // (We use last distance from 'distance history table'). if rangeDecoder.decode(bitWithProb: &probabilities[241 + (state << LZMAConstants.numPosBitsMax) + posState]) == 0 { // SHORT REP MATCH CASE state = state < 7 ? 9 : 11 let byte = self.byte(at: rep0 + 1) self.put(byte) uncompressedSize -= 1 continue } } else { // REP MATCH CASE // (It means that we use distance from 'distance history table'). // So the following code selectes one distance from history... // based on the binary data. let dist: Int if rangeDecoder.decode(bitWithProb: &probabilities[217 + state]) == 0 { dist = rep1 } else { if rangeDecoder.decode(bitWithProb: &probabilities[229 + state]) == 0 { dist = rep2 } else { dist = rep3 rep3 = rep2 } rep2 = rep1 } rep1 = rep0 rep0 = dist } len = repLenDecoder.decode(with: &rangeDecoder, posState: posState) state = state < 7 ? 8 : 11 } else { // SIMPLE MATCH CASE // First, we need to move history of distance values. rep3 = rep2 rep2 = rep1 rep1 = rep0 len = lenDecoder.decode(with: &rangeDecoder, posState: posState) state = state < 7 ? 7 : 10 // DECODE DISTANCE: /// Is used to define context for distance decoding. var lenState = len if lenState > LZMAConstants.numLenToPosStates - 1 { lenState = LZMAConstants.numLenToPosStates - 1 } /// Defines decoding scheme for distance value. let posSlot = posSlotDecoder[lenState].decode(with: &rangeDecoder) if posSlot < 4 { // If `posSlot` is less than 4 then distance has defined value (no need to decode). // And distance is actually equal to `posSlot`. rep0 = posSlot } else { let numDirectBits = (posSlot >> 1) - 1 var dist = (2 | (posSlot & 1)) << numDirectBits if posSlot < LZMAConstants.endPosModelIndex { // In this case we need a sequence of bits decoded with bit tree... // ...(separate trees for different `posSlot` values)... // ...and 'Reverse' scheme to get distance value. dist += LZMABitTreeDecoder.bitTreeReverseDecode(probs: &posDecoders, startIndex: dist - posSlot, bits: numDirectBits, &rangeDecoder) } else { // Middle bits of distance are decoded as direct bits from RangeDecoder. dist += rangeDecoder.decode(directBits: (numDirectBits - LZMAConstants.numAlignBits)) << LZMAConstants.numAlignBits // Low 4 bits are decoded with a bit tree decoder (called 'AlignDecoder') using "Reverse" scheme. dist += alignDecoder.reverseDecode(with: &rangeDecoder) } rep0 = dist } // END. // Check if finish marker is encountered. // Distance value of 2^32 is used to indicate 'End of Stream' marker. if UInt32(rep0) == 0xFFFFFFFF { guard rangeDecoder.isFinishedOK else { throw LZMAError.rangeDecoderFinishError } break } if uncompressedSize == 0 { throw LZMAError.exceededUncompressedSize } if rep0 >= dictSize || (rep0 > dictEnd && dictEnd < dictSize) { throw LZMAError.notEnoughToRepeat } } // Converting from zero-based length of the match to the real one. len += LZMAConstants.matchMinLen if uncompressedSize > -1 && uncompressedSize < len { throw LZMAError.repeatWillExceed } for _ in 0..<len { let byte = self.byte(at: rep0 + 1) self.put(byte) uncompressedSize -= 1 } } } // MARK: Dictionary (out window) related functions. mutating func put(_ byte: UInt8) { out.append(byte) dictEnd += 1 if dictEnd - dictStart == dictSize { dictStart += 1 } } private func byte(at distance: Int) -> UInt8 { return out[distance <= dictEnd ? dictEnd - distance : dictSize - distance + dictEnd] } }
mit
zitao0322/ShopCar
Shoping_Car/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift
14
2123
// // UIGestureRecognizer+Rx.swift // Touches // // Created by Carlos García on 10/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif // This should be only used from `MainScheduler` class GestureTarget<Recognizer: UIGestureRecognizer>: RxTarget { typealias Callback = (Recognizer) -> Void let selector = #selector(ControlTarget.eventHandler(_:)) weak var gestureRecognizer: Recognizer? var callback: Callback? init(_ gestureRecognizer: Recognizer, callback: Callback) { self.gestureRecognizer = gestureRecognizer self.callback = callback super.init() gestureRecognizer.addTarget(self, action: selector) let method = self.methodForSelector(selector) if method == nil { fatalError("Can't find method") } } func eventHandler(sender: UIGestureRecognizer!) { if let callback = self.callback, gestureRecognizer = self.gestureRecognizer { callback(gestureRecognizer) } } override func dispose() { super.dispose() self.gestureRecognizer?.removeTarget(self, action: self.selector) self.callback = nil } } extension UIGestureRecognizer: Reactive { } extension Reactive where Self: UIGestureRecognizer { /** Reactive wrapper for gesture recognizer events. */ public var rx_event: ControlEvent<Self> { let source: Observable<Self> = Observable.create { [weak self] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = self else { observer.on(.Completed) return NopDisposable.instance } let observer = GestureTarget(control) { control in observer.on(.Next(control)) } return observer }.takeUntil(rx_deallocated) return ControlEvent(events: source) } } #endif
mit
BellAppLab/Defines
Sources/Defines/Defines+Mac.swift
1
1594
/* Copyright (c) 2018 Bell App Lab <apps@bellapplab.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //MARK: - Instance Variables public extension Defines.Device.Model { /** Returns true if the model is a Mac. */ public var isMac: Bool { return isMacBookAir || isMacBook || isMacBookPro || isMacMini || isiMac || isMacPro } } //MARK: - Static Variables public extension Defines.Device { /** Returns true if the model is a Mac. */ public static let isMac: Bool = { return Defines.Device.currentModel.isMac }() }
mit
RemyDCF/tpg-offline
tpg offline/Settings/UpdateDeparturesTableViewController.swift
1
8013
// // UpdateDeparturesTableViewController.swift // tpg offline // // Created by Rémy Da Costa Faro on 11/06/2018. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit class UpdateDeparturesTableViewController: UITableViewController, DownloadOfflineDeparturesDelegate { override func viewDidLoad() { super.viewDidLoad() title = Text.offlineDepartures OfflineDeparturesManager.shared.addDownloadOfflineDeparturesDelegate(self) ColorModeManager.shared.addColorModeDelegate(self) if App.darkMode { self.tableView.backgroundColor = .black self.navigationController?.navigationBar.barStyle = .black self.tableView.separatorColor = App.separatorColor } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 2 ? 2 : 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell", for: indexPath) let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch cell.backgroundColor = App.cellBackgroundColor cell.textLabel?.text = Text.automatic cell.textLabel?.textColor = App.textColor cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.text = Text.offlineDeparturesOnWifi cell.detailTextLabel?.textColor = App.textColor cell.detailTextLabel?.numberOfLines = 0 statusSwitch.isOn = App.automaticDeparturesDownload statusSwitch.addTarget(self, action: #selector(self.changeAutomatic), for: .valueChanged) cell.accessoryView = statusSwitch if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black cell.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) cell.selectedBackgroundView = selectedView } return cell } else if indexPath.section == 1 { guard let cell = tableView.dequeueReusableCell(withIdentifier: "updateDeparturesButtonCell", for: indexPath) as? UpdateDeparturesButton else { return UITableViewCell() } if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black cell.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) cell.selectedBackgroundView = selectedView } cell.accessoryView = nil cell.textLabel?.text = "" cell.detailTextLabel?.text = "" cell.backgroundColor = App.cellBackgroundColor return cell } else { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell", for: indexPath) let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch cell.backgroundColor = App.cellBackgroundColor cell.textLabel?.text = Text.downloadMaps cell.textLabel?.textColor = App.textColor cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.text = "" statusSwitch.isOn = App.downloadMaps statusSwitch.addTarget(self, action: #selector(self.changeDownloadMaps), for: .valueChanged) cell.accessoryView = statusSwitch if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black cell.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) cell.selectedBackgroundView = selectedView } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell", for: indexPath) let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch cell.backgroundColor = App.cellBackgroundColor cell.textLabel?.text = Text.allowWithMobileData cell.textLabel?.textColor = App.textColor cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.text = "" statusSwitch.isOn = App.allowDownloadWithMobileData statusSwitch.addTarget(self, action: #selector(self.changeAllowDownloadWithMobileData), for: .valueChanged) cell.accessoryView = statusSwitch if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black cell.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) cell.selectedBackgroundView = selectedView } return cell } } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 1 { if OfflineDeparturesManager.shared.status == .error { return "An error occurred".localized } else { if UserDefaults.standard.bool(forKey: "offlineDeparturesUpdateAvailable") { return Text.updateAvailable } else if UserDefaults.standard.string(forKey: "departures.json.md5") == "" { return Text.noDeparturesInstalled } else { return Text.offlineDeparturesVersion } } } else { return "" } } @objc func changeAutomatic() { App.automaticDeparturesDownload = !App.automaticDeparturesDownload self.tableView.reloadData() } @objc func changeDownloadMaps() { App.downloadMaps = !App.downloadMaps self.tableView.reloadData() } @objc func changeAllowDownloadWithMobileData() { App.allowDownloadWithMobileData = !App.allowDownloadWithMobileData self.tableView.reloadData() } func updateDownloadStatus() { if OfflineDeparturesManager.shared.status == .notDownloading { self.tableView.reloadData() } } deinit { OfflineDeparturesManager.shared.removeDownloadOfflineDeparturesDelegate(self) ColorModeManager.shared.removeColorModeDelegate(self) } } class UpdateDeparturesButton: UITableViewCell, DownloadOfflineDeparturesDelegate { func updateDownloadStatus() { self.state = OfflineDeparturesManager.shared.status } @IBOutlet weak var button: UIButton! override func draw(_ rect: CGRect) { super.draw(rect) OfflineDeparturesManager.shared.addDownloadOfflineDeparturesDelegate(self) self.state = OfflineDeparturesManager.shared.status } deinit { OfflineDeparturesManager.shared.removeDownloadOfflineDeparturesDelegate(self) } var state: OfflineDeparturesManager.OfflineDeparturesStatus = .notDownloading { didSet { switch state { case .downloading: self.button.setTitle("Downloading...".localized, for: .disabled) self.button.isEnabled = false case .processing: self.button.setTitle("Saving...".localized, for: .disabled) self.button.isEnabled = false default: self.button.setTitle("Download now".localized, for: .normal) self.button.isEnabled = true } } } @IBAction func downloadButtonPushed() { if OfflineDeparturesManager.shared.status == any(of: .notDownloading, .error) { OfflineDeparturesManager.shared.download() } } }
mit
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/Offline methods/PXOfflineMethodsSheetViewController.swift
1
4886
import UIKit import MLBusinessComponents class PXOfflineMethodsSheetViewController: SheetViewController { private let sizes: [SheetSize] private let viewModel: PXOfflineMethodsViewModel private var totalView: UIView? init(viewController: PXOfflineMethodsViewController, offlineViewModel: PXOfflineMethodsViewModel, whiteViewHeight: CGFloat) { self.sizes = PXOfflineMethodsSheetViewController.getSizes(whiteViewHeight: whiteViewHeight) self.viewModel = offlineViewModel super.init(rootViewController: viewController, sizes: self.sizes, configuration: PXOfflineMethodsSheetViewController.getConfiguration()) viewController.delegate = self } override func viewDidLoad() { super.viewDidLoad() setupSheetDelegate() setupTotalView() } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if animated { UIView.animate(withDuration: 0.1) { self.totalView?.alpha = 0.0 } } } private func setupSheetDelegate() { delegate = self } private func setupTotalView() { let totalView = UIView() totalView.translatesAutoresizingMaskIntoConstraints = false totalView.backgroundColor = .clear totalView.alpha = 0.0 view.addSubview(totalView) NSLayoutConstraint.activate([ totalView.leadingAnchor.constraint(equalTo: view.leadingAnchor), totalView.trailingAnchor.constraint(equalTo: view.trailingAnchor), totalView.topAnchor.constraint(equalTo: view.topAnchor), totalView.heightAnchor.constraint(equalToConstant: PXOfflineMethodsSheetViewController.topBarHeight()) ]) let totalLabel = UILabel() totalLabel.translatesAutoresizingMaskIntoConstraints = false totalLabel.attributedText = viewModel.getTotalTitle().getAttributedString(fontSize: PXLayout.S_FONT, textColor: UIColor.Andes.gray900) totalLabel.textAlignment = .right totalLabel.backgroundColor = UIColor.Andes.white totalView.addSubview(totalLabel) NSLayoutConstraint.activate([ totalLabel.trailingAnchor.constraint(equalTo: totalView.trailingAnchor, constant: -14.0), totalLabel.bottomAnchor.constraint(greaterThanOrEqualTo: totalView.bottomAnchor) ]) let closeButton = UIButton(type: .custom) let closeImage = ResourceManager.shared.getImage("result-close-button")?.imageWithOverlayTint(tintColor: UIColor.Andes.gray900) closeButton.setImage(closeImage, for: .normal) closeButton.backgroundColor = .white closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.add(for: .touchUpInside) { [weak self] in PXFeedbackGenerator.mediumImpactFeedback() self?.presentingViewController?.dismiss(animated: true) } totalView.addSubview(closeButton) NSLayoutConstraint.activate([ closeButton.leadingAnchor.constraint(equalTo: totalView.leadingAnchor, constant: 2.0), closeButton.bottomAnchor.constraint(equalTo: totalView.bottomAnchor), closeButton.heightAnchor.constraint(equalToConstant: 44), closeButton.widthAnchor.constraint(equalTo: closeButton.heightAnchor), closeButton.trailingAnchor.constraint(equalTo: totalLabel.leadingAnchor), totalLabel.centerYAnchor.constraint(equalTo: closeButton.centerYAnchor) ]) view.sendSubviewToBack(totalView) self.totalView = totalView } private static func getSizes(whiteViewHeight: CGFloat) -> [SheetSize] { return [ .fixed(whiteViewHeight), .fixedFromTop(topBarHeight()) ] } private static func topBarHeight() -> CGFloat { return PXLayout.NAV_BAR_HEIGHT + PXLayout.getSafeAreaTopInset() } private static func getConfiguration() -> SheetConfiguration { var configuration = SheetConfiguration.default configuration.backgroundAlpha = 0.0 configuration.handle.height = 0.0 return configuration } } extension PXOfflineMethodsSheetViewController: SheetViewControllerDelegate { func sheetViewController(_ sheetViewController: SheetViewController, sheetHeightDidChange height: CGFloat) { let highest = view.bounds.height - PXOfflineMethodsSheetViewController.topBarHeight() let difference = highest - height if difference < 100 { totalView?.alpha = 1 - min(max(difference / 100, 0.0), 1.0) } else { totalView?.alpha = 0.0 } } } extension PXOfflineMethodsSheetViewController: PXOfflineMethodsViewControllerDelegate { func didEnableUI(enabled: Bool) { view.isUserInteractionEnabled = enabled } }
mit
iscriptology/swamp
Example/Pods/CryptoSwift/Sources/CryptoSwift/PKCS5/PBKDF1.swift
2
2532
// // PBKDF1.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 07/06/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // public extension PKCS5 { /// A key derivation function. /// /// PBKDF1 is recommended only for compatibility with existing /// applications since the keys it produces may not be large enough for /// some applications. public struct PBKDF1 { public enum Error: Swift.Error { case invalidInput case derivedKeyTooLong } public enum Variant { case md5, sha1 var size:Int { switch (self) { case .md5: return MD5.digestSize case .sha1: return SHA1.digestSize } } fileprivate func calculateHash(_ bytes:Array<UInt8>) -> Array<UInt8>? { switch (self) { case .sha1: return Digest.sha1(bytes) case .md5: return Digest.md5(bytes) } } } private let iterations: Int // c private let variant: Variant private let keyLength: Int private let t1: Array<UInt8> /// - parameters: /// - salt: salt, an eight-bytes /// - variant: hash variant /// - iterations: iteration count, a positive integer /// - keyLength: intended length of derived key public init(password: Array<UInt8>, salt: Array<UInt8>, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */) throws { precondition(iterations > 0) precondition(salt.count == 8) let keyLength = keyLength ?? variant.size if (keyLength > variant.size) { throw Error.derivedKeyTooLong } guard let t1 = variant.calculateHash(password + salt) else { throw Error.invalidInput } self.iterations = iterations self.variant = variant self.keyLength = keyLength self.t1 = t1 } /// Apply the underlying hash function Hash for c iterations public func calculate() -> Array<UInt8> { var t = t1 for _ in 2...self.iterations { t = self.variant.calculateHash(t)! } return Array(t[0..<self.keyLength]) } } }
mit
gunterhager/ReactiveCodable
ReactiveCodableTests/Models/Task.swift
1
216
// // Task.swift // ReactiveCodableTests // // Created by Gunter Hager on 01/08/2017. // Copyright © 2017 Gunter Hager. All rights reserved. // import Foundation struct Task: Codable { let title: String }
mit
ivanbruel/SwipeIt
SwipeIt/Helpers/ShareHelper/ShareHelper.swift
1
1019
// // ShareHelper.swift // Reddit // // Created by Ivan Bruel on 09/08/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import UIKit class ShareHelper { private weak var viewController: UIViewController? init(viewController: UIViewController) { self.viewController = viewController } func share(text: String? = nil, URL: NSURL? = nil, image: UIImage? = nil, fromView: UIView? = nil) { let shareables: [AnyObject?] = [text, URL, image] let activityViewController = UIActivityViewController(activityItems: shareables.flatMap { $0 }, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeOpenInIBooks] activityViewController.popoverPresentationController?.sourceView = fromView viewController?.presentViewController(activityViewController, animated: true, completion: nil) } }
mit
nifty-swift/Nifty
Tests/NiftyTests/numel_test.swift
2
1342
/*************************************************************************************************** * numel_test.swift * * This file tests the numel function. * * Author: Philip Erickson * Creation Date: 22 Jan 2017 * * 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. * * Copyright 2017 Philip Erickson **************************************************************************************************/ import XCTest @testable import Nifty class numel_test: XCTestCase { #if os(Linux) static var allTests: [XCTestCaseEntry] { let tests = [ testCase([("testBasic", self.testBasic)]), ] return tests } #endif func testBasic() { // TODO: fill me in print("\n\t*** WARNING: Test unimplemented - \(#file)\n") } }
apache-2.0
nickfalk/BSImagePicker
Pod/Classes/View/SelectionView.swift
2
3707
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 /** Used as an overlay on selected cells */ @IBDesignable final class SelectionView: UIView { var selectionString: String = "" { didSet { if selectionString != oldValue { setNeedsDisplay() } } } var settings: BSImagePickerSettings = Settings() override func draw(_ rect: CGRect) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Color Declarations //// Shadow Declarations let shadow2Offset = CGSize(width: 0.1, height: -0.1); let shadow2BlurRadius: CGFloat = 2.5; //// Frames let checkmarkFrame = bounds; //// Subframes let group = CGRect(x: checkmarkFrame.minX + 3, y: checkmarkFrame.minY + 3, width: checkmarkFrame.width - 6, height: checkmarkFrame.height - 6) //// CheckedOval Drawing let checkedOvalPath = UIBezierPath(ovalIn: CGRect(x: group.minX + floor(group.width * 0.0 + 0.5), y: group.minY + floor(group.height * 0.0 + 0.5), width: floor(group.width * 1.0 + 0.5) - floor(group.width * 0.0 + 0.5), height: floor(group.height * 1.0 + 0.5) - floor(group.height * 0.0 + 0.5))) context?.saveGState() context?.setShadow(offset: shadow2Offset, blur: shadow2BlurRadius, color: settings.selectionShadowColor.cgColor) settings.selectionFillColor.setFill() checkedOvalPath.fill() context?.restoreGState() settings.selectionStrokeColor.setStroke() checkedOvalPath.lineWidth = 1 checkedOvalPath.stroke() context?.setFillColor(UIColor.white.cgColor) //// Check mark for single assets if (settings.maxNumberOfSelections == 1) { context?.setStrokeColor(UIColor.white.cgColor) let checkPath = UIBezierPath() checkPath.move(to: CGPoint(x: 7, y: 12.5)) checkPath.addLine(to: CGPoint(x: 11, y: 16)) checkPath.addLine(to: CGPoint(x: 17.5, y: 9.5)) checkPath.stroke() return; } //// Bezier Drawing (Picture Number) let size = selectionString.size(attributes: settings.selectionTextAttributes) selectionString.draw(in: CGRect(x: checkmarkFrame.midX - size.width / 2.0, y: checkmarkFrame.midY - size.height / 2.0, width: size.width, height: size.height), withAttributes: settings.selectionTextAttributes) } }
mit
sgtsquiggs/clean-swift-templates
Clean Swift HELM/Unit Tests.xctemplate/___FILEBASENAME___InteractorTests.swift
1
973
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // @testable import ___PROJECTNAME___ import XCTest class ___FILEBASENAMEASIDENTIFIER___InteractorTests: XCTestCase { // MARK: Subject under test var sut: ___FILEBASENAMEASIDENTIFIER___Interactor! // MARK: Test lifecycle override func setUp() { super.setUp() setup___FILEBASENAMEASIDENTIFIER___Interactor() } override func tearDown() { super.tearDown() } // MARK: Test setup func setup___FILEBASENAMEASIDENTIFIER___Interactor() { sut = ___FILEBASENAMEASIDENTIFIER___Interactor() } // MARK: Test doubles // MARK: Tests func testSomething() { // Given // When // Then } }
mit
patrick-sheehan/cwic
Source/UIStoryboard.swift
1
663
// // UIStoryboard.swift // cwic // // Created by Patrick Sheehan on 7/1/17. // Copyright © 2017 Síocháin Solutions. All rights reserved. // import UIKit extension UIStoryboard { /// Main.storyboard identifiers for custom ViewControllers enum Id: String { case Profile = "ProfileViewController" case Position = "PositionViewController" } /// Get a view controller instance for the given storyboard id static func getViewController(_ storyboardId: Id) -> UIViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil) return storyboard.instantiateViewController(withIdentifier: storyboardId.rawValue) } }
gpl-3.0
rowungiles/SwiftTech
SwiftTech/SwiftTech/Utilities/Types/SegueHandlerType.swift
1
851
// // SegueHandlerType.swift // SwiftTech // // Created by Rowun Giles on 06/01/2016. // Copyright © 2016 Rowun Giles. All rights reserved. // import UIKit protocol SegueHandlerType { typealias SegueIdentifier: RawRepresentable } extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String { func performSegueWithIdentifier(segueIdentifier: SegueIdentifier, sender: AnyObject?) { performSegueWithIdentifier(segueIdentifier.rawValue, sender: sender) } func segueIdentifierForSegue(segue: UIStoryboardSegue) -> SegueIdentifier { guard let identifier = segue.identifier, segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("Invalid segue identifier \(segue.identifier).") } return segueIdentifier } }
gpl-3.0
icapps/ios-air-rivet
Example/Example/Modules/PostCodable.swift
3
274
import Foundation import Faro import Stella class PostServiceModel: Decodable { let posts: [Post] } struct Post: Decodable { let uuid: Int var title: String? private enum CodingKeys: String, CodingKey { case uuid = "id" case title } }
mit
kalehv/SwiftAlgo
SwiftAlgo/BinaryTreeNode.swift
2
464
// // BinaryTreeNode.swift // SwiftAlgo // // Created by Harshad Kale on 10/10/15. // Copyright © 2015 Harshad Kale. All rights reserved. // import Foundation class BinaryTreeNode<T where T: Comparable, T: Equatable> { var data: T? var left: BinaryTreeNode? var right: BinaryTreeNode? init(data: T?, left: BinaryTreeNode?, right: BinaryTreeNode?) { self.data = data! self.left = left! self.right = right! } }
mit
ben-ng/swift
test/IRGen/autolink_elf.swift
17
800
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %swift -target x86_64-unknown-linux-gnu -emit-module -parse-stdlib -o %t -module-name Empty -module-link-name swiftEmpty %S/../Inputs/empty.swift // RUN: %swift -target x86_64-unknown-linux-gnu %s -I %t -parse-stdlib -disable-objc-interop -module-name main -emit-ir -o - | %FileCheck %s // REQUIRES: CODEGENERATOR=X86 import Empty // Check that on ELF targets autolinking information is emitted and marked // as used. // CHECK-DAG: @_swift1_autolink_entries = private constant [13 x i8] c"-lswiftEmpty\00", section ".swift1_autolink_entries", align 8 // CHECK-DAG: @llvm.used = appending global [{{.*}} x i8*] [{{.*}}i8* getelementptr inbounds ([13 x i8], [13 x i8]* @_swift1_autolink_entries, i32 0, i32 0){{.*}}], section "llvm.metadata", align 8
apache-2.0
rnystrom/GitHawk
FreetimeTests/EmojiTests.swift
1
3393
// // EmojiTests.swift // FreetimeTests // // Created by Ryan Nystrom on 6/24/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import XCTest @testable import Freetime final class EmojiTests: XCTestCase { func test_replacingEmoji() { let text = "Lorem ipsum dolor sit amet, mei no ignota commodo, dolorem luptatum in qui. Iusto regione inermis ea quo, te eos consul utroque scaevola. Ea per possim salutandi. At tota aperiam ius, facilisi recusabo accommodare vel cu. Cibo omnium utamur et pro, :apple: temporibus eu cum.\nCum paulo definitionem at, vel atqui tempor ad. Ex minimum percipit erroribus vis, qui erroribus persequeris te, et augue :chart_with_upwards_trend: mediocritatem eum. Et mei cibo dicta, vis reque :dancers: at, suas mutat corrumpit eos eu. Sint eruditi eos ei, ad pri esse omnes, dolorem blandit voluptatibus an ius.\nOption eligendi id eum, ne sea porro :small_red_triangle_down: assueverit, sed modo diam in. Id vim eripuit intellegebat, ad quo consul constituto, at vix natum interpretaris. Id his tritani vituperata, ea minim quidam aliquip vis, animal pertinacia ad sit. Mel impedit interpretaris ne, iusto oblique platonem vel at, duo illud populo adversarium in. Ius ex quas rebum luptatum. Quot vero audire in qui.\nEx vix solet dolorem deleniti, mea semper quodsi cu, sit deseruisse quaerendum ne. Per :eight_spoked_asterisk: adhuc altera at. Ad sit debet disputando. Vide indoctum sea ne. Vocent neglegentur ei mea, noster :cop: eum cu, an tantas dictas eripuit mea.\nAt exerci explicari suscipiantur mea, agam paulo cum in. Veri deseruisse est ei, per cu audire sapientem suavitate. Sea cu adhuc facete, pri facilis apeirian ad. Agam postea oblique duo in, et laudem suscipit his, eos cu tale quodsi appetere. Pri cu malis doctus, id vel partem diceret.\nNam ut congue discere salutatus, ea amet diam eam, ut singulis legendos omittantur sea. :smile: aliquam pertinacia duo an. No nam quidam prompta, labore noluisse sed te. Singulis repudiandae sed an, no sit percipit philosophia definitionem, id has :busts_in_silhouette: option. Ex quo fabulas signiferumque. At usu quas movet alterum, populo noluisse et pri.\nDico alterum probatus pro et, etiam accumsan vim in. Quo te nonumy euripidis, mel no diam case iriure. Everti timeam qui ut, id nostro sadipscing pri. Usu tamquam voluptua at, blandit vituperata mea cu. Ad reque definitiones vis, recusabo periculis vel an, nominavi copiosae nec cu.\nVocibus mediocrem ea eos. Vel ea novum mediocritatem, id sed consul perpetua delicatissimi, mollis facilisi sed ut. Ubique deseruisse ne duo. Id sit recusabo gloriatur. An ius vidit suscipit honestatis.\nEssent feugait vel in. Putent pertinacia eloquentiam sit ne, pri veri admodum in. At sed epicuri repudiare argumentum. Velit dolore iudicabit pri ne, in prima adhuc eligendi vis, in sit verear tibique iudicabit. In vel labore doctus ancillae, id iudico prodesset duo.\nVel cu soleat eripuit principes, ea :smile: agam harum dolorum, an mel dicant graeci :vertical_traffic_light:. Ad per iudico eirmod, assum omnium an eos. Mea tale epicuri appellantur in, placerat dissentias et est, et ius oblique electram. Et vis nullam verear nominati, meliore periculis constituam in per, eos ea elit vitae." measure { for _ in 0..<10 { _ = text.replacingGithubEmoji } } } }
mit
jpedrosa/sua_sdl
Sources/_Sua/file.swift
1
15059
public class File: CustomStringConvertible { var _fd: Int32 public let path: String // Lower level constructor. The validity of the fd parameter is not checked. public init(path: String, fd: Int32) { self.path = path self._fd = fd } public init(path: String, mode: FileOperation = .R) throws { self.path = path _fd = Sys.openFile(path, operation: mode) if _fd == -1 { throw FileError.Open } } deinit { close() } public func printList(string: String) { // 10 - new line write(string) if string.isEmpty || string.utf16.codeUnitAt(string.utf16.count - 1) != 10 { let a: [UInt8] = [10] writeBytes(a, maxBytes: a.count) } } public func print(v: String) { write(v) } public func read(maxBytes: Int = -1) throws -> String? { if maxBytes < 0 { let a = try readAllCChar() return String.fromCharCodes(a) } else { var a = [CChar](count: maxBytes, repeatedValue: 0) try readCChar(&a, maxBytes: maxBytes) return String.fromCharCodes(a) } } public func readBytes(inout buffer: [UInt8], maxBytes: Int) throws -> Int { return try doRead(&buffer, maxBytes: maxBytes) } public func readAllBytes() throws -> [UInt8] { var a = [UInt8](count: length, repeatedValue: 0) let n = try readBytes(&a, maxBytes: a.count) if n != a.count { throw FileError.Read } return a } public func readCChar(inout buffer: [CChar], maxBytes: Int) throws -> Int { return try doRead(&buffer, maxBytes: maxBytes) } public func readAllCChar() throws -> [CChar] { var a = [CChar](count: length, repeatedValue: 0) let n = try readCChar(&a, maxBytes: a.count) if n != a.count { throw FileError.Read } return a } public func readLines() throws -> [String?] { var r: [String?] = [] let a = try readAllCChar() var si = 0 for i in 0..<a.count { if a[i] == 10 { r.append(String.fromCharCodes(a, start: si, end: i)) si = i + 1 } } return r } public func write(string: String) -> Int { return Sys.writeString(_fd, string: string) } public func writeBytes(bytes: [UInt8], maxBytes: Int) -> Int { return Sys.write(_fd, address: bytes, length: maxBytes) } public func writeCChar(bytes: [CChar], maxBytes: Int) -> Int { return Sys.write(_fd, address: bytes, length: maxBytes) } public func flush() { // Not implemented yet. } public func close() { if _fd != -1 { Sys.close(_fd) } _fd = -1 } public var isOpen: Bool { return _fd != -1 } public var fd: Int32 { return _fd } public func doRead(address: UnsafeMutablePointer<Void>, maxBytes: Int) throws -> Int { assert(maxBytes >= 0) let n = Sys.read(_fd, address: address, length: maxBytes) if n == -1 { throw FileError.Read } return n } func seek(offset: Int, whence: Int32) -> Int { return Sys.lseek(_fd, offset: offset, whence: whence) } public var position: Int { get { return seek(0, whence: PosixSys.SEEK_CUR) } set(value) { seek(value, whence: PosixSys.SEEK_SET) } } public var length: Int { let current = position if current == -1 { return -1 } else { let end = seek(0, whence: PosixSys.SEEK_END) position = current return end } } public var description: String { return "File(path: \(inspect(path)))" } public static func open(path: String, mode: FileOperation = .R, fn: (f: File) throws -> Void) throws { let f = try File(path: path, mode: mode) defer { f.close() } try fn(f: f) } public static func exists(path: String) -> Bool { var buf = Sys.statBuffer() return Sys.stat(path, buffer: &buf) == 0 } public static func stat(path: String) -> Stat? { var buf = Sys.statBuffer() return Sys.stat(path, buffer: &buf) == 0 ? Stat(buffer: buf) : nil } public static func delete(path: String) throws { if Sys.unlink(path) == -1 { throw FileError.Delete } } public static func rename(oldPath: String, newPath: String) throws { if Sys.rename(oldPath, newPath: newPath) == -1 { throw FileError.Rename } } // Aliases for handy FilePath methods. public static func join(firstPath: String, _ secondPath: String) -> String { return FilePath.join(firstPath, secondPath) } public static func baseName(path: String, suffix: String? = nil) -> String { return FilePath.baseName(path, suffix: suffix) } public static func dirName(path: String) -> String { return FilePath.dirName(path) } public static func extName(path: String) -> String { return FilePath.extName(path) } public static func expandPath(path: String) throws -> String { return try FilePath.expandPath(path) } } public enum FileError: ErrorType { case Open case Delete case Rename case Read } // The file will be closed and removed automatically when it can be garbage // collected. // // The file will be created with the file mode of read/write by the user. // // **Note**: If the process is cancelled (CTRL+C) or does not terminate // normally, the files may not be removed automatically. public class TempFile: File { init(prefix: String = "", suffix: String = "", directory: String? = nil) throws { var d = "/tmp/" if let ad = directory { d = ad let len = d.utf16.count if len == 0 || d.utf16.codeUnitAt(len - 1) != 47 { // / d += "/" } } var fd: Int32 = -1 var attempts = 0 var path = "" while fd == -1 { path = "\(d)\(prefix)\(RNG().nextUInt64())\(suffix)" fd = Sys.openFile(path, operation: .W, mode: PosixSys.USER_RW_FILE_MODE) if attempts >= 100 { throw TempFileError.Create(message: "Too many attempts.") } else if attempts % 10 == 0 { IO.sleep(0.00000001) } attempts += 1 } super.init(path: path, fd: fd) } deinit { closeAndUnlink() } public func closeAndUnlink() { close() Sys.unlink(path) } } public enum TempFileError: ErrorType { case Create(message: String) } public class FilePath { public static func join(firstPath: String, _ secondPath: String) -> String { let fpa = firstPath.bytes let i = skipTrailingSlashes(fpa, lastIndex: fpa.count - 1) let fps = String.fromCharCodes(fpa, start: 0, end: i) ?? "" if !secondPath.isEmpty && secondPath.utf16.codeUnitAt(0) == 47 { // / return "\(fps)\(secondPath)" } return "\(fps)/\(secondPath)" } public static func skipTrailingSlashes(bytes: [UInt8], lastIndex: Int) -> Int { var i = lastIndex while i >= 0 && bytes[i] == 47 { // / i -= 1 } return i } public static func skipTrailingChars(bytes: [UInt8], lastIndex: Int) -> Int { var i = lastIndex while i >= 0 && bytes[i] != 47 { // / i -= 1 } return i } public static func baseName(path: String, suffix: String? = nil) -> String { let bytes = path.bytes let len = bytes.count var ei = skipTrailingSlashes(bytes, lastIndex: len - 1) if ei >= 0 { var si = 0 if ei > 0 { si = skipTrailingChars(bytes, lastIndex: ei - 1) + 1 } if let sf = suffix { ei = skipSuffix(bytes, suffix: sf, lastIndex: ei) } return String.fromCharCodes(bytes, start: si, end: ei) ?? "" } return "/" } public static func skipSuffix(bytes: [UInt8], suffix: String, lastIndex: Int) -> Int { var a = suffix.bytes var i = lastIndex var j = a.count - 1 while i >= 0 && j >= 0 && bytes[i] == a[j] { i -= 1 j -= 1 } return j < 0 ? i : lastIndex } public static func dirName(path: String) -> String { let bytes = path.bytes let len = bytes.count var i = skipTrailingSlashes(bytes, lastIndex: len - 1) if i > 0 { //var ei = i i = skipTrailingChars(bytes, lastIndex: i - 1) let ci = i i = skipTrailingSlashes(bytes, lastIndex: i - 1) if i >= 0 { return String.fromCharCodes(bytes, start: 0, end: i) ?? "" } else if ci > 0 { return String.fromCharCodes(bytes, start: ci - 1, end: len - 1) ?? "" } else if ci == 0 { return "/" } } else if i == 0 { // Ignore. } else { return String.fromCharCodes(bytes, start: len - (len > 1 ? 2 : 1), end: len) ?? "" } return "." } public static func extName(path: String) -> String { let bytes = path.bytes var i = bytes.count - 1 if bytes[i] != 46 { while i >= 0 && bytes[i] != 46 { // Skip trailing chars. i -= 1 } return String.fromCharCodes(bytes, start: i) ?? "" } return "" } public static func skipSlashes(bytes: [UInt8], startIndex: Int, maxBytes: Int) -> Int { var i = startIndex while i < maxBytes && bytes[i] == 47 { i += 1 } return i } public static func skipChars(bytes: [UInt8], startIndex: Int, maxBytes: Int) -> Int { var i = startIndex while i < maxBytes && bytes[i] != 47 { i += 1 } return i } static func checkHome(path: String?) throws -> String { if let hd = path { return hd } else { throw FilePathError.ExpandPath(message: "Invalid home directory.") } } public static func expandPath(path: String) throws -> String { let bytes = path.bytes let len = bytes.count if len > 0 { var i = 0 let fc = bytes[0] if fc == 126 { // ~ var homeDir = "" if len == 1 || bytes[1] == 47 { // / homeDir = try checkHome(IO.env["HOME"]) i = 1 } else { i = skipChars(bytes, startIndex: 1, maxBytes: len) if let name = String.fromCharCodes(bytes, start: 1, end: i - 1) { let ps = Sys.getpwnam(name) if ps != nil { homeDir = try checkHome(String.fromCString(ps.memory.pw_dir)) } else { throw FilePathError.ExpandPath(message: "User does not exist.") } } else { throw FilePathError.ExpandPath(message: "Invalid name.") } } if i >= len { return homeDir } return join(homeDir, doExpandPath(bytes, startIndex: i, maxBytes: len)) } else if fc != 47 { // / if let cd = Dir.cwd { if fc == 46 { // . let za = join(cd, path).bytes return doExpandPath(za, startIndex: 0, maxBytes: za.count) } return join(cd, doExpandPath(bytes, startIndex: 0, maxBytes: len)) } else { throw FilePathError.ExpandPath(message: "Invalid current directory.") } } return doExpandPath(bytes, startIndex: i, maxBytes: len) } return "" } public static func doExpandPath(bytes: [UInt8], startIndex: Int, maxBytes: Int) -> String { var i = startIndex var a = [String]() var ai = -1 var sb = "" func add() { let si = i i = skipChars(bytes, startIndex: i + 1, maxBytes: maxBytes) ai += 1 let s = String.fromCharCodes(bytes, start: si, end: i - 1) ?? "" if ai < a.count { a[ai] = s } else { a.append(s) } i = skipSlashes(bytes, startIndex: i + 1, maxBytes: maxBytes) } func stepBack() { if ai >= 0 { ai -= 1 } i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes) } if maxBytes > 0 { let lasti = maxBytes - 1 while i < maxBytes && bytes[i] == 47 { // sb += "/" i += 1 } if i >= maxBytes { return sb } while i < maxBytes { var c = bytes[i] if c == 46 { // . if i < lasti { c = bytes[i + 1] if c == 46 { // .. if i < lasti - 1 { c = bytes[i + 2] if c == 47 { // / stepBack() } else { add() } } else { stepBack() } } else if c == 47 { // / i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes) } else { add() } } else { break } } else { add() } } var slash = false for i in 0...ai { if slash { sb += "/" } sb += a[i] slash = true } if bytes[lasti] == 47 { // / sb += "/" } } return sb } } enum FilePathError: ErrorType { case ExpandPath(message: String) } public class FileStream { public var fp: CFilePointer? let SIZE = 80 // Starting buffer size. public init(fp: CFilePointer) { self.fp = fp } deinit { close() } public func close() { if let afp = fp { Sys.fclose(afp) } fp = nil } public func readAllCChar(command: String) throws -> [CChar] { guard let afp = fp else { return [CChar]() } var a = [CChar](count: SIZE, repeatedValue: 0) var buffer = [CChar](count: SIZE, repeatedValue: 0) var alen = SIZE var j = 0 while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil { for i in 0..<SIZE { let c = buffer[i] if c == 0 { break } if j >= alen { var b = [CChar](count: alen * 8, repeatedValue: 0) for m in 0..<alen { b[m] = a[m] } a = b alen = b.count } a[j] = c j += 1 } } return a } public func readLines(command: String, fn: (string: String?) -> Void) throws { guard let afp = fp else { return } var a = [CChar](count: SIZE, repeatedValue: 0) var buffer = [CChar](count: SIZE, repeatedValue: 0) var alen = SIZE var j = 0 while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil { var i = 0 while i < SIZE { let c = buffer[i] if c == 0 { break } if j >= alen { var b = [CChar](count: alen * 8, repeatedValue: 0) for m in 0..<alen { b[m] = a[m] } a = b alen = b.count } a[j] = c if c == 10 { fn(string: String.fromCharCodes(a, start: 0, end: j)) j = 0 } else { j += 1 } i += 1 } } if j > 0 { fn(string: String.fromCharCodes(a, start: 0, end: j - 1)) } } public func readByteLines(command: String, maxBytes: Int = 80, fn: (bytes: [UInt8], length: Int) -> Void) throws { guard let afp = fp else { return } var buffer = [UInt8](count: Int(maxBytes), repeatedValue: 0) while true { let n = Sys.fread(&buffer, size: 1, nmemb: maxBytes, fp: afp) if n > 0 { fn(bytes: buffer, length: n) } else { break } } } }
apache-2.0
adrfer/swift
test/Driver/embed-bitcode.swift
20
3466
// RUN: %target-swiftc_driver -driver-print-bindings -embed-bitcode %s 2>&1 | FileCheck -check-prefix=CHECK-%target-object-format %s // CHECK-macho: "swift", inputs: ["{{.*}}embed-bitcode.swift"], output: {llvm-bc: "[[BC:.*\.bc]]"} // CHECK-macho: "swift", inputs: ["[[BC]]"], output: {object: "[[OBJECT:.*\.o]]"} // CHECK-macho: "ld", inputs: ["[[OBJECT]]"], output: {image: "embed-bitcode"} // CHECK-elf: "swift", inputs: ["{{.*}}embed-bitcode.swift"], output: {llvm-bc: "[[BC:.*\.bc]]"} // CHECK-elf: "swift", inputs: ["[[BC]]"], output: {object: "[[OBJECT:.*\.o]]"} // CHECK-elf: "swift-autolink-extract", inputs: ["[[OBJECT]]"], output: {autolink: "[[AUTOLINK:.*\.autolink]]"} // CHECK-elf: "clang++", inputs: ["[[OBJECT]]", "[[AUTOLINK]]"], output: {image: "main"} // RUN: %target-swiftc_driver -embed-bitcode %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-FRONT -check-prefix=CHECK-FRONT-%target-object-format // CHECK-FRONT: -frontend // CHECK-FRONT: -emit-bc // CHECK-FRONT: -frontend // CHECK-FRONT: -c // CHECK-FRONT: -embed-bitcode{{ }} // CHECK-FRONT: -disable-llvm-optzns // CHECK-FRONT-macho: ld{{"? }} // CHECK-FRONT-macho: -bitcode_bundle // RUN: %target-swiftc_driver -embed-bitcode-marker %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-MARKER -check-prefix=CHECK-MARKER-%target-object-format // CHECK-MARKER: -frontend // CHECK-MARKER: -c // CHECK-MARKER: -embed-bitcode-marker // CHECK-MARKER-NOT: -frontend // CHECK-MARKER-macho: ld{{"? }} // CHECK-MARKER-macho: -bitcode_bundle // RUN: %target-swiftc_driver -embed-bitcode -Xcc -DDEBUG -Xllvm -fake-llvm-option -c -emit-module %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-MODULE // CHECK-MODULE: -frontend // CHECK-MODULE: -emit-bc // CHECK-MODULE-DAG: -Xcc -DDEBUG // CHECK-MODULE-DAG: -Xllvm -fake-llvm-option // CHECK-MODULE-DAG: -emit-module-path // CHECK-MODULE: -frontend // CHECK-MODULE: -emit-module // CHECK-MODULE: -frontend // CHECK-MODULE: -c // CHECK-MODULE-NOT: -Xcc // CHECK-MODULE-NOT: -DDEBUG // CHECK-MODULE-NOT: -fake-llvm-option // CHECK-MODULE-NOT: -emit-module-path // RUN: %target-swiftc_driver -embed-bitcode -force-single-frontend-invocation %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-SINGLE // CHECK-SINGLE: -frontend // CHECK-SINGLE: -emit-bc // CHECK-SINGLE: -frontend // CHECK-SINGLE: -c // CHECK-SINGLE: -embed-bitcode // CHECK-SINGLE: -disable-llvm-optzns // RUN: %target-swiftc_driver -embed-bitcode -c -parse-as-library -emit-module -force-single-frontend-invocation %s -parse-stdlib -module-name Swift 2>&1 -### | FileCheck %s -check-prefix=CHECK-LIB-WMO // CHECK-LIB-WMO: -frontend // CHECK-LIB-WMO: -emit-bc // CHECK-LIB-WMO: -parse-stdlib // CHECK-LIB-WMO: -frontend // CHECK-LIB-WMO: -c // CHECK-LIB-WMO: -parse-stdlib // CHECK-LIB-WMO: -embed-bitcode // CHECK-LIB-WMO: -disable-llvm-optzns // RUN: %target-swiftc_driver -embed-bitcode -c -parse-as-library -emit-module %s %S/../Inputs/empty.swift -module-name ABC 2>&1 -### | FileCheck %s -check-prefix=CHECK-LIB // CHECK-LIB: swift -frontend // CHECK-LIB: -emit-bc // CHECK-LIB: -primary-file // CHECK-LIB: swift -frontend // CHECK-LIB: -emit-bc // CHECK-LIB: -primary-file // CHECK-LIB: swift -frontend // CHECK-LIB: -emit-module // CHECK-LIB: swift -frontend // CHECK-LIB: -c // CHECK-LIB: -embed-bitcode // CHECK-LIB: -disable-llvm-optzns // CHECK-LIB: swift -frontend // CHECK-LIB: -c // CHECK-LIB: -embed-bitcode // CHECK-LIB: -disable-llvm-optzns // CHECK-LIB-NOT: swift -frontend
apache-2.0
ephread/Instructions
Examples/Example/Sources/Core/AppDelegate.swift
1
2536
// Copyright (c) 2015-present Frédéric Maquin <fred@ephread.com> and contributors. // Licensed under the terms of the MIT License. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundSessionCompletionHandler: (() -> Void)? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Removing animations for speed and stability. if CommandLine.arguments.contains("--UITests") || CommandLine.arguments.contains("--SnapshotTests") { UIView.setAnimationsEnabled(false) } return true } // MARK: Legacy Lifecycle func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } // MARK: Background URLSession func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { backgroundSessionCompletionHandler = completionHandler } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) 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) } @available(iOS 13.0, *) 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. } }
mit
thiagolioy/marvelapp
Marvel/Models/ThumbImage.swift
1
547
// // ThumbImage.swift // Marvel // // Created by Thiago Lioy on 17/11/16. // Copyright © 2016 Thiago Lioy. All rights reserved. // import Foundation import ObjectMapper struct ThumbImage { var path: String = "" var imageExtension: String = "" func fullPath() -> String { return "\(path).\(imageExtension)" } } extension ThumbImage: Mappable { init?(map: Map) { } mutating func mapping(map: Map) { path <- map["path"] imageExtension <- map["extension"] } }
mit
cplaverty/KeitaiWaniKani
WaniKaniKit/Database/Table/Schema/Table.swift
1
3740
// // Table.swift // WaniKaniKit // // Copyright © 2017 Chris Laverty. All rights reserved. // class Table { let name: String let schemaType = "table" // We have to make these vars so that we can create the Mirror in the initialiser var columns: [Column]! = nil var primaryKeys: [Column]? = nil var indexes: [TableIndex]? = nil init(name: String, indexes: [TableIndex]? = nil) { self.name = name let mirror = Mirror(reflecting: self) var columns = [Column]() columns.reserveCapacity(Int(mirror.children.count)) for child in mirror.children { if let column = child.value as? Column { column.table = self columns.append(column) } } self.columns = columns let primaryKeys = columns.filter({ $0.isPrimaryKey }) self.primaryKeys = primaryKeys.isEmpty ? nil : primaryKeys self.indexes = indexes indexes?.forEach({ $0.table = self }) } enum ColumnType: String { case int = "INTEGER" case float = "REAL" case numeric = "NUMERIC" case text = "TEXT" case blob = "BLOB" } class Column { let name: String let type: ColumnType let isNullable: Bool let isPrimaryKey: Bool let isUnique: Bool weak var table: Table? init(name: String, type: ColumnType, nullable: Bool = true, primaryKey: Bool = false, unique: Bool = false) { self.name = name self.type = type self.isNullable = nullable self.isPrimaryKey = primaryKey self.isUnique = unique } } class TableIndex { let name: String let columns: [Column] let isUnique: Bool weak var table: Table? init(name: String, columns: [Column], unique: Bool = false) { self.name = name self.columns = columns self.isUnique = unique } } } // MARK: - CustomStringConvertible extension Table: CustomStringConvertible { var description: String { return name } } extension Table.Column: CustomStringConvertible { var description: String { guard let table = table else { return name } return "\(table.name).\(name)" } } // MARK: - TableProtocol extension Table: TableProtocol { var sqlStatement: String { var query = "CREATE TABLE \(name) (" query += columns.lazy.map({ $0.sqlStatement }).joined(separator: ", ") if let primaryKeys = primaryKeys { query += ", PRIMARY KEY (" query += primaryKeys.lazy.map({ $0.name }).joined(separator: ", ") query += ")" } query += ");" if let indexes = indexes, !indexes.isEmpty { query += "\n" query += indexes.lazy.map({ $0.sqlStatement }).joined(separator: "\n") } return query } } // MARK: - ColumnProtocol extension Table.Column: ColumnProtocol { var sqlStatement: String { var decl = "\(name) \(type.rawValue)" if !isNullable { decl += " NOT NULL" } if isUnique { decl += " UNIQUE" } return decl } } // MARK: - SQLConvertible extension Table.TableIndex: SQLConvertible { var sqlStatement: String { guard let table = table else { fatalError("Index not attached to a table!") } return (isUnique ? "CREATE UNIQUE INDEX" : "CREATE INDEX") + " \(name) ON \(table.name) (\(columns.lazy.map({ $0.name }).joined(separator: ", ")));" } }
mit
Vienta/kuafu
kuafu/kuafu/src/Controller/KFLisenceDetailViewController.swift
1
944
// // KFLisenceDetailViewController.swift // kuafu // // Created by Vienta on 15/7/18. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit class KFLisenceDetailViewController: UIViewController { @IBOutlet weak var txvLisence: UITextView! var lisenceName: String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = self.lisenceName var lisenceFileName: String = self.lisenceName + "_LICENSE" let path = NSBundle.mainBundle().pathForResource(lisenceFileName, ofType: "txt") var lisenceContent: String! = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil) self.txvLisence.text = lisenceContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/TrainingExampleList.swift
1
914
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** TrainingExampleList. */ public struct TrainingExampleList: Decodable { public var examples: [TrainingExample]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case examples = "examples" } }
mit
LaudyLaw/FirstSwiftDemo
MyFirstGitSwiftDemo/ForthCycleViewController.swift
1
549
// // ForthCycleViewController.swift // MyFirstGitSwiftDemo // // Created by luosong on 15/5/27. // Copyright (c) 2015年 Personal. All rights reserved. // import UIKit class ForthCycleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
material-foundation/material-automation
Sources/main.swift
1
5627
/* Copyright 2018 the Material Automation authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import PerfectLib import PerfectHTTP import PerfectHTTPServer import PerfectLogger import PerfectThread #if os(Linux) srandom(UInt32(time(nil))) #endif // Create HTTP server. let server = HTTPServer() // Create the container variable for routes to be added to. var routes = Routes() // Create GitHub app config. let config = GithubAppConfig() routes.add(method: .get, uri: "/_ah/health", handler: { request, response in LogFile.info("GET - /_ah/health route handler...") response.setBody(string: "OK") response.completed() }) // Basic GET request routes.add(method: .get, uri: "/hello", handler: { request, response in LogFile.info("GET - /hello route handler...") response.setBody(string: config.helloMessage) response.completed() }) routes.add(method: .post, uri: "/labels/updateall", handler: { request, response in LogFile.info("/labels/updateall") guard let password = request.header(.authorization), GithubAuth.verifyGooglerPassword(googlerPassword: password) else { response.completed(status: .unauthorized) return } var json: [String: Any] do { json = try request.postBodyString?.jsonDecode() as? [String: Any] ?? [String: Any]() } catch { response.completed(status: .unauthorized) return } guard let installationID = json["installation"] as? String, let repoURL = json["repository_url"] as? String else { LogFile.error("The incoming request is missing information: \(json.description)") response.completed(status: .unauthorized) return } guard let githubAPI = GithubManager.shared.getGithubAPI(for: installationID) else { LogFile.error("could not get a github instance with an access token for \(installationID)") response.completed(status: .unauthorized) return } Threading.getDefaultQueue().dispatch { githubAPI.setLabelsForAllIssues(repoURL: repoURL) } response.completed() }) routes.add(method: .post, uri: "/webhook", handler: { request, response in LogFile.info("/webhook") Analytics.trackEvent(category: "Incoming", action: "/webhook") guard let sig = request.header(.custom(name: "X-Hub-Signature")), let bodyString = request.postBodyString, GithubAuth.verifyGithubSignature(payload: bodyString, requestSig: sig) else { LogFile.error("unauthorized request") response.completed(status: .unauthorized) return } guard let githubData = GithubData.createGithubData(from: bodyString), let installationID = githubData.installationID else { LogFile.error("couldn't parse incoming webhook request") response.completed(status: .ok) return } guard let githubAPI = GithubManager.shared.getGithubAPI(for: installationID) else { LogFile.error("could not get a github instance with an access token for \(installationID)") response.completed(status: .unauthorized) return } if let PRData = githubData.PRData { // Pull Request data received. if githubData.action == "synchronize" || githubData.action == "opened" { // Pull Request either opened or updated. LabelAnalysis.addAndFixLabelsForPullRequests(PRData: PRData, githubAPI: githubAPI) } } else if let issueData = githubData.issueData { // Issue data received. if githubData.action == "opened" { // Issue opened. LabelAnalysis.addAndFixLabelsForIssues(issueData: issueData, githubAPI: githubAPI) LabelAnalysis.addNeedsActionabilityReviewLabel(issueData: issueData, githubAPI: githubAPI) } let isClientBlockingIssue = issueData.labels.contains(where: { $0 == "Client-blocking" }) if (githubData.action == "labeled" || githubData.action == "opened") && isClientBlockingIssue { ProjectAnalysis.addIssueToCurrentSprint(githubData: githubData, githubAPI: githubAPI) } } else if githubData.projectCard != nil { // Project card data received. if githubData.action == "moved" { // Card moved between columns. ProjectAnalysis.didMoveCard(githubData: githubData, githubAPI: githubAPI) } } else if githubData.project != nil { if githubData.action == "closed" { // Project closed ProjectAnalysis.didCloseProject(githubData: githubData, githubAPI: githubAPI) } } var ret = "" do { ret = try githubData.jsonEncodedString() } catch { LogFile.error("\(error)") } response.setHeader(.contentType, value: "application/json") response.appendBody(string: ret) response.completed() }) // Add the routes to the server. server.addRoutes(routes) // Set a listen port of 8080 server.serverPort = 8080 GithubData.registerModels() do { // Launch the HTTP server. try server.start() } catch PerfectError.networkError(let err, let msg) { LogFile.error("Network error thrown: \(err) \(msg)") }
apache-2.0
chrishulbert/Swift2Keychain
Swift2KeychainTests/Swift2KeychainTests.swift
1
2218
// // Swift2KeychainTests.swift // Swift2KeychainTests // // Created by Chris Hulbert on 22/06/2015. // Copyright © 2015 Chris Hulbert. All rights reserved. // import XCTest import Swift2Keychain class Swift2KeychainTests: XCTestCase { override func setUp() { super.setUp() Keychain.deleteAccount("Account") } func testSyncBackgroundCombinations() { Keychain.setString("TestPasswordTT", forAccount: "Account", synchronizable: true, background: true) let resultTT = Keychain.stringForAccount("Account") XCTAssertEqual(resultTT!, "TestPasswordTT") Keychain.deleteAccount("Account") XCTAssertNil(Keychain.stringForAccount("Account")) Keychain.setString("TestPasswordFT", forAccount: "Account", synchronizable: false, background: true) let resultFT = Keychain.stringForAccount("Account") XCTAssertEqual(resultFT!, "TestPasswordFT") Keychain.deleteAccount("Account") XCTAssertNil(Keychain.stringForAccount("Account")) Keychain.setString("TestPasswordTF", forAccount: "Account", synchronizable: true, background: false) let resultTF = Keychain.stringForAccount("Account") XCTAssertEqual(resultTF!, "TestPasswordTF") Keychain.deleteAccount("Account") XCTAssertNil(Keychain.stringForAccount("Account")) Keychain.setString("TestPasswordFF", forAccount: "Account", synchronizable: false, background: false) let resultFF = Keychain.stringForAccount("Account") XCTAssertEqual(resultFF!, "TestPasswordFF") Keychain.deleteAccount("Account") XCTAssertNil(Keychain.stringForAccount("Account")) } func testSetAndDelete() { let blank = Keychain.stringForAccount("Account") XCTAssertNil(blank) Keychain.setString("Password", forAccount: "Account", synchronizable: false, background: false) let password = Keychain.stringForAccount("Account") XCTAssertNotNil(password) Keychain.deleteAccount("Account") let blankAgain = Keychain.stringForAccount("Account") XCTAssertNil(blankAgain) } }
mit
tkremenek/swift
validation-test/compiler_crashers_fixed/00577-swift-constraints-constraintsystem-gettypeofmemberreference.swift
65
531
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func g<T) { struct S { struct c : c> String { class B : NSObject { } } struct B? = compose<T { } protocol A { } private let g = c())
apache-2.0
cuappdev/podcast-ios
old/Podcast/System.swift
1
598
// // System.swift // Podcast // // Created by Natasha Armbrust on 3/2/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit class System { // TODO: CHANGE THIS static let feedTab = 0 static let discoverSearchTab: Int = 1 static let bookmarkTab: Int = 2 static let profileTab: Int = 3 static var currentUser: User? static var currentSession: Session? static var endpointRequestQueue = EndpointRequestQueue() static func isiPhoneX() -> Bool { return UIScreen.main.nativeBounds.height == 2436 } }
mit
radex/swift-compiler-crashes
crashes-duplicates/07636-swift-sourcemanager-getmessage.swift
11
250
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing deinit { protocol A : B<D> Void>) { if true { class b { func p() { class case c,
mit
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Mocks/MockNSThread.swift
1
1559
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import XCTest // Use this class when need to test behavior in the global thread from the main thread. final class MockNSThread : PBMNSThreadProtocol { var mockIsMainThread: Bool init(mockIsMainThread: Bool) { self.mockIsMainThread = mockIsMainThread } // MARK: - PBMNSThreadProtocol var isMainThread: Bool { return mockIsMainThread } } // Use this class when need to test switching the execution from the global thread to the main thread. final class PBMThread : PBMNSThreadProtocol { var checkThreadCallback:((Bool) -> Void) init(checkThreadCallback: @escaping ((Bool) -> Void)) { self.checkThreadCallback = checkThreadCallback } // MARK: - PBMNSThreadProtocol var isMainThread: Bool { let isMainThread = Thread.isMainThread checkThreadCallback(isMainThread) return isMainThread } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/09712-swift-constraints-constraintgraphscope-constraintgraphscope.swift
11
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let d{ let a=1 var:A{}protocol A{ func a func a<h:a
mit
ustwo/videoplayback-ios
Source/Presenter/VPKVideoPlaybackPresenter.swift
1
6061
// // VPKVideoViewPresenter.swift // VideoPlaybackKit // // Created by Sonam on 4/21/17. // Copyright © 2017 ustwo. All rights reserved. // import Foundation import AVFoundation public class VPKVideoPlaybackPresenter { static let fadeOutTime: TimeInterval = 3.0 var videoView: VPKVideoViewProtocol? { didSet { observeVideoViewLifecycle() } } var hasFadedOutControlView: Bool = false var progressTime = 0.0 var playbackBarView: VPKPlaybackControlViewProtocol? var interactor: VPKVideoPlaybackInteractorInputProtocol? var builder: VPKVideoPlaybackBuilderProtocol? var videoSizeState: VideoSizeState? var playbackTheme: ToolBarTheme? var shouldAutoplay: Bool? var indexPath: NSIndexPath? var duration: TimeInterval? required public init(with autoPlay:Bool = false, showInCell indexPath: NSIndexPath?, playbackTheme theme: ToolBarTheme) { self.shouldAutoplay = autoPlay self.indexPath = indexPath self.videoSizeState = .normal self.playbackTheme = theme } private func observeVideoViewLifecycle() { videoView?.viewWillAppearClosure = { () in if self.shouldAutoplay == true { self.didTapVideoView() } } } } //MARK: VIEW --> Presenter extension VPKVideoPlaybackPresenter: VPKVideoPlaybackPresenterProtocol { //VIEW -> PRESENTER func viewDidLoad() { //Update the default image if let localImage = interactor?.localImageName { videoView?.localPlaceHolderName = localImage } else if let remoteImageURL = interactor?.remoteImageURL { videoView?.remotePlaceHolderURL = remoteImageURL } if self.shouldAutoplay == true { didTapVideoView() } } func reuseInCell() { interactor?.didReuseInCell() } func didMoveOffScreen() { interactor?.didMoveOffScreen() } func didTapVideoView() { guard let safeVideoUrl = interactor?.videoType.videoUrl else { return } interactor?.didTapVideo(videoURL: safeVideoUrl, at: self.indexPath) } public func didExpand() { guard let state = videoSizeState else { return } switch state { case .normal: videoView?.makeFullScreen() case .fullScreen: videoView?.makeNormalScreen() } videoSizeState?.toggle() } func didSkipBack(_ seconds: Float) { didScrubTo(TimeInterval(seconds)) } func didSkipForward(_ seconds: Float) { didScrubTo(TimeInterval(seconds)) } func didScrubTo(_ value: TimeInterval) { interactor?.didScrubTo(value) } func formattedProgressTime(from seconds: TimeInterval) -> String { return seconds.formattedTimeFromSeconds } } //MARK: INTERACTOR --> Presenter extension VPKVideoPlaybackPresenter: VPKVideoPlaybackInteractorOutputProtocol { func onVideoResetPresentation() { videoView?.reloadInterfaceWithoutPlayerlayer() } func onVideoDidStartPlayingWith(_ duration: TimeInterval) { self.duration = duration playbackBarView?.maximumSeconds = Float(duration) playbackBarView?.showDurationWith(duration.formattedTimeFromSeconds) playbackBarView?.toggleActionButton(PlayerState.playing.buttonImageName) } func onVideoPlayingFor(_ seconds: TimeInterval) { playbackBarView?.progressValue = Float(seconds) playbackBarView?.updateTimePlayingCompletedTo(seconds.formattedTimeFromSeconds) self.progressTime = seconds if videoIsReachingTheEnd() { fadeInControlBarView() hasFadedOutControlView = false } else if videoHasBeenPlaying(for: VPKVideoPlaybackPresenter.fadeOutTime) && hasFadedOutControlView == false { hasFadedOutControlView = true fadeOutControlBarView() } } func videoHasBeenPlaying(for seconds: TimeInterval) -> Bool { return (seconds...seconds + 5).contains(progressTime) } func videoIsReachingTheEnd() -> Bool { guard let safeDuration = duration else { return false } let timeLeft = safeDuration - progressTime return timeLeft <= 5.0 } func fadeOutControlBarView() { guard let playbackView = playbackBarView else { return } PlaybackControlViewAnimator.fadeOut(playbackView) } func fadeInControlBarView() { guard let playbackView = playbackBarView else { return } PlaybackControlViewAnimator.fadeIn(playbackView) } func onVideoDidPlayToEnd() { videoView?.showPlaceholder() playbackBarView?.toggleActionButton(PlayerState.paused.buttonImageName) playbackBarView?.progressValue = 0.0 } func onVideoDidStopPlaying() { playbackBarView?.toggleActionButton(PlayerState.paused.buttonImageName) guard let controlView = playbackBarView else { assertionFailure("control view is nil") return } PlaybackControlViewAnimator.fadeIn(controlView) } func onVideoDidStartPlaying() { videoView?.activityIndicator.stopAnimating() playbackBarView?.toggleActionButton(PlayerState.playing.buttonImageName) } func onVideoLoadSuccess(_ playerLayer: AVPlayerLayer) { videoView?.reloadInterface(with: playerLayer) } func onVideoLoadFail(_ error: String) { //TODO: (SD) PASS ERROR } } //MAK: Presenter transformers fileprivate extension TimeInterval { var formattedTimeFromSeconds: String { let minutes = Int(self.truncatingRemainder(dividingBy: 3600))/60 let seconds = Int(self.truncatingRemainder(dividingBy: 60)) return String(format: "%02i:%02i", minutes, seconds) } }
mit
ThunderAnimal/BBPhobia_ios
BBPhobiaUITests/BBPhobiaUITests.swift
1
1252
// // BBPhobiaUITests.swift // BBPhobiaUITests // // Created by Martin Weber on 04/02/2017. // Copyright © 2017 Martin Weber. All rights reserved. // import XCTest class BBPhobiaUITests: 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. } }
apache-2.0
NileshJarad/shopping_cart_ios_swift
ShoppingCart/AppDelegate.swift
1
2150
// // AppDelegate.swift // ShoppingCart // // Created by Nilesh Jarad on 09/09/16. // Copyright © 2016 Nilesh Jarad. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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:. } }
lgpl-3.0
Sharelink/Bahamut
Bahamut/BahamutServiceContainer/FileService/DownloadExtension.swift
1
4629
// // DownloadBaseExtension.swift // Bahamut // // Created by AlexChow on 15/11/25. // Copyright © 2015年 GStudio. All rights reserved. // import Foundation //MARK: Id File Fetcher class IdFileFetcher: FileFetcher { var fileType:FileType!; func startFetch(_ fileId: String, delegate: ProgressTaskDelegate) { DispatchQueue.global().async { () -> Void in if let path = Bundle.main.path(forResource: "\(fileId)", ofType:""){ if PersistentFileHelper.fileExists(path){ delegate.taskCompleted(fileId, result: path) } }else{ let fileService = ServiceContainer.getFileService() if let path = fileService.getFilePath(fileId, type: self.fileType){ delegate.taskCompleted(fileId, result: path) }else { ProgressTaskWatcher.sharedInstance.addTaskObserver(fileId, delegate: delegate) fileService.fetchFile(fileId, fileType: self.fileType){ filePath in } } } } } } extension FileService { func getFileFetcherOfFileId(_ fileType:FileType) -> FileFetcher { let fetcher = IdFileFetcher() fetcher.fileType = fileType return fetcher } } //MARK: Download FileService Extension extension FileService { func getCachedFileAccessInfo(_ fileId:String)->FileAccessInfo? { return PersistentManager.sharedInstance.getModel(FileAccessInfo.self, idValue: fileId) } func fetchFileAccessInfo(_ fileId:String,callback:@escaping (FileAccessInfo?)->Void) { let req = GetBahamutFireRequest() req.fileId = fileId let bahamutFireClient = BahamutRFKit.sharedInstance.getBahamutFireClient() bahamutFireClient.execute(req) { (result:SLResult<FileAccessInfo>) -> Void in if result.isSuccess{ if let fa = result.returnObject { fa.saveModel() callback(fa) return } } self.fetchingFinished(fileId) callback(nil) } } fileprivate class CallbackTaskDelegate:NSObject,ProgressTaskDelegate { var callback:((_ filePath:String?) -> Void)? @objc func taskCompleted(_ taskIdentifier:String,result:Any!){ callback?(result as? String) } @objc func taskFailed(_ taskIdentifier:String,result:Any!){ callback?(nil) } } func fetchFile(_ fileId:String,fileType:FileType,callback:@escaping (_ filePath:String?) -> Void) { if String.isNullOrWhiteSpace(fileId) { callback(nil) return } let d = CallbackTaskDelegate() d.callback = callback ProgressTaskWatcher.sharedInstance.addTaskObserver(fileId, delegate: d) if isFetching(fileId) { return } setFetching(fileId) if let fa = getCachedFileAccessInfo(fileId) { if String.isNullOrWhiteSpace(fa.expireAt) || fa.expireAt.dateTimeOfString.timeIntervalSinceNow > 0 { startFetch(fa,fileTyp: fileType) return } } fetchFileAccessInfo(fileId) { (fileAccessInfo) in if let fa = fileAccessInfo { self.startFetch(fa,fileTyp: fileType) }else{ self.fetchingFinished(fileId) ProgressTaskWatcher.sharedInstance.missionFailed(fileId, result: nil) } } } fileprivate func startFetch(_ fa:FileAccessInfo,fileTyp:FileType) { func progress(_ fid:String,persent:Float) { ProgressTaskWatcher.sharedInstance.setProgress(fid, persent: persent) } func finishCallback(_ fid:String,absoluteFilePath:String?){ if String.isNullOrWhiteSpace(absoluteFilePath){ ProgressTaskWatcher.sharedInstance.missionFailed(fid, result: nil) }else{ ProgressTaskWatcher.sharedInstance.missionCompleted(fid, result: absoluteFilePath) } } if fa.isServerTypeAliOss() { self.fetchFromAliOSS(fa, fileType: fileTyp, progress:progress, callback: finishCallback) }else { self.fetchBahamutFire(fa, fileType: fileTyp, progress:progress, callback: finishCallback) } } }
mit
flow-ai/flowai-swift
FlowCore/Classes/FileTemplate.swift
1
969
import Foundation /** File response template */ public class FileTemplate : Template { /// Title of the file private(set) public var title:String! /// URL that points to the file private(set) public var url:URL! /// Optional action private(set) public var action:Action? = nil override init(_ data: [String: Any]) throws { try super.init(data) guard let title = data["title"] as? String else { throw Exception.Serialzation("file template has no title") } self.title = title guard let url = data["url"] as? String else { throw Exception.Serialzation("file template has no url") } self.url = URL(string: url) if let action = data["action"] as? [String:Any] { self.action = try Action(action) } } public required init() { super.init() } }
mit
VigaasVentures/iOSWoocommerceClient
WoocommerceClient/models/Dimension.swift
1
546
// // Dimension.swift // WoocommerceClient // // Created by Damandeep Singh on 20/02/17. // Copyright © 2017 Damandeep Singh. All rights reserved. // import UIKit import ObjectMapper class Dimension: Mappable { var length:Double? var width:Double? var height:Double? var unit:String? public required init?(map: Map) { } public func mapping(map: Map) { length <- map["length"] width <- map["width"] height <- map["height"] unit <- map["unit"] } }
mit
Erickson0806/MySwiftPlayground
MySwiftPlayground/MyPlayground.playground/Contents.swift
1
1020
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // // ////let digitNames = [123,451,23] // ////let dig = digitNames.sort(<) //// ////print(dig) // // // //let digitNames = [ // 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", // 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" //] // // //let numbers = [16, 58, 510] // // //let strings = numbers.map { // (var number) -> String in // var output = "" // while number > 0 { // output = digitNames[number % 10]! + output // number /= 10 // } // return output //} var dict = ["atk":"atk"] dict["hah"] = "hah" dict dict func swap<MyCustomType>(inout num1:MyCustomType , inout num2:MyCustomType){ let temp = num1 num1 = num2 num2 = temp } var n1 = 4 var n2 = 5 swap(&n1, num2: &n2) n1 n2 let books :[String] = ["2","1"] //strings // strings 常量被推断为字符串类型数组,即 [String] // 其值为 ["OneSix", "FiveEight", "FiveOneZero"]
apache-2.0
NelsonLeDuc/JSACollection
JSACollectionTests/SwiftTest.swift
1
5312
// // SwiftTest.swift // JSACollection // // Created by Nelson LeDuc on 12/23/15. // Copyright © 2015 Nelson LeDuc. All rights reserved. // import XCTest @testable import JSACollection class ConversionModel: NSObject { var doubleAsString: Double = 0.0 var stringAsDouble: String = "" var integerAsString: Int = 0 var stringAsInteger: String = "" var numberAsString: NSNumber! } class SwiftTest: XCTestCase { var testCollection: NSDictionary! var topLevelCollection: NSDictionary! var middleCollection: NSDictionary! var parentTestCollection: NSDictionary! var conversionCollection: NSDictionary! override func setUp() { super.setUp() let bundle = NSBundle(forClass: self.dynamicType) let firstJSON = NSData(contentsOfFile: bundle.pathForResource("test1", ofType: "json")!)! testCollection = try! NSJSONSerialization.JSONObjectWithData(firstJSON, options: []) as! NSDictionary let secondJSON = NSData(contentsOfFile: bundle.pathForResource("test2", ofType: "json")!)! topLevelCollection = try! NSJSONSerialization.JSONObjectWithData(secondJSON, options: []) as! NSDictionary let thirdJSON = NSData(contentsOfFile: bundle.pathForResource("test3", ofType: "json")!)! middleCollection = try! NSJSONSerialization.JSONObjectWithData(thirdJSON, options: []) as! NSDictionary let fourthJSON = NSData(contentsOfFile: bundle.pathForResource("test4", ofType: "json")!)! parentTestCollection = try! NSJSONSerialization.JSONObjectWithData(fourthJSON, options: []) as! NSDictionary let fifthJSON = NSData(contentsOfFile: bundle.pathForResource("testConversion", ofType: "json")!)! conversionCollection = try! NSJSONSerialization.JSONObjectWithData(fifthJSON, options: []) as! NSDictionary } func testGenerateFromClass() { let models = serializeObjects(testCollection, type: JSATestModelObject.self, nonstandard: false) XCTAssertEqual(models.count, 2) let model = models.first XCTAssertEqual(model?.nameString, "Bob Jones") XCTAssertEqual(model?.testURL.absoluteString, "http://www.google.com"); let modelNumArray = model?.randomArray as? [NSNumber] XCTAssertEqual(modelNumArray?.count, 3) XCTAssertEqual(modelNumArray![1].integerValue, 2) let homesArray = model?.homes as? [JSASubTestModelObject] XCTAssertEqual(homesArray?.count, 2); XCTAssertEqual(homesArray![0].homeName, "main"); XCTAssertNil(model?.bestHome); } func testGenerateFromClassAllowNonStandard() { let models = serializeObjects(testCollection, type: JSATestModelObject.self, nonstandard: true) XCTAssertEqual(models.count, 2) let model = models.first XCTAssertEqual(model?.nameString, "Bob Jones") XCTAssertEqual(model?.testURL.absoluteString, "http://www.google.com"); let modelNumArray = model?.randomArray as? [NSNumber] XCTAssertEqual(modelNumArray?.count, 3) XCTAssertEqual(modelNumArray![1].integerValue, 2) let homesArray = model?.homes as? [JSASubTestModelObject] XCTAssertEqual(homesArray?.count, 2); XCTAssertEqual(homesArray![0].homeName, "main"); XCTAssertNotNil(model?.bestHome); XCTAssertEqual(model?.bestHome.homeName, "Walmart"); XCTAssertNotNil(model?.bestHome.parentModelObject); } // MARK: - Object Mapper func testGenerateFromClassSubMapper() { let mapper = ObjectMapper(JSATestModelObject.self) mapper.allowNonStandard = true let subMapper = ObjectMapper(JSASubTestModelObject.self) subMapper.setterBlock = { (dict, object) in object.homeName = "My Fave" return object } mapper.addSubMapper("bestHome", mapper: subMapper) let models = serializeObjects(testCollection, mapper: mapper) XCTAssertEqual(models.count, 2); let model = models.first XCTAssertEqual(model?.nameString, "Bob Jones") XCTAssertEqual(model?.testURL.absoluteString, "http://www.google.com"); let modelNumArray = model?.randomArray as? [NSNumber] XCTAssertEqual(modelNumArray?.count, 3) XCTAssertEqual(modelNumArray![1].integerValue, 2) let homesArray = model?.homes as? [JSASubTestModelObject] XCTAssertEqual(homesArray?.count, 2); XCTAssertEqual(homesArray![0].homeName, "main"); XCTAssertNotNil(model?.bestHome); XCTAssertNil(model?.unused); XCTAssertEqual(model!.bestHome.homeName, "My Fave"); } func testNumberConverstions() { let models = serializeObjects(conversionCollection, type: ConversionModel.self) XCTAssertEqual(models.count, 1) let model = models.first! XCTAssertEqual(model.doubleAsString, 10.01) XCTAssertEqual(model.stringAsDouble, "10.01") XCTAssertEqual(model.integerAsString, 12) XCTAssertEqual(model.stringAsInteger, "12") XCTAssertEqual(model.numberAsString, NSNumber(double: 10.01)) } }
mit
DmitrySmolyakov/DocumentReader
Example/DocumentReaderSwift/DocumentReaderSwift/ViewController.swift
1
605
// // ViewController.swift // DocumentReaderSwift // // Created by Dmitry Smolyakov on 5/5/17. // Copyright © 2017 Dmitry Smolyakov. All rights reserved. // import UIKit import DocumentReader class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let docReader = DocReader(licensePath: String()) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ReactiveX/RxSwift
RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift
2
694
// // RxTableViewDelegateProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift /// For more information take a look at `DelegateProxyType`. open class RxTableViewDelegateProxy : RxScrollViewDelegateProxy { /// Typed parent object. public weak private(set) var tableView: UITableView? /// - parameter tableView: Parent object for delegate proxy. public init(tableView: UITableView) { self.tableView = tableView super.init(scrollView: tableView) } } extension RxTableViewDelegateProxy: UITableViewDelegate {} #endif
mit
jiayue198509/SmartTeaGarden_IOS
SmartTeaGarden/SmartTeaGarden/classes/Common/Common.swift
1
311
// // Common.swift // SmartTeaGarden // // Created by jiaerdong on 2017/3/9. // Copyright © 2017年 tianciqinyun. All rights reserved. // import Foundation import UIKit let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height public let kAppId = "" public let kAppKey = ""
mit
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/ImmuTable+WordPress.swift
2
447
import WordPressShared /// This lives as an extension on a separate file because it's specific to our UI /// implementation and shouldn't be in a generic ImmuTable that we might eventually /// release as a standalone library. /// extension ImmuTableViewHandler { public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionFooter(view) } }
gpl-2.0
Knowinnovation/kievents
KIEventsTests/KIEventsTests.swift
1
906
// // KIEventsTests.swift // KIEventsTests // // Created by Drew Dunne on 7/15/15. // Copyright (c) 2015 Know Innovation. All rights reserved. // import UIKit import XCTest class KIEventsTests: 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. } } }
gpl-3.0
chetca/Android_to_iOs
memuDemo/SideMenuSC/MenuCell.swift
1
1194
// // MenuCell.swift // memuDemo // // Created by Parth Changela on 09/10/16. // Copyright © 2016 Parth Changela. All rights reserved. // import UIKit class MenuCell: UITableViewCell { @IBOutlet var lblMenuRightConstraint: NSLayoutConstraint! @IBOutlet weak var lblMenuname: UILabel! @IBOutlet weak var imgIcon: UIImageView! var lblFont = UIFont() override func awakeFromNib() { super.awakeFromNib() if let window = UIApplication.shared.keyWindow { lblMenuRightConstraint.constant = -window.frame.width * 0.2 } lblMenuname.sizeToFit() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected == true { lblMenuname.textColor = UIColor.orange lblMenuname.font = UIFont(name: "Helvetica-Bold", size: 11) } else { lblMenuname.textColor = UIColor.black lblMenuname.font = UIFont(name: "Helvetica-Light", size: 11.5) } // Configure the view for the selected state } }
mit
JohnCoates/Aerial
Aerial/Source/Models/Hardware/ISSoundAdditions/SoundOutputManager+Properties.swift
1
1277
// // SoundOutputManager+Properties.swift // // // Created by Alessio Moiso on 09.03.22. // import CoreAudio public extension Sound.SoundOutputManager { /// Get the system default output device. /// /// You can use this value to interact with the device directly via /// other system calls. /// /// This value will return `nil` if there is currently no device selected in /// System Preferences > Sound > Output. var defaultOutputDevice: AudioDeviceID? { try? retrieveDefaultOutputDevice() } /// Get or set the volume of the default output device. /// /// Errors will be ignored. If you need to handle errors, /// use `readVolume` and `setVolume`. /// /// The values range between 0 and 1. var volume: Float { get { (try? readVolume()) ?? 0 } set { do { try setVolume(newValue) } catch { } } } /// Get or set whether the system default output device is muted or not. /// /// Errors will be ignored. If you need to handle errors, /// use `readMute` and `mute`. Devices that do not support muting /// will always return `false`. var isMuted: Bool { get { (try? readMute()) ?? false } set { do { try mute(newValue) } catch { } } } }
mit
whitepaperclip/Exsilio-iOS
Exsilio/MapViewController.swift
1
3050
// // MapViewController.swift // Exsilio // // Created by Nick Kezhaya on 5/5/16. // // import UIKit import CoreLocation import SwiftyJSON import FontAwesome_swift import Mapbox protocol MapViewDelegate { func mapView(_ mapView: MGLMapView, didTapAt: CLLocationCoordinate2D) } class MapViewController: UIViewController { @IBOutlet var mapView: MGLMapView! var delegate: MapViewDelegate? var startingPoint: CLLocationCoordinate2D? // Gets set when previewing a tour. var tour: JSON? let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() mapView.logoView.isHidden = true mapView.attributionButton.isHidden = true if let startingPoint = startingPoint { setCoordinate(startingPoint) } if let tour = tour { title = "Tour Map" MapHelper.drawTour(tour, mapView: mapView) MapHelper.setMapBounds(for: tour, mapView: mapView) } else { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped)) mapView.addGestureRecognizer(tapGestureRecognizer) locationManager.delegate = self if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .notDetermined { locationManager.requestWhenInUseAuthorization() } navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(done)) } } func setCoordinate(_ coordinate: CLLocationCoordinate2D) { guard let delegate = delegate else { return } delegate.mapView(mapView, didTapAt: coordinate) mapView.setCenter(coordinate, zoomLevel: 15, animated: true) } func done() { navigationController?.dismiss(animated: true, completion: nil) } @objc private func mapViewTapped(gestureRecognizer: UITapGestureRecognizer) { guard let delegate = delegate else { return } let coordinate = mapView.convert(gestureRecognizer.location(in: mapView), toCoordinateFrom: mapView) delegate.mapView(mapView, didTapAt: coordinate) } } extension MapViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedAlways || status == .authorizedWhenInUse { manager.startUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { manager.stopUpdatingLocation() if startingPoint != nil { return } if let coordinate = locations.first?.coordinate { setCoordinate(coordinate) } } }
mit
Rahulclaritaz/rahul
ixprez/ixprez/XPAutoPoplatedTableViewCell.swift
1
522
// // XPAutoPoplatedTableViewCell.swift // ixprez // // Created by Claritaz Techlabs on 17/05/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit class XPAutoPoplatedTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
modocache/Gift
Gift/Commit/Commit+Merge.swift
1
822
import LlamaKit public extension Commit { /** Merges another commit into this commit to produce an index. :param: commit The commit to merge into this one. :param: options A set of options to configure merge behavior. :returns: A result that is either: the resulting index, or an error indicating what went wrong. */ public func merge(commit: Commit, options: MergeOptions = MergeOptions()) -> Result<Index, NSError> { var out = COpaquePointer.null() var cOptions = options.cOptions let errorCode = git_merge_commits(&out, cRepository, cCommit, commit.cCommit, &cOptions) if errorCode == GIT_OK.value { return success(Index(cIndex: out)) } else { return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_merge_commits")) } } }
mit
congncif/SiFUtilities
Foundation/String+Validation.swift
2
1080
// // String+Validation.swift // SiFUtilities // // Created by FOLY on 2/7/17. // Copyright © 2017 [iF] Solution. All rights reserved. // import Foundation extension String { public var isValidEmail: Bool { let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) let result = emailTest.evaluate(with: self) return result } }
mit
jakehirzel/swift-tip-calculator
CheckPlease/ViewController.swift
1
11136
// // ViewController.swift // CheckPlease // // Created by Jake Hirzel on 7/2/16. // Copyright © 2016 Jake Hirzel. All rights reserved. // import UIKit import MessageUI import Messages class ViewController: UIViewController, MFMessageComposeViewControllerDelegate { // MARK: Properties @IBOutlet weak var totalBillLabel: UILabel! @IBOutlet weak var percentOne: UILabel! @IBOutlet weak var percentTwo: UILabel! @IBOutlet weak var percentThree: UILabel! @IBOutlet weak var tipsView: UIView! @IBOutlet weak var splitsView: UIView! @IBOutlet var tipLines: [UIStackView]! @IBOutlet weak var tipPercentLabelOne: UILabel! @IBOutlet weak var tipPercentLabelTwo: UILabel! @IBOutlet weak var tipPercentLabelThree: UILabel! @IBOutlet weak var splitPercent: UILabel! @IBOutlet weak var splitTotal: UILabel! @IBOutlet weak var splitStepper: UIStepper! @IBOutlet weak var splitNumber: UILabel! @IBOutlet weak var splitPeople: UILabel! @IBOutlet weak var splitButton: UIButton! @IBOutlet weak var eachTotal: UILabel! @IBOutlet weak var keyOne: UIButton! @IBOutlet weak var keyTwo: UIButton! @IBOutlet weak var keyThree: UIButton! @IBOutlet weak var keyFour: UIButton! @IBOutlet weak var keyFive: UIButton! @IBOutlet weak var keySix: UIButton! @IBOutlet weak var keySeven: UIButton! @IBOutlet weak var keyEight: UIButton! @IBOutlet weak var keyNine: UIButton! @IBOutlet weak var keyZero: UIButton! // @IBOutlet weak var keyPoint: UIButton! @IBOutlet weak var keyDelete: UIButton! @IBOutlet weak var cursor: UIView! // MARK: Properties // String to hold value of totalBillLabel without the $ var totalBillLabelValue = "0.00" // Create instance of TipCalculator class let tipCalculatorInstance = TipCalculator() // Create instance of KeypadBehavior class let keypadBehavior = KeypadBehavior() // Set initial state of splitsView var isSplitsViewShowing = false // Set first split view toggle (for controlling pulse behavior on share button) var isFirstSplitsView = true // Variable to Track Tag of Tip Stack Item Tapped var tipsStackTag = 0 // MARK: View Handling override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Make the cursor repeatedly blink cursor.blink() // Pulse the percentages tipPercentLabelOne.pulseOnce(0.2) tipPercentLabelTwo.pulseOnce(0.5) tipPercentLabelThree.pulseOnce(0.8) // Set up the stepper splitStepper.tintColor = UIColor.white splitStepper.minimumValue = 1 splitStepper.maximumValue = 100 splitStepper.value = 1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Convenience func processTipCalculation() { let totalBillFloat: Float? = Float(totalBillLabelValue) if totalBillFloat != nil { let tipResults = tipCalculatorInstance.tipCalculator(totalBillFloat!, people: Float(splitStepper.value)) // Convert resulting floats to $0.00 format percentOne.text = String(format: "$%.2f", tipResults.tipOne) + " / " + String(format: "$%.2f", tipResults.totalOne) percentTwo.text = String(format: "$%.2f", tipResults.tipTwo) + " / " + String(format: "$%.2f", tipResults.totalTwo) percentThree.text = String(format: "$%.2f", tipResults.tipThree) + " / " + String(format: "$%.2f", tipResults.totalThree) // Update split number splitNumber.text = String(Int(splitStepper.value)) if splitStepper.value == 1 { splitPeople.text = "Person" } else { splitPeople.text = "People" } // Set split total and each person total switch tipsStackTag { case 1: splitPercent.text = String(Int(tipCalculatorInstance.tipPercentOne * 100)) + "%" splitTotal.text = percentOne.text eachTotal.text = String(format: "$%.2f", tipResults.splitTipOne) + " / " + String(format: "$%.2f", tipResults.splitTotalOne) case 2: splitPercent.text = String(Int(tipCalculatorInstance.tipPercentTwo * 100)) + "%" splitTotal.text = percentTwo.text eachTotal.text = String(format: "$%.2f", tipResults.splitTipTwo) + " / " + String(format: "$%.2f", tipResults.splitTotalTwo) case 3: splitPercent.text = String(Int(tipCalculatorInstance.tipPercentThree * 100)) + "%" splitTotal.text = percentThree.text eachTotal.text = String(format: "$%.2f", tipResults.splitTipThree) + " / " + String(format: "$%.2f", tipResults.splitTotalThree) default: splitPercent.text = "15%" splitTotal.text = "$0.00 / $0.00" eachTotal.text = "$0.00 / $0.00" } } else { percentOne.text = "$0.00 / $0.00" percentTwo.text = "$0.00 / $0.00" percentThree.text = "$0.00 / $0.00" splitTotal.text = "$0.00 / $0.00" eachTotal.text = "$0.00 / $0.00" // Update split number splitNumber.text = String(Int(splitStepper.value)) if splitStepper.value == 1 { splitPeople.text = "Person" } else { splitPeople.text = "People" } } } // MARK: MFMessageComposeViewControllerDelegate func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { self.dismiss(animated: true, completion: nil) } // MARK: Actions @IBAction func numKeyTapped(sender: UIButton) { // Process key press let keypadOutput = keypadBehavior.keypadButtonTapped(sender, totalIn: totalBillLabelValue) // Assign returned value to totalBillLabelValue totalBillLabelValue = keypadOutput // Change the color of the totalBillLabel text after first input // UIView.animate(withDuration: 8) { // totalBillLabel.textColor = UIColor(hue: 3.59, saturation: 0.0, brightness: 0.21, alpha: 1.0) // } totalBillLabel.textColor = UIColor(hue: 3.59, saturation: 0.0, brightness: 0.21, alpha: 1.0) // Insert dollar sign and update totalBillLabel // totalBillLabel.text = String(format: "$%.2f", totalBillLabelValue) totalBillLabel.text = "$" + keypadOutput // Process the tip processTipCalculation() } @IBAction func delKeyTapped(sender: UIButton) { // Process delete key press let deleteButtonOutput = keypadBehavior.deleteButtonTapped(sender, totalIn: totalBillLabelValue) // Assign returned value to totalBillLabelValue totalBillLabelValue = deleteButtonOutput // Insert dollar sign and update totalBillLabel totalBillLabel.text = "$" + deleteButtonOutput // Process the tip processTipCalculation() } @IBAction func tipTapped(_ sender: UITapGestureRecognizer) { tipsStackTag = (sender.view?.tag)! if isSplitsViewShowing == false { UIView.transition( from: tipsView, to: splitsView, duration: 1.0, options: [UIView.AnimationOptions.transitionFlipFromRight, UIView.AnimationOptions.showHideTransitionViews] , // Pulse the share button on completion the first view only completion: { (finished: Bool) -> Void in if self.isFirstSplitsView == true { self.splitButton.pulseOnce(0.1) self.isFirstSplitsView = false } else { return } }) processTipCalculation() } else { UIView.transition( from: splitsView, to: tipsView, duration: 1.0, options: [UIView.AnimationOptions.transitionFlipFromLeft, UIView.AnimationOptions.showHideTransitionViews], // Pulse the percentage labels on completion completion: nil) } isSplitsViewShowing = !isSplitsViewShowing } @IBAction func splitStepperTapped(_ sender: UIStepper) { processTipCalculation() } @IBAction func splitShareTapped(_ sender: AnyObject) { let messageVC = MFMessageComposeViewController() if MFMessageComposeViewController.canSendText() { messageVC.messageComposeDelegate = self; // // Use iMessage App Extension if supported // if #available(iOS 10.0, *) { // let message = MSMessage() // let layout = MSMessageTemplateLayout() // layout.caption = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! // layout.subcaption = "(" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill)." // // message.layout = layout // // messageVC.message = message // // } // // // Or fall back on regular text message // else { // messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!" // } messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!" self.present(messageVC, animated: false, completion: nil) } // if MFMessageComposeViewController.canSendText() { // // messageVC.messageComposeDelegate = self; // // messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!" // // self.present(messageVC, animated: false, completion: nil) // // } } }
mit
chromatic-seashell/weibo
新浪微博/新浪微博/classes/main/GDWTabBarController.swift
1
5197
// // GDWTabBarController.swift // 新浪微博 // // Created by apple on 15/11/6. // Copyright © 2015年 apple. All rights reserved. // import UIKit class GDWTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() /* 设置tabBar的显示样式: 1在当前控制器中设置主题颜色 2在AppDelegate中设置外观颜色 UITabBar.appearance().tintColor=UIColor.orangeColor() */ tabBar.tintColor = UIColor.orangeColor() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //1.添加加号按钮到tabBar tabBar.addSubview(plusButton) //2.设置按钮的位置 let width = tabBar.bounds.width / CGFloat(childViewControllers.count) let height = tabBar.bounds.height let rect = CGRect(x: 0, y: 0, width: width, height: height) plusButton.frame = CGRectOffset(rect, 2 * width, 0) } /* +号按钮的懒加载 */ lazy var plusButton : UIButton={ let btn = UIButton(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button") btn.addTarget(self, action: Selector("plusBtnClick"), forControlEvents: UIControlEvents.TouchUpInside) return btn }() /* MARK: - 内部控制方法 如果给一个方法加上private, 那么这个方法就只能在当前文件中访问 private不光能够修饰方法, 还可以修改类/属性 注意: 按钮的点击事件是由运行循环动态派发的, 而如果将方法标记为私有的, 那这个方法在外界就拿不到, 所以动态派发时就找不到该方法 只要加上@objc, 那么就可以让私有方法支持动态派发 */ @objc private func plusBtnClick(){ GDWLog("btn") /* 使tabBarVc显示index对应的控制器 */ //selectedIndex = 2 } /* 纯代码时添加自控制器 */ func setUpChildViewController(){ /* 通过字符串生成类名,来创建对象,添加自控制器 */ addChildViewControllerWithString("GDWHomeViewController", imageName: "tabbar_home", title: "首页") addChildViewControllerWithString("GDWMessageViewController", imageName: "tabbar_message_center", title: "消息") addChildViewControllerWithString("GDWDiscoverViewController", imageName: "tabbar_discover", title: "发现") addChildViewControllerWithString("GDWMeViewController", imageName: "tabbar_profile", title: "我") /*:通过控制器对象,添加自控制器 addChildViewController(GDWHomeViewController(), imageName: "tabbar_home", title: "首页") addChildViewController(GDWMessageViewController(), imageName: "tabbar_message_center", title: "消息") addChildViewController(GDWDiscoverViewController(), imageName: "tabbar_discover", title: "发现") addChildViewController(GDWMeViewController(), imageName: "tabbar_profile", title: "我") */ } /* 通过字符串生成类名,来创建对象,添加自控制器 */ func addChildViewControllerWithString(childVcName: String, imageName:String , title:String ){ //1.获取命名空间 guard let workSpaceName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{ GDWLog("没有获取命名空间") return } //2通过字符串创建一个类名 let childVcClass:AnyObject? = NSClassFromString(workSpaceName + "." + childVcName) guard let childClass = childVcClass as? UIViewController.Type else{ GDWLog("childClass类名没有创建成功") return } //3创建自控制器 let childVc = childClass.init() //3.1设置控制器属性 //设置图片 childVc.tabBarItem.image=UIImage(named: imageName) childVc.tabBarItem.selectedImage = UIImage(named:imageName + "_highlighted") //设置标题 childVc.title=title //设置背景颜色 childVc.view.backgroundColor = UIColor.lightGrayColor() //3.2导航控制器 let nav = UINavigationController(rootViewController: childVc) //3.3添加自控制器 addChildViewController(nav) } /* 通过控制器对象,添加自控制器 */ func addChildViewController(childVc: UIViewController, imageName:String , title:String) { //1.设置控制器属性 //设置图片 childVc.tabBarItem.image=UIImage(named: imageName) childVc.tabBarItem.selectedImage = UIImage(named:imageName + "_highlighted") //设置标题 childVc.title=title //设置背景颜色 childVc.view.backgroundColor = UIColor.lightGrayColor() //2.导航控制器 let nav = UINavigationController(rootViewController: childVc) //3.添加自控制器 addChildViewController(nav) } }
apache-2.0