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
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostEditorSaveAction.swift
1
2159
import Foundation import WordPressShared /// Encapsulates the current save action of the editor, based on its /// post status, whether it's already been saved, is scheduled, etc. @objc enum PostEditorSaveAction: Int { case schedule case post case save case update } /// Some utility methods to help keep track of the current post action extension WPPostViewController { /// What action should be taken when the user taps the editor's save button? var currentSaveAction: PostEditorSaveAction { if let status = post.status, let originalStatus = post.original?.status, status != originalStatus || !post.hasRemote() { if post.isScheduled() { return .schedule } else if status == .publish { return .post } else { return .save } } else { return .update } } /// The title for the Save button, based on the current save action var saveBarButtonItemTitle: String { switch currentSaveAction { case .schedule: return NSLocalizedString("Schedule", comment: "Schedule button, this is what the Publish button changes to in the Post Editor if the post has been scheduled for posting later.") case .post: return NSLocalizedString("Publish", comment: "Label for the publish (verb) button. Tapping publishes a draft post.") case .save: return NSLocalizedString("Save", comment: "Save button label (saving content, ex: Post, Page, Comment).") case .update: return NSLocalizedString("Update", comment: "Update button label (saving content, ex: Post, Page, Comment).") } } /// The analytics stat to post when the user saves, based on the current post action func analyticsStatForSaveAction(_ action: PostEditorSaveAction) -> WPAnalyticsStat { switch action { case .post: return .editorPublishedPost case .schedule: return .editorScheduledPost case .save: return .editorSavedDraft case .update: return .editorUpdatedPost } } }
gpl-2.0
ImperialDevelopment/IDPopup
Example/IDPopup/AppDelegate.swift
1
2181
// // AppDelegate.swift // IDPopup // // Created by Michael Schoder on 08/10/2017. // Copyright (c) 2017 Michael Schoder. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
akabekobeko/examples-ios-fmdb
UsingFMDB-Swift/UsingFMDB-Swift/DAOFactory.swift
1
1576
// // DAOFactory.swift // UsingFMDB-Swift // // Created by akabeko on 2016/12/22. // Copyright © 2016年 akabeko. All rights reserved. // import UIKit import FMDB /// Factory of a data access objects. class DAOFactory: NSObject { /// Path of the database file. private let filePath: String /// Initialize the instance. override init() { self.filePath = DAOFactory.databaseFilePath() super.init() // For debug print(self.filePath) } /// Initialize the instance with the path of the database file. /// /// - Parameter filePath: the path of the database file. init(filePath: String) { self.filePath = filePath super.init() } /// Create the data access object of the books. /// /// - Returns: Instance of the data access object. func bookDAO() -> BookDAO? { if let db = self.connect() { return BookDAO(db: db) } return nil } /// Connect to the database. /// /// - Returns: Connection instance if successful, nil otherwise. private func connect() -> FMDatabase? { let db = FMDatabase(path: self.filePath) return (db?.open())! ? db : nil } /// Get the path of database file. /// /// - Returns: Path of the database file. private static func databaseFilePath() -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let dir = paths[0] as NSString return dir.appendingPathComponent("app.db") } }
mit
bmichotte/HSTracker
HSTracker/Logging/CardIds/Shaman.swift
1
7726
/* This file is generated by https://github.com/HearthSim/HearthDb The MIT License (MIT) Copyright (c) 2016 HearthSim 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. Source: https://github.com/HearthSim/HearthDb */ import Foundation extension CardIds.Collectible { struct Shaman { static let TuskarrTotemic = "AT_046" static let DraeneiTotemcarver = "AT_047" static let HealingWave = "AT_048" static let ThunderBluffValiant = "AT_049" static let ChargedHammer = "AT_050" static let ElementalDestruction = "AT_051" static let TotemGolem = "AT_052" static let AncestralKnowledge = "AT_053" static let TheMistcaller = "AT_054" static let LavaShock = "BRM_011" static let FireguardDestroyer = "BRM_012" static let JinyuWaterspeaker = "CFM_061" static let CallInTheFinishers = "CFM_310" static let JadeChieftain = "CFM_312" static let FindersKeepers = "CFM_313" static let WhiteEyes = "CFM_324" static let Devolve = "CFM_696" static let LotusIllusionist = "CFM_697" static let JadeLightning = "CFM_707" static let JadeClaws = "CFM_717" static let FrostShock = "CS2_037" static let AncestralSpirit = "CS2_038" static let Windfury = "CS2_039" static let AncestralHealing = "CS2_041" static let FireElemental = "CS2_042" static let RockbiterWeapon = "CS2_045" static let Bloodlust = "CS2_046" static let FarSight = "CS2_053" static let LightningBolt = "EX1_238" static let LavaBurst = "EX1_241" static let DustDevil = "EX1_243" static let TotemicMight = "EX1_244" static let EarthShock = "EX1_245" static let Hex = "EX1_246" static let StormforgedAxe = "EX1_247" static let FeralSpirit = "EX1_248" static let EarthElemental = "EX1_250" static let ForkedLightning = "EX1_251" static let UnboundElemental = "EX1_258" static let LightningStorm = "EX1_259" static let FlametongueTotem = "EX1_565" static let Doomhammer = "EX1_567" static let ManaTideTotem = "EX1_575" static let Windspeaker = "EX1_587" static let Reincarnate = "FP1_025" static let AncestorsCall = "GVG_029" static let Powermace = "GVG_036" static let WhirlingZapOMatic = "GVG_037" static let Crackle = "GVG_038" static let VitalityTotem = "GVG_039" static let SiltfinSpiritwalker = "GVG_040" static let Neptulon = "GVG_042" static let DunemaulShaman = "GVG_066" static let Thrall = "HERO_02" static let MorglTheOracle = "HERO_02a" static let WickedWitchdoctor = "KAR_021" static let SpiritClaws = "KAR_063" static let MaelstromPortal = "KAR_073" static let RumblingElemental = "LOE_016" static let TunnelTrogg = "LOE_018" static let EveryfinIsAwesome = "LOE_113" static let AlakirTheWindlord = "NEW1_010" static let PrimalFusion = "OG_023" static let FlamewreathedFaceless = "OG_024" static let EternalSentinel = "OG_026" static let Evolve = "OG_027" static let ThingFromBelow = "OG_028" static let HammerOfTwilight = "OG_031" static let Stormcrack = "OG_206" static let HallazealTheAscended = "OG_209" static let MasterOfEvolution = "OG_328" static let AirElemental = "UNG_019" static let Volcano = "UNG_025" static let PrimalfinTotem = "UNG_201" static let FirePlumeHarbinger = "UNG_202" static let StoneSentinel = "UNG_208" static let KalimosPrimalLord = "UNG_211" static let TidalSurge = "UNG_817" static let HotSpringGuardian = "UNG_938" static let UniteTheMurlocs = "UNG_942" static let SpiritEcho = "UNG_956" } } extension CardIds.NonCollectible { struct Shaman { static let KalimosPrimalLord_InvocationOfEarth = "UNG_211a" static let AncestralHealing_AncestralInfusionEnchantment = "CS2_041e" static let RockbiterWeapon_RockbiterWeaponEnchantment = "CS2_045e" static let Bloodlust_BloodlustEnchantment = "CS2_046e" static let TotemicCall = "CS2_049" static let SearingTotem = "CS2_050" static let StoneclawTotem = "CS2_051" static let WrathOfAirTotem = "CS2_052" static let TotemicMight_TotemicMightEnchantment = "EX1_244e" static let Hex_HexxedEnchantment = "EX1_246e" static let FlametongueTotem_FlametongueEnchantment = "EX1_565o" static let HealingTotem = "NEW1_009" static let AncestralSpirit_AncestralSpiritEnchantment = "CS2_038e" static let FarSight_FarSightEnchantment = "CS2_053e" static let UnboundElemental_OverloadingEnchantment = "EX1_258e" static let SpiritWolf = "EX1_tk11" static let Powermace_PoweredEnchantment = "GVG_036e" static let LavaShock_LavaShockToken = "BRM_011t" static let DraeneiTotemcarver_ExperiencedEnchantment = "AT_047e" static let ThunderBluffValiant_PowerOfTheBluffEnchantment = "AT_049e" static let ChargedHammer_LightningJoltToken = "AT_050t" static let JusticarTrueheart_TotemicSlam = "AT_132_SHAMAN" static let JusticarTrueheart_HealingTotem = "AT_132_SHAMANa" static let JusticarTrueheart_SearingTotem = "AT_132_SHAMANb" static let JusticarTrueheart_StoneclawTotem = "AT_132_SHAMANc" static let JusticarTrueheart_WrathOfAirTotem = "AT_132_SHAMANd" static let DanEmmons = "CRED_47" static let TotemicCall_TotemicCallHeroSkins = "CS2_049_H1" static let TotemicSlamHeroSkins = "CS2_049_H1_AT_132" static let SecondClassShamanTavernBrawl = "TB_ClassRandom_Shaman" static let ElementalEruptionTavernBrawl = "TB_CoOpv3_006" static let TunnelTrogg_TroggNoStupidEnchantment = "LOE_018e" static let HammerofTwilight_TwilightElemental = "OG_031a" static let EvolveTavernBrawl = "TB_OG_027" static let CallintheFinishers_MurlocRazorgillToken = "CFM_310t" static let WhiteEyes_TheStormGuardianToken = "CFM_324t" static let StoneSentinel_RockElementalToken = "UNG_208t" static let KalimosPrimalLord_StoneElemental = "UNG_211aa" static let KalimosPrimalLord_InvocationOfWater = "UNG_211b" static let KalimosPrimalLord_InvocationOfFire = "UNG_211c" static let KalimosPrimalLord_InvocationOfAir = "UNG_211d" static let UnitetheMurlocs_MegafinToken = "UNG_942t" static let SpiritEcho_EchoedSpiritEnchantment = "UNG_956e" } }
mit
pecuniabanking/pecunia-client
Source/ChipcardManager.swift
1
11957
// // ChipcardManager.swift // Pecunia // // Created by Frank Emminghaus on 24.06.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation import HBCI4Swift var _manager:ChipcardManager! @objcMembers open class CardBankData : NSObject { var name:String; var bankCode:String; var country:String; var host:String; var userId:String; init(name:String, bankCode:String, country:String, host:String, userId:String) { self.name = name; self.bankCode = bankCode; self.country = country; self.host = host; self.userId = userId; } } @objc open class ChipcardManager : NSObject { var card: HBCISmartcardDDV!; public override init() { super.init(); } func stringToBytes(_ s:NSString) ->Data { let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: s.length/2); for i in 0 ..< s.length/2 { var value:UInt32 = 0; let hexString = s.substring(with: NSMakeRange(2*i, 2)); let scanner = Scanner(string: hexString); scanner.scanHexInt32(&value); buffer[i] = UInt8(value & 0xff); } let result = Data(bytes: UnsafePointer<UInt8>(buffer), count: s.length/2); buffer.deinitialize(count: s.length/2); return result; } func bytesToString(_ data:Data) ->NSString { let ret = NSMutableString(); let p = UnsafeMutablePointer<UInt8>(mutating: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)); for i in 0 ..< data.count { ret.appendFormat("%0.2X", p[i]); } return ret; } open func isCardConnected() ->Bool { if card != nil { return card.isConnected(); } return false; } @objc open func getReaders() ->Array<String>? { return HBCISmartcardDDV.readers(); } open func connectCard(_ userIdName:String?) throws { // check if reader is still available if !card.isReaderConnected() { throw NSError.errorWithMsg(msgId: "AP366", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP366", comment: ""); alert.runModal(); return false; */ } if !card.isConnected() { var result = card.connect(1); if result == HBCISmartcard.ConnectResult.not_supported { throw NSError.errorWithMsg(msgId: "AP365", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP365", comment: ""); alert.runModal(); return false; */ } if result == HBCISmartcard.ConnectResult.no_card { // no card inserted. Open dialog to wait for it let controller = ChipcardRequestController(windowNibName: "ChipcardRequestController"); controller._userIdName = userIdName; if NSApp.runModal(for: controller.window!) == NSApplication.ModalResponse.cancel { // cancelled throw HBCIError.userAbort; //return false; } result = controller.connectResult; } // verify card let controller = ChipcardPinRequestController(windowNibName: "ChipcardPinRequestController"); if NSApp.runModal(for: controller.window!) == NSApplication.ModalResponse.cancel { // verification not o.k. throw NSError.errorWithMsg(msgId: "AP369", titleId: "AP368"); } /* let notificationController = NotificationWindowController(message: NSLocalizedString("AP351", comment:""), title: NSLocalizedString("AP357", comment:"")); notificationController?.showWindow(self); notificationController?.window?.makeKeyAndOrderFront(self); if !card.verifyPin() { notificationController?.window?.close(); throw NSError.errorWithMsg(msgId: "AP369", titleId: "AP368"); } notificationController?.window?.close(); */ } } open func requestCardForUser(_ user:BankUser) throws { if card == nil { // no card object created yet if let readers = HBCISmartcardDDV.readers() { if readers.count == 0 { // no card readers found throw NSError.errorWithMsg(msgId: "AP364", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP364", comment: ""); alert.runModal(); return false; */ } var idx = user.ddvReaderIdx.intValue if idx >= readers.count { logWarning("Index in user information is wrong"); idx = 0; } let readerName = readers[idx]; card = HBCISmartcardDDV(readerName: readerName); } else { throw NSError.errorWithMsg(msgId: "AP364", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP364", comment: ""); alert.runModal(); return false; */ } } // connect card try connectCard(user.name); // check user if let bankData = card.getBankData(1) { if bankData.userId == user.userId { return; } else { // card is connected but wrong user logError("HBCIChipcard: Karte vorhanden aber falscher Anwender(%@)", bankData.userId); throw NSError.errorWithMsg(msgId: "AP362", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; let msg = String(format: NSLocalizedString("AP362", comment: ""), bankData.userId, user.userId); alert.messageText = msg; alert.runModal(); return false; */ } } else { logError("HBCIChipcard: Bankdaten konnten nicht gelesen werden"); throw NSError.errorWithMsg(msgId: "AP363", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP363", comment: ""); alert.runModal(); return false; */ } } @objc open func requestCardForReader(_ readerName:String) throws { if card == nil { card = HBCISmartcardDDV(readerName: readerName); } else if card.readerName != readerName { card.disconnect(); card = HBCISmartcardDDV(readerName: readerName); } // connect card try connectCard(nil); } open func initializeChipcard(_ paramString:NSString) ->NSString? { let params = paramString.components(separatedBy: "|"); if params.count != 2 { logError("Falsche Parameter bei der Chipkarteninitialisierung"); return nil; } // card should already be initialized... if card == nil { return nil; } return nil; } @objc open func getBankData() ->CardBankData? { if let data = card.getBankData(1) { return CardBankData(name: data.name, bankCode: data.bankCode, country: data.country, host: data.host, userId: data.userId); } return nil; } @objc open func writeBankData(_ data:CardBankData) ->Bool { let hbciData = HBCICardBankData(name: data.name, bankCode: data.bankCode, country: data.country, host: data.host, hostAdd: "", userId: data.userId, commtype: 0); return card.writeBankData(1, data: hbciData); } open func readBankData(_ paramString:NSString) ->NSString? { let idx = paramString.integerValue; if let data = card.getBankData(idx) { return NSString(format: "%@|%@|%@|%@", data.country, data.bankCode, data.host, data.userId); } return nil; } open func readKeyData(_ paramString:NSString) ->NSString? { /* let sigid = card.getSignatureId(); if sigid == 0xffff { logError("Could not read signature id"); return nil; } let keys = card.getKeyData(); if keys.count != 2 { logError("Error reading key information from chipcard"); return nil; } return NSString(format: "%d|%i|%i|%i|%i", sigid, keys[0].keyNumber, keys[0].keyVersion, keys[1].keyNumber, keys[1].keyVersion); */ return nil; } open func enterPin(_ paramString:NSString) ->Bool { //return card.verifyPin(); // card should already been verified return true; } open func saveSigId(_ paramString:NSString) ->Bool { //let sigid = paramString.integerValue; /* if !card.writeSignatureId(sigid) { logError("Error while saving new signature id to chipcard"); return false; } */ return true; } open func sign(_ paramString:NSString) ->NSString? { //let hash = stringToBytes(paramString); /* if let sig = card.sign(hash) { return bytesToString(sig); } */ return nil; } open func encrypt(_ paramString:NSString) ->NSString? { //let keyNum = paramString.integerValue; /* if let keys = card.getEncryptionKeys(UInt8(keyNum)) { return NSString(format: "%@|%@", bytesToString(keys.plain), bytesToString(keys.encrypted)); } */ return nil; } open func decrypt(_ paramString:NSString) ->NSString? { let params = paramString.components(separatedBy: "|"); if params.count != 2 { logError("Fehlende Parameter zum Entschlüsseln"); return nil; } //let keyNum = Int(params[0])!; //let encKey = params[1] as NSString; /* if let plain = card.decryptKey(UInt8(keyNum), encrypted: stringToBytes(encKey)) { return bytesToString(plain); } */ return nil; } open func close() { if card != nil { card.disconnect(); card = nil; } } @objc open var cardNumber:NSString { get { if let cardNumber = card.cardNumber { return cardNumber; } else { if card.getCardID() { if let cardNumber = card.cardNumber { return cardNumber; } } return "<unbekannt>"; } } } @objc public static var manager:ChipcardManager { get { if let manager = _manager { return manager; } else { _manager = ChipcardManager(); return _manager; } } } }
gpl-2.0
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Models/Mapping/AttachmentModelMapping.swift
2
2246
// // AttachmentModelMapping.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 16/01/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift extension Attachment: ModelMappeable { func map(_ values: JSON, realm: Realm?) { if self.identifier == nil { self.identifier = String.random(30) } if let authorName = values["author_name"].string { self.title = "@\(authorName)" } if let title = values["title"].string { self.title = title } if let titleLink = values["title_link"].string { self.titleLink = titleLink } self.collapsed = values["collapsed"].bool ?? false self.text = values["text"].string self.thumbURL = values["thumb_url"].string self.color = values["color"].string self.titleLinkDownload = values["title_link_download"].bool ?? true self.imageURL = encode(url: values["image_url"].string) self.imageType = values["image_type"].string self.imageSize = values["image_size"].int ?? 0 self.audioURL = encode(url: values["audio_url"].string) self.audioType = values["audio_type"].string self.audioSize = values["audio_size"].int ?? 0 self.videoURL = encode(url: values["video_url"].string) self.videoType = values["video_type"].string self.videoSize = values["video_size"].int ?? 0 // Override title & value from fields object if let fields = values["fields"].array?.first { self.title = fields["title"].string ?? self.title self.text = fields["value"].string ?? self.text } } fileprivate func encode(url: String?) -> String? { guard let url = url else { return nil } let parts = url.components(separatedBy: "/") var encoded: [String] = [] for part in parts { if let string = part.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { encoded.append(string) } else { encoded.append(part) } } return encoded.joined(separator: "/") } }
mit
lifcio/todo-app-syncano
todo-app-syncano/String+localization.swift
1
366
// // String+localization.swift // todo-app-syncano // // Created by Mariusz Wisniewski on 8/14/15. // Copyright (c) 2015 Mariusz Wisniewski. All rights reserved. // extension String { func localized(comment: String = "") -> String { return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: comment) } }
mit
jacobwhite/firefox-ios
Extensions/NotificationService/ExtensionProfile.swift
7
1673
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Shared import Sync // This is a cut down version of the Profile. // This will only ever be used in the NotificationService extension. // It allows us to customize the SyncDelegate, and later the SyncManager. class ExtensionProfile: BrowserProfile { init(localName: String) { super.init(localName: localName, clear: false) self.syncManager = ExtensionSyncManager(profile: self) } } fileprivate let extensionSafeNames = Set(["clients"]) // Mock class required by `BrowserProfile` open class PanelDataObservers { init(profile: Any) {} } // Mock class required by `BrowserProfile` open class SearchEngines { init(prefs: Any, files: Any) {} } class ExtensionSyncManager: BrowserProfile.BrowserSyncManager { init(profile: ExtensionProfile) { super.init(profile: profile) } // We don't want to send ping data at all while we're in the extension. override func canSendUsageData() -> Bool { return false } // We should probably only want to sync client commands while we're in the extension. override func syncNamedCollections(why: SyncReason, names: [String]) -> Success { let names = names.filter { extensionSafeNames.contains($0) } return super.syncNamedCollections(why: why, names: names) } override func takeActionsOnEngineStateChanges<T: EngineStateChanges>(_ changes: T) -> Deferred<Maybe<T>> { return deferMaybe(changes) } }
mpl-2.0
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Module/Main/Controller/BaseTableViewController.swift
1
2678
// // BaseTableViewController.swift // SinaWeiBo // // Created by 何启亮 on 16/5/12. // Copyright © 2016年 HQL. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { // MARK: - 属性 var isLogin: Bool = HQLUserAccountViewModel.shareInstance.isUserLogin override func viewDidLoad() { if isLogin{ // 如果登陆了,就照常加载 super.viewDidLoad() }else{ // 如果没有登陆,则进入访客视图 self.view = visitor visitor.delegate = self if self.isKindOfClass(HomeController) { visitor.startRotationAnimation() }else if self is MessageController{ visitor.setupVisitorInfo("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") }else if self is DiscoveryController{ visitor.setupVisitorInfo("visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") }else if self is ProfileController{ visitor.setupVisitorInfo("visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人") } // 没有登录才设置导航栏 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(visitorViewDidClickRegister)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(visitorViewDidClickLogin)) } } // MARK: - 懒加载 lazy var visitor: visitorView = visitorView() } // MARK: - 协议 /** * switf 中遵守协议有两种方式,一种是在class定义的时候,在父类后面加上“,协议名”,一种是扩展对象实现协议: 可以将一个协议对应的代码写在一起 */ extension BaseTableViewController: visitorViewDelegate{ // 实现协议方法 // 登录 func visitorViewDidClickLogin() { // CZPrint(items: "登录") // modal 出一个控制器 let oauthVC = HQLOauthViewController() let nav: UINavigationController = UINavigationController(rootViewController: oauthVC) self.presentViewController(nav, animated: true, completion: nil) } // 注册 func visitorViewDidClickRegister() { print("注册") } }
apache-2.0
benlangmuir/swift
validation-test/compiler_crashers_fixed/25947-llvm-tinyptrvector-swift-valuedecl-push-back.swift
65
452
// 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 import a func a}struct B<T where H.B:A{struct c}var a
apache-2.0
xixi197/XXColorTheme
Classes/UIKit/UIProgressView+XXColorStyle.swift
1
1372
// // UIProgressView+XXColorStyle.swift // XXColorTheme // // Created by xixi197 on 16/1/21. // Copyright © 2016年 xixi197. All rights reserved. // import UIKit import RxSwift import NSObject_Rx extension UIProgressView { private struct AssociatedKeys { static var ProgressTintColorStyle = "xx_progressTintColorStyle" static var TrackTintColorStyle = "xx_trackTintColorStyle" } var xx_progressTintColorStyle: XXColorStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.ProgressTintColorStyle) as? String ?? "" return XXColorStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.ProgressTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addColorStyle(newValue, forSelector: "setProgressTintColor:") } } var xx_trackTintColorStyle: XXColorStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.TrackTintColorStyle) as? String ?? "" return XXColorStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.TrackTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addColorStyle(newValue, forSelector: "setTrackTintColor:") } } }
mit
wireapp/wire-ios-sync-engine
Source/UserSession/Search/SearchResult.swift
1
6239
// // 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 public struct SearchResult { public var contacts: [ZMSearchUser] public var teamMembers: [ZMSearchUser] public var addressBook: [ZMSearchUser] public var directory: [ZMSearchUser] public var conversations: [ZMConversation] public var services: [ServiceUser] } extension SearchResult { public init?(payload: [AnyHashable: Any], query: SearchRequest.Query, searchOptions: SearchOptions, contextProvider: ContextProvider) { guard let documents = payload["documents"] as? [[String: Any]] else { return nil } let filteredDocuments = documents.filter { (document) -> Bool in let name = document["name"] as? String let handle = document["handle"] as? String return !query.isHandleQuery || name?.hasPrefix("@") ?? true || handle?.contains(query.string.lowercased()) ?? false } let searchUsers = ZMSearchUser.searchUsers(from: filteredDocuments, contextProvider: contextProvider) contacts = [] addressBook = [] directory = searchUsers.filter({ !$0.isConnected && !$0.isTeamMember }) conversations = [] services = [] if searchOptions.contains(.teamMembers) && searchOptions.isDisjoint(with: .excludeNonActiveTeamMembers) { teamMembers = searchUsers.filter({ $0.isTeamMember }) } else { teamMembers = [] } } public init?(servicesPayload servicesFullPayload: [AnyHashable: Any], query: String, contextProvider: ContextProvider) { guard let servicesPayload = servicesFullPayload["services"] as? [[String: Any]] else { return nil } let searchUsersServices = ZMSearchUser.searchUsers(from: servicesPayload, contextProvider: contextProvider) contacts = [] teamMembers = [] addressBook = [] directory = [] conversations = [] services = searchUsersServices } public init?(userLookupPayload: [AnyHashable: Any], contextProvider: ContextProvider ) { guard let userLookupPayload = userLookupPayload as? [String: Any], let searchUser = ZMSearchUser.searchUser(from: userLookupPayload, contextProvider: contextProvider), searchUser.user == nil || searchUser.user?.isTeamMember == false else { return nil } contacts = [] teamMembers = [] addressBook = [] directory = [searchUser] conversations = [] services = [] } mutating func extendWithMembershipPayload(payload: MembershipListPayload) { payload.members.forEach { (membershipPayload) in let searchUser = teamMembers.first(where: { $0.remoteIdentifier == membershipPayload.userID }) let permissions = membershipPayload.permissions.flatMap({ Permissions(rawValue: $0.selfPermissions) }) searchUser?.updateWithTeamMembership(permissions: permissions, createdBy: membershipPayload.createdBy) } } mutating func filterBy(searchOptions: SearchOptions, query: String, contextProvider: ContextProvider) { guard searchOptions.contains(.excludeNonActivePartners) else { return } let selfUser = ZMUser.selfUser(in: contextProvider.viewContext) let isHandleQuery = query.hasPrefix("@") let queryWithoutAtSymbol = (isHandleQuery ? String(query[query.index(after: query.startIndex)...]) : query).lowercased() teamMembers = teamMembers.filter({ $0.teamRole != .partner || $0.teamCreatedBy == selfUser.remoteIdentifier || isHandleQuery && $0.handle == queryWithoutAtSymbol }) } func copy(on context: NSManagedObjectContext) -> SearchResult { let copiedConversations = conversations.compactMap { context.object(with: $0.objectID) as? ZMConversation } return SearchResult(contacts: contacts, teamMembers: teamMembers, addressBook: addressBook, directory: directory, conversations: copiedConversations, services: services) } func union(withLocalResult result: SearchResult) -> SearchResult { return SearchResult(contacts: result.contacts, teamMembers: result.teamMembers, addressBook: result.addressBook, directory: directory, conversations: result.conversations, services: services) } func union(withServiceResult result: SearchResult) -> SearchResult { return SearchResult(contacts: contacts, teamMembers: teamMembers, addressBook: addressBook, directory: directory, conversations: conversations, services: result.services) } func union(withDirectoryResult result: SearchResult) -> SearchResult { return SearchResult(contacts: contacts, teamMembers: Array(Set(teamMembers).union(result.teamMembers)), addressBook: addressBook, directory: result.directory, conversations: conversations, services: services) } }
gpl-3.0
imex94/KCLTech-iOS-Sessions-2014-2015
session208/session208/UIPathFollower.swift
1
1224
// // UIPathFollower.swift // session208 // // Created by Clarence Ji on 1/26/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import UIKit class UIPathFollower: UIImageView { func startAnimate(parent: UIViewController) { image = UIImage(named: "satellite") hidden = false bounds.size.width = 100 bounds.size.height = 100 center = parent.view.center var animation = CAKeyframeAnimation(keyPath: "position") animation.path = CGPathCreateWithEllipseInRect(CGRectMake(-100, -100, 200, 200), nil) animation.duration = 10 animation.repeatCount = 1000 animation.calculationMode = kCAAnimationPaced animation.rotationMode = kCAAnimationRotateAuto animation.additive = true parent.view.addSubview(self) layer.addAnimation(animation, forKey: "rotateAnimation") } func stopAnimate() { var fadeOut = CABasicAnimation(keyPath: "opacity") fadeOut.toValue = 0.0 fadeOut.duration = 2.0 fadeOut.fillMode = kCAFillModeForwards fadeOut.removedOnCompletion = false self.layer.addAnimation(fadeOut, forKey: "fadeout") } }
mit
noppoMan/Suv
Tests/SuvTests/TcpTests.swift
1
2112
// // TcpTests.swift // Suv // // Created by Yuki Takei on 2/15/16. // Copyright © 2016 MikeTOKYO. All rights reserved. // import XCTest import CLibUv @testable import Suv // Simple Echo Server private func launchServer() throws -> TCP { let server = TCP() let addr = Address(host: "0.0.0.0", port: 9999) try server.bind(addr) try server.listen { result in switch result { case .success(_): let client = TCP() try! server.accept(client) client.read { result in switch result { case .success(let data): client.write(data) case .failure(let error): client.close() XCTFail("\(error)") } } case .failure(let error): XCTFail("\(error)") } } return server } class TcpTests: XCTestCase { static var allTests: [(String, (TcpTests) -> () throws -> Void)] { return [ ("testTcpConnect", testTcpConnect) ] } func testTcpConnect(){ waitUntil(5, description: "TCPServer Connect") { done in let server = try! launchServer() let client = TCP() client.connect(Address(host: "0.0.0.0", port: 9999)) { result in switch result { case .success(_): client.write("Hi!".data) client.read { result in switch result { case .success(let data): XCTAssertEqual(data.utf8String!, "Hi!") server.close() Loop.defaultLoop.stop() done() case .failure(let error): client.close() XCTFail("\(error)") } } case .failure(let error): XCTFail("\(error)") } } } } }
mit
objecthub/swift-lispkit
Sources/LispKit/Data/Cell.swift
1
1210
// // Cell.swift // LispKit // // Created by Matthias Zenger on 07/02/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// /// `Cell` implements a mutable expression. /// public final class Cell: ManagedObject, CustomStringConvertible { /// The current value of the cell. public var value: Expr /// Create a new cell with a given initial value. public init(_ value: Expr) { self.value = value } /// Clear cell value. public override func clean() { self.value = .undef } /// A string representation of this cell. public var description: String { return "«cell \(self.value)»" } }
apache-2.0
jtbandes/swift-compiler-crashes
fixed/27255-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
4
294
// 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 a{ {{} class C func b{class b{ class B{ struct S{var b{struct S{ class A{ func b{[b{class b{{ } let a{ let a{ func b{a=a
mit
kareman/SwiftShell
Sources/SwiftShell/Files.swift
1
2965
/* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com) * */ import Foundation /** The default FileManager */ public let Files = FileManager.default /** Appends file or directory url to directory url */ public func + (leftpath: URL, rightpath: String) -> URL { leftpath.appendingPathComponent(rightpath) } /** Error type for file commands. */ public enum FileError: Error { case notFound(path: String) public static func checkFile(_ path: String) throws { if !Files.fileExists(atPath: path) { throw notFound(path: path) } } } extension FileError: CustomStringConvertible { public var description: String { switch self { case let .notFound(path): return "Error: '\(path)' does not exist." } } } /** Opens a file for reading, throws if an error occurs. */ public func open(_ path: String, encoding: String.Encoding = main.encoding) throws -> ReadableStream { // URL does not handle leading "~/" let fixedpath = path.hasPrefix("~") ? NSString(string: path).expandingTildeInPath : path return try open(URL(fileURLWithPath: fixedpath, isDirectory: false), encoding: encoding) } /** Opens a file for reading, throws if an error occurs. */ public func open(_ path: URL, encoding: String.Encoding = main.encoding) throws -> ReadableStream { do { return FileHandleStream(try FileHandle(forReadingFrom: path), encoding: encoding) } catch { try FileError.checkFile(path.path) throw error } } /** Opens a file for writing, creates it first if it doesn't exist. If the file already exists and overwrite=false, the writing will begin at the end of the file. - parameter overwrite: If true, replace the file if it exists. */ public func open(forWriting path: URL, overwrite: Bool = false, encoding: String.Encoding = main.encoding) throws -> FileHandleStream { if overwrite || !Files.fileExists(atPath: path.path) { try Files.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) _ = Files.createFile(atPath: path.path, contents: nil, attributes: nil) } do { let filehandle = try FileHandle(forWritingTo: path) _ = filehandle.seekToEndOfFile() return FileHandleStream(filehandle, encoding: encoding) } catch { try FileError.checkFile(path.path) throw error } } /** Opens a file for writing, creates it first if it doesn't exist. If the file already exists and overwrite=false, the writing will begin at the end of the file. - parameter overwrite: If true, replace the file if it exists. */ public func open(forWriting path: String, overwrite: Bool = false, encoding: String.Encoding = main.encoding) throws -> FileHandleStream { let fixedpath = path.hasPrefix("~") ? NSString(string: path).expandingTildeInPath : path return try open(forWriting: URL(fileURLWithPath: fixedpath, isDirectory: false), overwrite: overwrite, encoding: encoding) }
mit
vitormesquita/Malert
Malert/Classes/Base/BaseMalertViewController.swift
1
1195
// // BaseMalertViewController.swift // Pods // // Created by Vitor Mesquita on 01/11/16. // // import UIKit public class BaseMalertViewController: UIViewController { private(set) var keyboardRect = CGRect.zero func listenKeyboard(){ NotificationCenter.default.addObserver( self, selector: #selector(BaseMalertViewController.keyboardWillShow(sender:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(BaseMalertViewController.keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil ) } @objc func keyboardWillShow(sender: NSNotification){ guard let userInfo = sender.userInfo else { return } if let keyboardRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue{ self.keyboardRect = keyboardRect } } @objc func keyboardWillHide(sender: NSNotification){ keyboardRect = CGRect.zero } }
mit
CosmicMind/Motion
Sources/Extensions/Motion+CALayer.swift
3
9680
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit internal extension CALayer { /// Swizzle the `add(_:forKey:) selector. static var motionAddedAnimations: [(CALayer, String, CAAnimation)]? = { let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) { method_exchangeImplementations(originalMethod, swizzledMethod) } } swizzling(CALayer.self, #selector(add(_:forKey:)), #selector(motionAdd(anim:forKey:))) return nil }() @objc dynamic func motionAdd(anim: CAAnimation, forKey: String?) { if nil == CALayer.motionAddedAnimations { motionAdd(anim: anim, forKey: forKey) } else { let copiedAnim = anim.copy() as! CAAnimation copiedAnim.delegate = nil // having delegate resulted some weird animation behavior CALayer.motionAddedAnimations?.append((self, forKey!, copiedAnim)) } } /// Retrieves all currently running animations for the layer. var animations: [(String, CAAnimation)] { guard let keys = animationKeys() else { return [] } return keys.map { return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation) } } /** Concats transforms and returns the result. - Parameters layer: A CALayer. - Returns: A CATransform3D. */ func flatTransformTo(layer: CALayer) -> CATransform3D { var l = layer var t = l.transform while let sl = l.superlayer, self != sl { t = CATransform3DConcat(sl.transform, t) l = sl } return t } /// Removes all Motion animations. func removeAllMotionAnimations() { guard let keys = animationKeys() else { return } for animationKey in keys where animationKey.hasPrefix("motion.") { removeAnimation(forKey: animationKey) } } } public extension CALayer { /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: CAAnimation...) { animate(animations) } /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: [CAAnimation]) { for animation in animations { if let a = animation as? CABasicAnimation { a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!) } updateModel(animation) if let a = animation as? CAPropertyAnimation { add(a, forKey: a.keyPath!) } else if let a = animation as? CAAnimationGroup { add(a, forKey: nil) } else if let a = animation as? CATransition { add(a, forKey: kCATransition) } } } /** A function that accepts a list of MotionAnimation values and executes them. - Parameter animations: A list of MotionAnimation values. */ func animate(_ animations: MotionAnimation...) { animate(animations) } /** A function that accepts an Array of MotionAnimation values and executes them. - Parameter animations: An Array of MotionAnimation values. - Parameter completion: An optional completion block. */ func animate(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { startAnimations(animations, completion: completion) } } fileprivate extension CALayer { /** A function that executes an Array of MotionAnimation values. - Parameter _ animations: An Array of MotionAnimations. - Parameter completion: An optional completion block. */ func startAnimations(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { let ts = MotionAnimationState(animations: animations) Motion.delay(ts.delay) { [weak self, ts = ts, completion = completion] in guard let `self` = self else { return } var anims = [CABasicAnimation]() var duration = 0 == ts.duration ? 0.01 : ts.duration if let v = ts.backgroundColor { let a = MotionCAAnimation.background(color: UIColor(cgColor: v)) a.fromValue = self.backgroundColor anims.append(a) } if let v = ts.borderColor { let a = MotionCAAnimation.border(color: UIColor(cgColor: v)) a.fromValue = self.borderColor anims.append(a) } if let v = ts.borderWidth { let a = MotionCAAnimation.border(width: v) a.fromValue = NSNumber(floatLiteral: Double(self.borderWidth)) anims.append(a) } if let v = ts.cornerRadius { let a = MotionCAAnimation.corner(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.cornerRadius)) anims.append(a) } if let v = ts.transform { let a = MotionCAAnimation.transform(v) a.fromValue = NSValue(caTransform3D: self.transform) anims.append(a) } if let v = ts.spin { var a = MotionCAAnimation.spin(x: v.x) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(y: v.y) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(z: v.z) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.position { let a = MotionCAAnimation.position(v) a.fromValue = NSValue(cgPoint: self.position) anims.append(a) } if let v = ts.opacity { let a = MotionCAAnimation.fade(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.opacity.rawValue) ?? NSNumber(floatLiteral: 1) anims.append(a) } if let v = ts.zPosition { let a = MotionCAAnimation.zPosition(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.zPosition.rawValue) ?? NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.size { let a = MotionCAAnimation.size(v) a.fromValue = NSValue(cgSize: self.bounds.size) anims.append(a) } if let v = ts.shadowPath { let a = MotionCAAnimation.shadow(path: v) a.fromValue = self.shadowPath anims.append(a) } if let v = ts.shadowColor { let a = MotionCAAnimation.shadow(color: UIColor(cgColor: v)) a.fromValue = self.shadowColor anims.append(a) } if let v = ts.shadowOffset { let a = MotionCAAnimation.shadow(offset: v) a.fromValue = NSValue(cgSize: self.shadowOffset) anims.append(a) } if let v = ts.shadowOpacity { let a = MotionCAAnimation.shadow(opacity: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowOpacity)) anims.append(a) } if let v = ts.shadowRadius { let a = MotionCAAnimation.shadow(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowRadius)) anims.append(a) } if #available(iOS 9.0, *), let (stiffness, damping) = ts.spring { for i in 0..<anims.count where nil != anims[i].keyPath { let v = anims[i] guard "cornerRadius" != v.keyPath else { continue } let a = MotionCAAnimation.convert(animation: v, stiffness: stiffness, damping: damping) anims[i] = a if a.settlingDuration > duration { duration = a.settlingDuration } } } let g = Motion.animate(group: anims, timingFunction: ts.timingFunction, duration: duration) self.animate(g) if let v = ts.completion { Motion.delay(duration, execute: v) } if let v = completion { Motion.delay(duration, execute: v) } } } } private extension CALayer { /** Updates the model with values provided in animation. - Parameter animation: A CAAnimation. */ func updateModel(_ animation: CAAnimation) { if let a = animation as? CABasicAnimation { setValue(a.toValue, forKeyPath: a.keyPath!) } else if let a = animation as? CAAnimationGroup { a.animations?.forEach { updateModel($0) } } } }
mit
elpassion/el-space-ios
ELSpace/Models/DTO/NewActivityDTO.swift
1
150
struct NewActivityDTO { let projectId: Int? let value: Double? let performedAt: String let comment: String? let reportType: Int }
gpl-3.0
anirudh24seven/wikipedia-ios
WikipediaUnitTests/Code/NumberFormatterExtrasTests.swift
1
1085
import XCTest class NumberFormatterExtrasTests: XCTestCase { func testThousands() { var number: UInt64 = 215 var format: String = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("215")) number = 1500 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("1.5")) number = 538000 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("538")) number = 867530939 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("867.5")) number = 312490123456 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("312.5")) } }
mit
Zewo/Epoch
Sources/HTTP/Request/Request.swift
2
5907
import Core import IO import Media import Venice public final class Request : Message { public typealias UpgradeConnection = (Response, DuplexStream) throws -> Void public var method: Method public var uri: URI public var version: Version public var headers: Headers public var body: Body public var storage: Storage = [:] public var upgradeConnection: UpgradeConnection? public init( method: Method, uri: URI, headers: Headers = [:], version: Version = .oneDotOne, body: Body ) { self.method = method self.uri = uri self.headers = headers self.version = version self.body = body } public enum Method { case get case head case post case put case patch case delete case options case trace case connect case other(String) } } extension Request { public convenience init( method: Method, uri: String, headers: Headers = [:] ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .empty ) switch method { case .get, .head, .options, .connect, .trace: break default: contentLength = 0 } } public convenience init( method: Method, uri: String, headers: Headers = [:], body stream: Readable ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .readable(stream) ) } public convenience init( method: Method, uri: String, headers: Headers = [:], body write: @escaping Body.Write ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .writable(write) ) } public convenience init( method: Method, uri: String, headers: Headers = [:], body buffer: BufferRepresentable, timeout: Duration = 5.minutes ) throws { try self.init( method: method, uri: uri, headers: headers, body: { stream in try stream.write(buffer, deadline: timeout.fromNow()) } ) contentLength = buffer.bufferSize } public convenience init<Content : EncodingMedia>( method: Method, uri: String, headers: Headers = [:], content: Content, timeout: Duration = 5.minutes ) throws { try self.init( method: method, uri: uri, headers: headers, body: { writable in try content.encode(to: writable, deadline: timeout.fromNow()) } ) self.contentType = Content.mediaType self.contentLength = nil self.transferEncoding = "chunked" } public convenience init<Content : MediaEncodable>( method: Method, uri: String, headers: Headers = [:], content: Content, timeout: Duration = 5.minutes ) throws { let media = try Content.defaultEncodingMedia() try self.init( method: method, uri: uri, headers: headers, body: { writable in try media.encode(content, to: writable, deadline: timeout.fromNow()) } ) self.contentType = media.mediaType self.contentLength = nil self.transferEncoding = "chunked" } public convenience init<Content : MediaEncodable>( method: Method, uri: String, headers: Headers = [:], content: Content, contentType mediaType: MediaType, timeout: Duration = 5.minutes ) throws { let media = try Content.encodingMedia(for: mediaType) try self.init( method: method, uri: uri, headers: headers, body: { writable in try media.encode(content, to: writable, deadline: timeout.fromNow()) } ) self.contentType = media.mediaType self.contentLength = nil self.transferEncoding = "chunked" } } extension Request { public var path: String { return uri.path! } public var accept: [MediaType] { get { return headers["Accept"].map({ MediaType.parse(acceptHeader: $0) }) ?? [] } set(accept) { headers["Accept"] = accept.map({ $0.type + "/" + $0.subtype }).joined(separator: ", ") } } public var authorization: String? { get { return headers["Authorization"] } set(authorization) { headers["Authorization"] = authorization } } public var host: String? { get { return headers["Host"] } set(host) { headers["Host"] = host } } public var userAgent: String? { get { return headers["User-Agent"] } set(userAgent) { headers["User-Agent"] = userAgent } } } extension Request : CustomStringConvertible { /// :nodoc: public var requestLineDescription: String { return method.description + " " + uri.description + " " + version.description + "\n" } /// :nodoc: public var description: String { return requestLineDescription + headers.description } }
mit
kstaring/swift
validation-test/compiler_crashers/28386-swift-typebase-getdesugaredtype.swift
5
450
// 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 --crash %target-swift-frontend %s -parse struct A{init(){let:A class B:A class A:B{ init()
apache-2.0
natecook1000/swift
stdlib/public/core/NewtypeWrapper.swift
2
5299
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// An implementation detail used to implement support importing /// (Objective-)C entities marked with the swift_newtype Clang /// attribute. public protocol _SwiftNewtypeWrapper : RawRepresentable, _HasCustomAnyHashableRepresentation { } extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable { /// The hash value. @inlinable public var hashValue: Int { return rawValue.hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable // FIXME(sil-serialize-all) public func _rawHashValue(seed: (UInt64, UInt64)) -> Int { return rawValue._rawHashValue(seed: seed) } } extension _SwiftNewtypeWrapper { public func _toCustomAnyHashable() -> AnyHashable? { return nil } } extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable { public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _NewtypeWrapperAnyHashableBox(self)) } } internal struct _NewtypeWrapperAnyHashableBox<Base>: _AnyHashableBox where Base: _SwiftNewtypeWrapper & Hashable, Base.RawValue: Hashable { var _value: Base init(_ value: Base) { self._value = value } var _canonicalBox: _AnyHashableBox { return (_value.rawValue as AnyHashable)._box._canonicalBox } func _isEqual(to other: _AnyHashableBox) -> Bool? { _preconditionFailure("_isEqual called on non-canonical AnyHashable box") } var _hashValue: Int { _preconditionFailure("_hashValue called on non-canonical AnyHashable box") } func _hash(into hasher: inout Hasher) { _preconditionFailure("_hash(into:) called on non-canonical AnyHashable box") } func _rawHashValue(_seed: (UInt64, UInt64)) -> Int { _preconditionFailure("_rawHashValue(_seed:) called on non-canonical AnyHashable box") } var _base: Any { return _value } func _unbox<T: Hashable>() -> T? { return _value as? T ?? _value.rawValue as? T } func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { if let value = _value as? T { result.initialize(to: value) return true } if let value = _value.rawValue as? T { result.initialize(to: value) return true } return false } } #if _runtime(_ObjC) extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable { // Note: This is the only default typealias for _ObjectiveCType, because // constrained extensions aren't allowed to define types in different ways. // Fortunately the others don't need it. public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType { return rawValue._bridgeToObjectiveC() } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) { var innerResult: Self.RawValue? Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) -> Bool { var innerResult: Self.RawValue? let success = Self.RawValue._conditionallyBridgeFromObjectiveC( source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } return success } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType? ) -> Self { return Self( rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))! } } extension _SwiftNewtypeWrapper where Self.RawValue: AnyObject { @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue { return rawValue } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) { result = Self(rawValue: source) } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) -> Bool { result = Self(rawValue: source) return result != nil } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue? ) -> Self { return Self(rawValue: source!)! } } #endif
apache-2.0
practicalswift/swift
benchmark/single-source/ByteSwap.swift
10
1932
//===--- ByteSwap.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of Swift byte swap. // rdar://problem/22151907 import Foundation import TestsUtils public let ByteSwap = BenchmarkInfo( name: "ByteSwap", runFunction: run_ByteSwap, tags: [.validation, .algorithm]) // a naive O(n) implementation of byteswap. @inline(never) func byteswap_n(_ a: UInt64) -> UInt64 { return ((a & 0x00000000000000FF) &<< 56) | ((a & 0x000000000000FF00) &<< 40) | ((a & 0x0000000000FF0000) &<< 24) | ((a & 0x00000000FF000000) &<< 8) | ((a & 0x000000FF00000000) &>> 8) | ((a & 0x0000FF0000000000) &>> 24) | ((a & 0x00FF000000000000) &>> 40) | ((a & 0xFF00000000000000) &>> 56) } // a O(logn) implementation of byteswap. @inline(never) func byteswap_logn(_ a: UInt64) -> UInt64 { var a = a a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32 a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16 a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8 return a } @inline(never) public func run_ByteSwap(_ N: Int) { var s: UInt64 = 0 for _ in 1...10000*N { // Check some results. let x : UInt64 = UInt64(getInt(0)) s = s &+ byteswap_logn(byteswap_n(x &+ 2457)) &+ byteswap_logn(byteswap_n(x &+ 9129)) &+ byteswap_logn(byteswap_n(x &+ 3333)) } CheckResults(s == (2457 &+ 9129 &+ 3333) &* 10000 &* N) }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/17327-swift-sourcemanager-getmessage.swift
11
254
// 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 { let a [ { func g { case { class A { let a { if true { enum A { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/21224-swift-declcontext-lookupqualified.swift
11
252
// 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 a { struct B { struct B<d where I : d { typealias e = B var a { { } { protocol
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/20646-no-stacktrace.swift
11
282
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSData { struct A { { } { } { } let a { enum b { deinit { ( [ { func a { protocol P { { } class case ,
mit
mac-cain13/CoreDataKit
CoreDataKitTests/NSManagedObjectContextTests.swift
2
7898
// // NSManagedObjectTests.swift // CoreDataKit // // Created by Mathijs Kadijk on 15-10-14. // Copyright (c) 2014 Mathijs Kadijk. All rights reserved. // import XCTest import CoreData import CoreDataKit class NSManagedObjectContextTests: TestCase { func testInitWithPersistentStore() { let context = NSManagedObjectContext(persistentStoreCoordinator: coreDataStack.persistentStoreCoordinator) XCTAssertNil(context.parent, "Unexpected parent context") XCTAssertNotNil(context.persistentStoreCoordinator, "Missing persistent coordinator") XCTAssertEqual(context.persistentStoreCoordinator!, coreDataStack.persistentStoreCoordinator, "Incorrect persistent coordinator") XCTAssertEqual(context.concurrencyType, NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType, "Incorrect concurrency type") } func testInitWithPersistentStoreObtainsPermanentIDs() { let context = NSManagedObjectContext(persistentStoreCoordinator: coreDataStack.persistentStoreCoordinator) testContextObtainsPermanentIDs(context: context) } func testInitWithParentContext() { let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType, parentContext: coreDataStack.rootContext) XCTAssertNotNil(context.parent, "Missing parent context") XCTAssertEqual(context.parent!, coreDataStack.rootContext, "Incorrect parent context") XCTAssertEqual(context.concurrencyType, NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType, "Incorrect concurrency type") } func testInitWithParentContextObtainsPermanentIDs() { let parentContext = NSManagedObjectContext(persistentStoreCoordinator: coreDataStack.persistentStoreCoordinator) let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType, parentContext: parentContext) testContextObtainsPermanentIDs(context: context) } // MARK: - Saving func testPerformBlockAndSaveToPersistentStore() { let completionExpectation = expectation(description: "Expected completion handler call") let countFRq = NSFetchRequest<NSManagedObject>(entityName: "Employee") XCTAssertEqual(try? coreDataStack.rootContext.count(for: countFRq), 0, "Unexpected employee entities") coreDataStack.backgroundContext.perform(block: { (context) -> CommitAction in let employee: Employee = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context) as! Employee employee.name = "Mike Ross" return .saveToPersistentStore }, completionHandler: { (result) -> Void in do { _ = try result() XCTAssertEqual(try self.coreDataStack.rootContext.count(for: countFRq), 1, "Unexpected employee entity count") completionExpectation.fulfill() } catch { XCTFail("Unexpected error") } }) waitForExpectations(timeout: 3, handler: nil) } func testFailingPerformBlockAndSaveToPersistentStore() { let completionExpectation = expectation(description: "Expected completion handler call") let countFRq = NSFetchRequest<NSManagedObject>(entityName: "Employee") XCTAssertEqual(try? coreDataStack.rootContext.count(for: countFRq), 0, "Unexpected employee entities") coreDataStack.backgroundContext.perform(block: { (context) -> CommitAction in NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context) return .saveToParentContext }, completionHandler: { (result) -> Void in do { _ = try result() XCTFail("Expected error") } catch CoreDataKitError.coreDataError(let error) { XCTAssertEqual((error as NSError).code, 1570, "Incorrect error code") XCTAssertEqual(try? self.coreDataStack.rootContext.count(for: countFRq), 0, "Unexpected employee entities") completionExpectation.fulfill() } catch { XCTFail("Unexpected error") } }) waitForExpectations(timeout: 3, handler: nil) } // MARK: Obtaining permanent IDs func testObtainPermanentIDsForInsertedObjects() { let employee: Employee = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: coreDataStack.rootContext) as! Employee employee.name = "Harvey Specter" XCTAssertTrue(employee.objectID.isTemporaryID, "Object ID must be temporary") do { try coreDataStack.rootContext.obtainPermanentIDsForInsertedObjects() XCTAssertFalse(employee.objectID.isTemporaryID, "Object ID must be permanent") } catch { XCTFail("Unexpected error") } } private func testContextObtainsPermanentIDs(context: NSManagedObjectContext) { let saveExpectation = expectation(description: "Await save result") var employee: Employee! context.perform(block: { context in employee = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context) as! Employee employee.name = "Harvey Specter" XCTAssertTrue(employee.objectID.isTemporaryID, "Object ID must be temporary") return .saveToParentContext }, completionHandler: { _ in XCTAssertFalse(employee.objectID.isTemporaryID, "Object ID must be permanent") saveExpectation.fulfill() }) waitForExpectations(timeout: 3, handler: nil) } // MARK: - Creating func testCreate() { do { let employee = try coreDataStack.rootContext.create(Employee.self) XCTAssertTrue(employee.isInserted, "Managed object should be inserted") XCTAssertEqual(employee.managedObjectContext!, coreDataStack.rootContext, "Unexpected managed object context") } catch { XCTFail("Unexpected error") } } func testCreateIncorrectEntityName() { do { _ = try coreDataStack.rootContext.create(EmployeeIncorrectEntityName.self) XCTFail("Unexpected managed object") } catch CoreDataKitError.contextError { // Expected error } catch { XCTFail("Unexpected error") } } // MARK: - Finding func testFindAllEmployeesWithOneEmployeeInserted() { do { let employee = try coreDataStack.rootContext.create(Employee.self) employee.name = "Rachel Zane" let results = try coreDataStack.rootContext.find(Employee.self) XCTAssertEqual(results.count, 1, "Incorrect number of results") if let firstEmployee = results.first { XCTAssertEqual(firstEmployee.name, "Rachel Zane", "Incorrect employee name") } } catch { XCTFail("Unexpected error") } } func testFindEmployeesWithoutAnythingInserted() { do { let results = try coreDataStack.rootContext.find(Employee.self, predicate: nil, sortDescriptors: nil, limit: nil) XCTAssertEqual(results.count, 0, "Incorrect number of results") } catch { XCTFail("Unexpected error") } } func testFindEmployeesWithFilteringAndSorting() { do { let employee0 = try coreDataStack.rootContext.create(Employee.self) let employee1 = try coreDataStack.rootContext.create(Employee.self) let employee2 = try coreDataStack.rootContext.create(Employee.self) employee0.name = "Rachel Zane 2" employee1.name = "Rachel Zane 1" employee2.name = "Mike Ross" } catch { XCTFail("Missing managed object") } let predicate = NSPredicate(format: "name contains %@", argumentArray: ["Rachel Zane"]) let sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] do { let results = try coreDataStack.rootContext.find(Employee.self, predicate: predicate, sortDescriptors: sortDescriptors, limit: nil) XCTAssertEqual(results.count, 2, "Incorrect number of results") XCTAssertEqual(results[0].name, "Rachel Zane 1", "Incorrect order") XCTAssertEqual(results[1].name, "Rachel Zane 2", "Incorrect order") } catch { XCTFail("Unexpected error") } } }
mit
billhsu0913/VideBounceButtonView
VideBounceButtonViewExample/ViewController.swift
1
1757
// // ViewController.swift // VideBounceButtonViewExample // // Created by Oreki Houtarou on 11/29/14. // Copyright (c) 2014 Videgame. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var buttons: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for button in buttons { button.layer.cornerRadius = button.frame.height / 2 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.whiteColor().CGColor } // let bounceButtonView = view as VideBounceButtonView // bounceButtonView.exclusiveButtons = [buttons[0]] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonTapped(sender: AnyObject) { let button = sender as UIButton let snapView = UIView(frame: button.frame) snapView.layer.cornerRadius = button.layer.cornerRadius snapView.backgroundColor = button.backgroundColor view.insertSubview(snapView, atIndex: 0) let maxScale = max(view.frame.width / snapView.frame.width * 2.0, view.frame.height / snapView.frame.height * 2.0) UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in snapView.transform = CGAffineTransformMakeScale(maxScale, maxScale) }) { (finished) -> Void in if finished { self.view.backgroundColor = button.backgroundColor snapView.removeFromSuperview() } } } }
mit
darkerk/v2ex
V2EX/Cells/FavoriteNodeViewCell.swift
1
1724
// // FavoriteNodeViewCell.swift // V2EX // // Created by darker on 2017/3/20. // Copyright © 2017年 darker. All rights reserved. // import UIKit import Kingfisher class FavoriteNodeViewCell: UITableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var countLabel: UILabel! var node: Node? { willSet { if let model = newValue { iconView.kf.setImage(with: URL(string: model.iconURLString), placeholder: #imageLiteral(resourceName: "slide_menu_setting")) nameLabel.text = model.name countLabel.text = " \(model.comments) " countLabel.isHidden = model.comments == 0 } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundColor = AppStyle.shared.theme.cellBackgroundColor contentView.backgroundColor = AppStyle.shared.theme.cellBackgroundColor let selectedView = UIView() selectedView.backgroundColor = AppStyle.shared.theme.cellSelectedBackgroundColor self.selectedBackgroundView = selectedView nameLabel.textColor = AppStyle.shared.theme.black64Color countLabel.clipsToBounds = true countLabel.layer.cornerRadius = 9 countLabel.backgroundColor = AppStyle.shared.theme.topicReplyCountBackgroundColor countLabel.textColor = AppStyle.shared.theme.topicReplyCountTextColor } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0357-swift-type-transform.swift
13
249
// RUN: not %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 func g<T>: T.e { let i: T.c = nil
apache-2.0
Arty-Maly/Volna
Volna/Thumbnail+CoreDataProperties.swift
1
547
// // Thumbnail+CoreDataProperties.swift // Volna // // Created by Artem Malyshev on 2/25/17. // Copyright © 2017 Artem Malyshev. All rights reserved. // import Foundation import CoreData extension Thumbnail { @nonobjc public class func fetchRequest() -> NSFetchRequest<Thumbnail> { return NSFetchRequest<Thumbnail>(entityName: "Thumbnail"); } @NSManaged public var id: NSNumber @NSManaged public var imageData: NSData @NSManaged public var url: String @NSManaged public var radioStation: RadioStation }
gpl-3.0
Eccelor/material-components-ios
components/AppBar/examples/AppBarDelegateForwardingExample.swift
1
5318
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents // This example builds upon AppBarTypicalUseExample. class AppBarDelegateForwardingExample: UITableViewController { let appBar = MDCAppBar() convenience init() { self.init(style: .plain) } override init(style: UITableViewStyle) { super.init(style: style) self.appBar.navigationBar.tintColor = UIColor.white appBar.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white ] self.addChildViewController(appBar.headerViewController) self.title = "Delegate Forwarding" let color = UIColor(white: 0.2, alpha:1) appBar.headerViewController.headerView.backgroundColor = color let mutator = MDCAppBarTextColorAccessibilityMutator() mutator.mutate(appBar) } override func viewDidLoad() { super.viewDidLoad() // UITableViewController's tableView.delegate is self by default. We're setting it here for // emphasis. self.tableView.delegate = self appBar.headerViewController.headerView.trackingScrollView = self.tableView appBar.addSubviewsToParent() self.tableView.layoutMargins = UIEdgeInsets.zero self.tableView.separatorInset = UIEdgeInsets.zero } // The following four methods must be forwarded to the tracking scroll view in order to implement // the Flexible Header's behavior. override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidScroll() } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidEndDecelerating() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset) } } // MARK: Typical setup override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Delegate Forwarding (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor( red: CGFloat(0x03) / CGFloat(255), green: CGFloat(0xA9) / CGFloat(255), blue: CGFloat(0xF4) / CGFloat(255), alpha: 1) appBar.headerViewController.headerView.backgroundColor = color appBar.navigationBar.tintColor = UIColor.white } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: Catalog by convention extension AppBarDelegateForwardingExample { class func catalogBreadcrumbs() -> [String] { return ["App Bar", "Delegate Forwarding (Swift)"] } func catalogShouldHideNavigation() -> Bool { return true } } extension AppBarDelegateForwardingExample { override var childViewControllerForStatusBarHidden: UIViewController? { return appBar.headerViewController } override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } } // MARK: - Typical application code (not Material-specific) // MARK: UITableViewDataSource extension AppBarDelegateForwardingExample { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell!.layoutMargins = UIEdgeInsets.zero return cell! } }
apache-2.0
turingcorp/gattaca
gattaca/Model/Home/Action/MHomeActionMeh.swift
1
252
import UIKit struct MHomeActionMeh:MHomeActionProtocol { let icon:UIImage = #imageLiteral(resourceName: "assetGenericActionMeh") let display:UIImage = #imageLiteral(resourceName: "assetGenericMarkMeh") let mark:DGif.Mark = DGif.Mark.meh }
mit
hoffmanjon/SwiftyBones
examples/BlinkingLed/main.swift
1
467
import Glibc if let led = SBDigitalGPIO(id: "gpio30", direction: .OUT){ while(true) { if let oldValue = led.getValue() { print("Changing") var newValue = (oldValue == DigitalGPIOValue.HIGH) ? DigitalGPIOValue.LOW : DigitalGPIOValue.HIGH led.setValue(newValue) usleep(150000) } } } else { print("Error init pin") }
mit
grpc/grpc-swift
Sources/GRPC/ConnectionPool/GRPCChannelPool.swift
1
14751
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Logging import NIOCore import NIOPosix public enum GRPCChannelPool { /// Make a new ``GRPCChannel`` on which calls may be made to gRPC services. /// /// The channel is backed by one connection pool per event loop, each of which may make multiple /// connections to the given target. The size of the connection pool, and therefore the maximum /// number of connections it may create at a given time is determined by the number of event loops /// in the provided `EventLoopGroup` and the value of /// ``GRPCChannelPool/Configuration/ConnectionPool-swift.struct/connectionsPerEventLoop``. /// /// The event loop and therefore connection chosen for a call is determined by /// ``CallOptions/eventLoopPreference-swift.property``. If the `indifferent` preference is used /// then the least-used event loop is chosen and a connection on that event loop will be selected. /// If an `exact` preference is used then a connection on that event loop will be chosen provided /// the given event loop belongs to the `EventLoopGroup` used to create this ``GRPCChannel``. /// /// Each connection in the pool is initially idle, and no connections will be established until /// a call is made. The pool also closes connections after they have been inactive (i.e. are not /// being used for calls) for some period of time. This is determined by /// ``GRPCChannelPool/Configuration/idleTimeout``. /// /// > Important: The values of `transportSecurity` and `eventLoopGroup` **must** be compatible. /// > /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/tls(_:)`` the allowed /// > `EventLoopGroup`s depends on the value of ``GRPCTLSConfiguration``. If a TLS configuration /// > is known ahead of time, ``PlatformSupport/makeEventLoopGroup(compatibleWith:loopCount:)`` /// > may be used to construct a compatible `EventLoopGroup`. /// > /// > If the `EventLoopGroup` is known ahead of time then a default TLS configuration may be /// > constructed with ``GRPCTLSConfiguration/makeClientDefault(compatibleWith:)``. /// > /// > For ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext`` transport /// > security both `MultiThreadedEventLoopGroup` and `NIOTSEventLoopGroup` (and `EventLoop`s /// > from either) may be used. /// /// - Parameters: /// - target: The target to connect to. /// - transportSecurity: Transport layer security for connections. /// - eventLoopGroup: The `EventLoopGroup` to run connections on. /// - configure: A closure which may be used to modify defaulted configuration before /// constructing the ``GRPCChannel``. /// - Throws: If it is not possible to construct an SSL context. This will never happen when /// using the ``GRPCChannelPool/Configuration/TransportSecurity-swift.struct/plaintext`` /// transport security. /// - Returns: A ``GRPCChannel``. @inlinable public static func with( target: ConnectionTarget, transportSecurity: GRPCChannelPool.Configuration.TransportSecurity, eventLoopGroup: EventLoopGroup, _ configure: (inout GRPCChannelPool.Configuration) -> Void = { _ in } ) throws -> GRPCChannel { let configuration = GRPCChannelPool.Configuration.with( target: target, transportSecurity: transportSecurity, eventLoopGroup: eventLoopGroup, configure ) return try PooledChannel(configuration: configuration) } /// See ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)``. public static func with( configuration: GRPCChannelPool.Configuration ) throws -> GRPCChannel { return try PooledChannel(configuration: configuration) } } extension GRPCChannelPool { public struct Configuration: GRPCSendable { @inlinable internal init( target: ConnectionTarget, transportSecurity: TransportSecurity, eventLoopGroup: EventLoopGroup ) { self.target = target self.transportSecurity = transportSecurity self.eventLoopGroup = eventLoopGroup } // Note: we use `configure` blocks to avoid having to add new initializers when properties are // added to the configuration while allowing the configuration to be constructed as a constant. /// Construct and configure a ``GRPCChannelPool/Configuration``. /// /// - Parameters: /// - target: The target to connect to. /// - transportSecurity: Transport layer security for connections. Note that the value of /// `eventLoopGroup` must be compatible with the value /// - eventLoopGroup: The `EventLoopGroup` to run connections on. /// - configure: A closure which may be used to modify defaulted configuration. @inlinable public static func with( target: ConnectionTarget, transportSecurity: TransportSecurity, eventLoopGroup: EventLoopGroup, _ configure: (inout Configuration) -> Void = { _ in } ) -> Configuration { var configuration = Configuration( target: target, transportSecurity: transportSecurity, eventLoopGroup: eventLoopGroup ) configure(&configuration) return configuration } /// The target to connect to. public var target: ConnectionTarget /// Connection security. public var transportSecurity: TransportSecurity /// The `EventLoopGroup` used by the connection pool. public var eventLoopGroup: EventLoopGroup /// Connection pool configuration. public var connectionPool: ConnectionPool = .defaults /// HTTP/2 configuration. public var http2: HTTP2 = .defaults /// The connection backoff configuration. public var connectionBackoff = ConnectionBackoff() /// The amount of time to wait before closing the connection. The idle timeout will start only /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. /// /// If a connection becomes idle, starting a new RPC will automatically create a new connection. public var idleTimeout = TimeAmount.minutes(30) /// The connection keepalive configuration. public var keepalive = ClientConnectionKeepalive() /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB. /// /// Any received messages whose size exceeds this limit will cause RPCs to fail with /// a `.resourceExhausted` status code. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 { willSet { precondition(newValue >= 0, "maximumReceiveMessageLength must be positive") } } /// A channel initializer which will be run after gRPC has initialized each `NIOCore.Channel`. /// This may be used to add additional handlers to the pipeline and is intended for debugging. /// /// - Warning: The initializer closure may be invoked *multiple times*. #if compiler(>=5.6) @preconcurrency public var debugChannelInitializer: (@Sendable (Channel) -> EventLoopFuture<Void>)? #else public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? #endif /// An error delegate which is called when errors are caught. public var errorDelegate: ClientErrorDelegate? /// A delegate which will be notified about changes to the state of connections managed by the /// pool. public var delegate: GRPCConnectionPoolDelegate? /// A logger used for background activity, such as connection state changes. public var backgroundActivityLogger = Logger( label: "io.grpc", factory: { _ in return SwiftLogNoOpLogHandler() } ) } } extension GRPCChannelPool.Configuration { public struct TransportSecurity: GRPCSendable { private init(_ configuration: GRPCTLSConfiguration?) { self.tlsConfiguration = configuration } /// The TLS configuration used. A `nil` value means that no TLS will be used and /// communication at the transport layer will be plaintext. public var tlsConfiguration: Optional<GRPCTLSConfiguration> /// Secure the transport layer with TLS. /// /// The TLS backend used depends on the value of `configuration`. See ``GRPCTLSConfiguration`` /// for more details. /// /// > Important: the value of `configuration` **must** be compatible with /// > ``GRPCChannelPool/Configuration/eventLoopGroup``. See the documentation of /// > ``GRPCChannelPool/with(target:transportSecurity:eventLoopGroup:_:)`` for more details. public static func tls(_ configuration: GRPCTLSConfiguration) -> TransportSecurity { return TransportSecurity(configuration) } /// Insecure plaintext communication. public static let plaintext = TransportSecurity(nil) } } extension GRPCChannelPool.Configuration { public struct HTTP2: Hashable, GRPCSendable { private static let allowedTargetWindowSizes = (1 ... Int(Int32.max)) private static let allowedMaxFrameSizes = (1 << 14) ... ((1 << 24) - 1) /// Default HTTP/2 configuration. public static let defaults = HTTP2() @inlinable public static func with(_ configure: (inout HTTP2) -> Void) -> HTTP2 { var configuration = Self.defaults configure(&configuration) return configuration } /// The HTTP/2 max frame size. Defaults to 8MB. Values are clamped between 2^14 and 2^24-1 /// octets inclusive (RFC 7540 § 4.2). public var targetWindowSize = 8 * 1024 * 1024 { didSet { self.targetWindowSize = self.targetWindowSize.clamped(to: Self.allowedTargetWindowSizes) } } /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1 /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2). public var maxFrameSize: Int = 16384 { didSet { self.maxFrameSize = self.maxFrameSize.clamped(to: Self.allowedMaxFrameSizes) } } } } extension GRPCChannelPool.Configuration { public struct ConnectionPool: Hashable, GRPCSendable { /// Default connection pool configuration. public static let defaults = ConnectionPool() @inlinable public static func with(_ configure: (inout ConnectionPool) -> Void) -> ConnectionPool { var configuration = Self.defaults configure(&configuration) return configuration } /// The maximum number of connections per `EventLoop` that may be created at a given time. /// /// Defaults to 1. public var connectionsPerEventLoop: Int = 1 /// The maximum number of callers which may be waiting for a stream at any given time on a /// given `EventLoop`. /// /// Any requests for a stream which would cause this limit to be exceeded will be failed /// immediately. /// /// Defaults to 100. public var maxWaitersPerEventLoop: Int = 100 /// The maximum amount of time a caller is willing to wait for a stream for before timing out. /// /// Defaults to 30 seconds. public var maxWaitTime: TimeAmount = .seconds(30) /// The threshold which, if exceeded, when creating a stream determines whether the pool will /// establish another connection (if doing so will not violate ``connectionsPerEventLoop``). /// /// The 'load' is calculated as the ratio of demand for streams (the sum of the number of /// waiters and the number of reserved streams) and the total number of streams which each /// thread _could support. public var reservationLoadThreshold: Double = 0.9 } } /// The ID of a connection in the connection pool. public struct GRPCConnectionID: Hashable, GRPCSendable, CustomStringConvertible { private let id: ConnectionManagerID public var description: String { return String(describing: self.id) } internal init(_ id: ConnectionManagerID) { self.id = id } } /// A delegate for the connection pool which is notified of various lifecycle events. /// /// All functions must execute quickly and may be executed on arbitrary threads. The implementor is /// responsible for ensuring thread safety. public protocol GRPCConnectionPoolDelegate: GRPCSendable { /// A new connection was created with the given ID and added to the pool. The connection is not /// yet active (or connecting). /// /// In most cases ``startedConnecting(id:)`` will be the next function called for the given /// connection but ``connectionRemoved(id:)`` may also be called. func connectionAdded(id: GRPCConnectionID) /// The connection with the given ID was removed from the pool. func connectionRemoved(id: GRPCConnectionID) /// The connection with the given ID has started trying to establish a connection. The outcome /// of the connection will be reported as either ``connectSucceeded(id:streamCapacity:)`` or /// ``connectFailed(id:error:)``. func startedConnecting(id: GRPCConnectionID) /// A connection attempt failed with the given error. After some period of /// time ``startedConnecting(id:)`` may be called again. func connectFailed(id: GRPCConnectionID, error: Error) /// A connection was established on the connection with the given ID. `streamCapacity` streams are /// available to use on the connection. The maximum number of available streams may change over /// time and is reported via ``connectionUtilizationChanged(id:streamsUsed:streamCapacity:)``. The func connectSucceeded(id: GRPCConnectionID, streamCapacity: Int) /// The utlization of the connection changed; a stream may have been used, returned or the /// maximum number of concurrent streams available on the connection changed. func connectionUtilizationChanged(id: GRPCConnectionID, streamsUsed: Int, streamCapacity: Int) /// The remote peer is quiescing the connection: no new streams will be created on it. The /// connection will eventually be closed and removed from the pool. func connectionQuiescing(id: GRPCConnectionID) /// The connection was closed. The connection may be established again in the future (notified /// via ``startedConnecting(id:)``). func connectionClosed(id: GRPCConnectionID, error: Error?) }
apache-2.0
daniele-elia/metronome
metronomo/ViewController.swift
1
8603
// // ViewController.swift // metronomo // // Created by Daniele Elia on 25/02/15. // Copyright (c) 2015 Daniele Elia. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { @IBOutlet var labelBpm: UILabel! @IBOutlet var btnStart: UIButton! @IBOutlet var stepper: UIStepper! @IBOutlet var labelBattiti: UILabel! @IBOutlet var stepperBattiti: UIStepper! @IBOutlet var labelNomeTempo: UILabel! var myTimer: NSTimer? var myTimerBattiti: NSTimer? var player : AVAudioPlayer? var myImageView: UIImageView! let altezzaSchermo = UIScreen.mainScreen().bounds.size.height let larghezzaSchermo = UIScreen.mainScreen().bounds.size.width var tempo: Double = 1 var bpm: Double = 60 var battiti: Double = 1 let yImmagine: CGFloat = 60 //CGFloat(altezzaSchermo/2) let larghezzaPallina: CGFloat = 60 let altezzaPallina:CGFloat = 60 var inizio = 1 var tempoIniziale: CFAbsoluteTime = 0 override func viewDidLoad() { super.viewDidLoad() var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() if let savedBpm = defaults.objectForKey("Bpm") as? String { labelBpm.text = savedBpm stepper.value = (labelBpm.text! as NSString).doubleValue } else { labelBpm.text = "\(Int(stepper.value))" } if let savedBattiti = defaults.objectForKey("Battiti") as? String { labelBattiti.text = savedBattiti stepperBattiti.value = (labelBattiti.text! as NSString).doubleValue } else { labelBattiti.text = "\(Int(stepperBattiti.value))" } var image = UIImage(named: "pallina") myImageView = UIImageView(image: image!) myImageView.frame = CGRect(x: CGFloat(30), y: yImmagine, width: larghezzaPallina, height: altezzaPallina) view.addSubview(myImageView) var audioSessionError: NSError? let audioSession = AVAudioSession.sharedInstance() audioSession.setActive(true, error: nil) if audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError){ debugPrintln("Successfully set the audio session") } else { debugPrintln("Could not set the audio session") } calcolaTempo() nomeTempo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* The delegate message that will let us know that the player has finished playing an audio file */ func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) { //debugPrintln("Finished playing the song") //sleep(1) } @IBAction func cambiaBpm(sender: AnyObject) { labelBpm.text = "\(Int(stepper.value))" calcolaTempo() } @IBAction func cambiaBattit(sender: UIStepper) { labelBattiti.text = "\(Int(stepperBattiti.value))" calcolaTempo() } func calcolaTempo() { bpm = (labelBpm.text! as NSString).doubleValue tempo = 60/bpm battiti = (labelBattiti.text! as NSString).doubleValue nomeTempo() debugPrintln("tempo: \(tempo)") var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(labelBpm.text, forKey: "Bpm") defaults.setObject(labelBattiti.text, forKey: "Battiti") defaults.synchronize() } @IBAction func startStop(sender: UIButton) { calcolaTempo() var lbl: String = "Start" var img: String = "play" if btnStart.titleLabel?.text == "Start" { img = "stop" lbl = "Stop" inizio = 1 tempoIniziale = CFAbsoluteTimeGetCurrent() myTimer = NSTimer.scheduledTimerWithTimeInterval(0.005, target: self, selector: "timerMethod:", userInfo: nil, repeats: true) UIScreen.mainScreen().brightness = 0 } else { myTimer?.invalidate() self.myTimerBattiti?.invalidate() myImageView.frame = CGRectMake(CGFloat(30), yImmagine, larghezzaPallina, altezzaPallina) UIScreen.mainScreen().brightness = 0.2 } btnStart.setTitle(lbl, forState: UIControlState.Normal) let image = UIImage(named: img) as UIImage! btnStart.setImage(image, forState: .Normal) } func timerMethod(sender: NSTimer){ if (CFAbsoluteTimeGetCurrent() - tempoIniziale) >= (tempo) { click() move() tempoIniziale = CFAbsoluteTimeGetCurrent() } } func move() { var origine: CGFloat = 30 if myImageView.frame.origin.x == 30 { origine = larghezzaSchermo - (myImageView.frame.width*2) } UIView.animateWithDuration(tempo, delay: 0.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in self.myImageView.frame = CGRectMake(origine, self.myImageView.frame.origin.y, self.myImageView.frame.size.width, self.myImageView.frame.size.height); }, completion: nil) } func click() { var file = NSBundle.mainBundle().URLForResource("toc", withExtension: "aiff") var error:NSError? /* Start the audio player */ self.player = AVAudioPlayer(contentsOfURL: file, error: &error) /* Did we get an instance of AVAudioPlayer? */ if let theAudioPlayer = self.player { theAudioPlayer.delegate = self; if inizio == 1 { self.player?.volume = 1 } else { self.player?.volume = 0.2 //debugPrintln("0.5") } if theAudioPlayer.prepareToPlay() && theAudioPlayer.play(){ //debugPrintln("Successfully started playing") } else { debugPrintln("Failed to play \(error)") } } else { /* Handle the failure of instantiating the audio player */ } debugPrintln("battito: \(inizio)") inizio = inizio + 1 if inizio > Int(battiti) { inizio = 1 } } func nomeTempo() { var n: String = "Largo" switch bpm { case 40...59: n = "Largo" case 60...65: n = "Larghetto" case 66...75: n = "Adagio" case 76...107: n = "Andante" case 108...119: n = "Moderato" case 120...167: n = "Allegro" case 168...199: n = "Presto" case 200...250: n = "Prestissimo" default: n = " " } labelNomeTempo.text = n } func handleInterruption(notification: NSNotification){ /* Audio Session is interrupted. The player will be paused here */ let interruptionTypeAsObject = notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeAsObject.unsignedLongValue) if let type = interruptionType{ if type == .Ended{ /* resume the audio if needed */ } } debugPrintln("interruption") } // ======== respond to remote controls override func canBecomeFirstResponder() -> Bool { return true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.becomeFirstResponder() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() } override func remoteControlReceivedWithEvent(event: UIEvent) { /* let rc = event.subtype if let theAudioPlayer = self.player { println("received remote control \(rc.rawValue)") // 101 = pause, 100 = play switch rc { case .RemoteControlTogglePlayPause: if theAudioPlayer.playing { theAudioPlayer.pause() } else { theAudioPlayer.play() } case .RemoteControlPlay: theAudioPlayer.play() case .RemoteControlPause: theAudioPlayer.pause() default:break } } */ } }
gpl-2.0
sameertotey/LimoService
LimoService/RequestInfoViewController.swift
1
17153
// // RequestInfoViewController.swift // LimoService // // Created by Sameer Totey on 4/22/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class RequestInfoViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var dateButton: UIButton! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var fromTextField: UITextField! @IBOutlet weak var toTextField: UITextField! @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! @IBOutlet weak var label4: UILabel! @IBOutlet weak var label5: UILabel! @IBOutlet weak var label6: UILabel! @IBOutlet weak var line1: UIView! @IBOutlet weak var line2: UIView! @IBOutlet weak var line3: UIView! @IBOutlet weak var line4: UIView! @IBOutlet weak var fromImage: UIImageView! @IBOutlet weak var toImage: UIImageView! @IBOutlet weak var passengersImage: UIImageView! @IBOutlet weak var bagsImage: UIImageView! @IBOutlet weak var dateImage: UIImageView! @IBOutlet var tapGestureRecognizer: UITapGestureRecognizer! var savedLabel1: UILabel! var savedLabel2: UILabel! var savedLabel3: UILabel! var savedLabel4: UILabel! var savedLabel5: UILabel! var savedLabel6: UILabel! var savedLine1: UIView! var savedLine2: UIView! var savedLine3: UIView! var savedLine4: UIView! var savedFromImage: UIImageView! var savedToImage: UIImageView! var savedPassengersImage: UIImageView! var savedBagsImage: UIImageView! var savedDateImage: UIImageView! var savedDatePicker: UIDatePicker! var savedDateButton: UIButton! var savedFromTextField: UITextField! var savedToTextField: UITextField! var limoRequest: LimoRequest? { didSet { updateUI() } } weak var delegate: RequestInfoDelegate? var date: NSDate? { didSet { if date != nil { datePicker?.minimumDate = date!.earlierDate(NSDate()) datePicker?.date = date! dateString = dateFormatter.stringFromDate(date!) updateDatePickerLabel() } } } var dateString: String? var enabled: Bool = true { didSet { dateButton.enabled = enabled datePicker.enabled = enabled fromTextField.enabled = enabled } } private func updateUI() { if let datePicker = datePicker { if limoRequest == nil { placeEditableView() } else { placeDisplayView() } } } override func viewDidLoad() { super.viewDidLoad() // save a reference to all the views so that they are not deallocated by ARC savedDatePicker = datePicker savedDateButton = dateButton savedLabel1 = label1 savedLabel2 = label2 savedLabel3 = label3 savedLabel4 = label4 savedLabel5 = label5 savedLabel6 = label6 let fromImageView = UIImageView(image: UIImage(named: "FromPin")) fromTextField.leftView = fromImageView fromTextField.leftViewMode = .Always let toImageView = UIImageView(image: UIImage(named: "ToPin")) toTextField.leftView = toImageView toTextField.leftViewMode = .Always savedFromTextField = fromTextField savedToTextField = toTextField savedFromImage = fromImage savedToImage = toImage savedDateImage = dateImage savedPassengersImage = passengersImage savedBagsImage = bagsImage savedLine1 = line1 savedLine2 = line2 savedLine3 = line3 savedLine4 = line4 updateUI() } func configureDatePicker() { datePicker?.datePickerMode = .DateAndTime // Set min/max date for the date picker. // As an example we will limit the date between now and 15 days from now. let now = NSDate() datePicker?.minimumDate = now date = now let currentCalendar = NSCalendar.currentCalendar() let dateComponents = NSDateComponents() dateComponents.day = 15 let fifteenDaysFromNow = currentCalendar.dateByAddingComponents(dateComponents, toDate: now, options: nil) datePicker?.maximumDate = fifteenDaysFromNow datePicker?.minuteInterval = 2 datePicker?.addTarget(self, action: "updateDatePickerLabel", forControlEvents: .ValueChanged) updateDatePickerLabel() } /// A date formatter to format the `date` property of `datePicker`. lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .ShortStyle return dateFormatter }() func updateDatePickerLabel() { dateButton?.setTitle(dateFormatter.stringFromDate(datePicker.date), forState: .Normal) if let date = datePicker?.date { delegate?.dateUpdated(date, newDateString: dateFormatter.stringFromDate(date)) } } var datePickerHidden = false { didSet { if datePickerHidden != oldValue { var viewsDict = Dictionary <String, UIView>() viewsDict["dateButton"] = dateButton viewsDict["datePicker"] = datePicker viewsDict["fromTextField"] = fromTextField viewsDict["toTextField"] = toTextField view.subviews.map({ $0.removeFromSuperview() }) view.addSubview(dateButton) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[dateButton]-|", options: nil, metrics: nil, views: viewsDict)) if datePickerHidden { view.addSubview(fromTextField) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[fromTextField]-|", options: nil, metrics: nil, views: viewsDict)) view.addSubview(toTextField) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[toTextField]-|", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[dateButton]-2-[fromTextField]-2-[toTextField]|", options: nil, metrics: nil, views: viewsDict)) } else { view.addSubview(datePicker) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[datePicker]-|", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[dateButton][datePicker]|", options: nil, metrics: nil, views: viewsDict)) } let heightNeeded: CGFloat if datePickerHidden { heightNeeded = dateButton.sizeThatFits(self.view.bounds.size).height + fromTextField.sizeThatFits(self.view.bounds.size).height + toTextField.sizeThatFits(self.view.bounds.size).height } else { heightNeeded = dateButton.sizeThatFits(self.view.bounds.size).height + datePicker.sizeThatFits(self.view.bounds.size).height } delegate?.neededHeight(heightNeeded) } } } // MARK: - Actions @IBAction func buttonTouched(sender: UIButton) { datePickerHidden = !datePickerHidden } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { var field: ActiveField switch textField { case fromTextField: field = .From delegate?.textFieldActivated(field) case toTextField: field = .To delegate?.textFieldActivated(field) default: println("unknown text field") } return false } func placeEditableView() { configureDatePicker() if datePicker != nil { datePickerHidden = !datePickerHidden datePickerHidden = true } tapGestureRecognizer.enabled = false } func placeDisplayView() { tapGestureRecognizer.enabled = true var viewsDict = Dictionary <String, UIView>() view.subviews.map({ $0.removeFromSuperview() }) label1.text = nil label2.text = nil label3.text = nil label4.text = nil label5.text = nil label6.text = nil [line1, line2, line3, line4].map({ $0.subviews.map({ $0.removeFromSuperview() }) }) viewsDict["line1"] = line1 viewsDict["line2"] = line2 viewsDict["line3"] = line3 viewsDict["line4"] = line4 viewsDict["label1"] = label1 viewsDict["label2"] = label2 viewsDict["label3"] = label3 viewsDict["label4"] = label4 viewsDict["label5"] = label5 viewsDict["label6"] = label6 viewsDict["fromImage"] = fromImage viewsDict["toImage"] = toImage viewsDict["passengersImage"] = passengersImage viewsDict["bagsImage"] = bagsImage view.addSubview(line1) view.addSubview(line2) view.addSubview(line3) view.addSubview(line4) setLines(viewsDict) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line1]", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line2]", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line3]", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line4]", options: nil, metrics: nil, views: viewsDict)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line1][line2][line3][line4]", options: nil, metrics: nil, views: viewsDict)) view.setNeedsLayout() view.layoutIfNeeded() let heightNeeded = line1.sizeThatFits(view.bounds.size).height + line2.sizeThatFits(view.bounds.size).height + line3.sizeThatFits(view.bounds.size).height + line4.sizeThatFits(view.bounds.size).height delegate?.neededHeight(heightNeeded) } func setLines(viewsDict: Dictionary <String, UIView>) { line1.removeConstraints(line1.constraints()) label1.text = limoRequest?.whenString line1.addSubview(label1) if let numPassengers = limoRequest?.numPassengers { label2.text = "\(numPassengers) " } line1.addSubview(passengersImage) line1.addSubview(label2) if let numBags = limoRequest?.numBags { label3.text = "\(numBags) " } line1.addSubview(bagsImage) line1.addSubview(label3) let label1Size = label1.sizeThatFits(view.bounds.size) let label2Size = label2.sizeThatFits(view.bounds.size) let label3Size = label3.sizeThatFits(view.bounds.size) let passengersImageSize = passengersImage.sizeThatFits(view.bounds.size) let bagsImageSize = bagsImage.sizeThatFits(view.bounds.size) let line1Height = max(label1Size.height, label2Size.height, label3Size.height, passengersImageSize.height, bagsImageSize.height) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-[passengersImage]-[label2]-[bagsImage]-[label3]-|", options: nil, metrics: nil, views: viewsDict)) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label1]", options: nil, metrics: nil, views: viewsDict)) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[passengersImage]", options: nil, metrics: nil, views: viewsDict)) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label2]|", options: nil, metrics: nil, views: viewsDict)) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[bagsImage]", options: nil, metrics: nil, views: viewsDict)) line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label3]", options: nil, metrics: nil, views: viewsDict)) line1.addConstraint(NSLayoutConstraint(item: line1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line1Height)) line2.removeConstraints(line2.constraints()) if let fromAddress = limoRequest?.fromAddress, fromName = limoRequest?.fromName { if !fromAddress.isEmpty { label4.text = fromAddress.fullAddressString(fromName) line2.addSubview(fromImage) line2.addSubview(label4) line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[fromImage]-[label4]-|", options: nil, metrics: nil, views: viewsDict)) line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[fromImage]", options: nil, metrics: nil, views: viewsDict)) line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label4]", options: nil, metrics: nil, views: viewsDict)) let label4Size = label4.sizeThatFits(view.bounds.size) let fromImageSize = fromImage.sizeThatFits(view.bounds.size) let line2Height = max(label4Size.height, fromImageSize.height) line2.addConstraint(NSLayoutConstraint(item: line2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line2Height)) } } line3.removeConstraints(line3.constraints()) if let toAddress = limoRequest?.toAddress, toName = limoRequest?.toName { if !toAddress.isEmpty { label5.text = toAddress.fullAddressString(toName) line3.addSubview(toImage) line3.addSubview(label5) line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[toImage]-[label5]-|", options: nil, metrics: nil, views: viewsDict)) line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[toImage]", options: nil, metrics: nil, views: viewsDict)) line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label5]", options: nil, metrics: nil, views: viewsDict)) let label5Size = label5.sizeThatFits(view.bounds.size) let toImageSize = fromImage.sizeThatFits(view.bounds.size) let line3Height = max(label5Size.height, toImageSize.height) line3.addConstraint(NSLayoutConstraint(item: line3, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line3Height)) } } // line3.setNeedsLayout() // line3.layoutIfNeeded() // line3.sizeToFit() // let line3Size = line3.sizeThatFits(CGSizeMake(view.frame.width, 600)) line4.removeConstraints(line4.constraints()) if let comment = limoRequest?.comment { label6.text = comment line4.addSubview(label6) line4.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label6]-|", options: nil, metrics: nil, views: viewsDict)) line4.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label6]", options: nil, metrics: nil, views: viewsDict)) line4.addConstraint(NSLayoutConstraint(item: line4, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: label6.sizeThatFits(view.bounds.size).height)) } // if let toAddress = limoRequest?.toAddress { // if !toAddress.isEmpty { // labelLine3.text = "To: \(toAddress) " // } // } // if let numBags = limoRequest?.numBags, numPassengers = limoRequest?.numPassengers, vehicle = limoRequest?.preferredVehicle { // labelLine4.text = "Passengers:\(numPassengers) Bags:\(numBags) for \(vehicle)" // } // if let comment = limoRequest?.comment { // labelLine5.text = comment // } } @IBAction func viewTapped(sender: AnyObject) { println("view was tapped.......") delegate?.displayViewTapped() } } extension String { func fullAddressString(name: String) -> String { let fullString: String if self.hasPrefix(name) { fullString = String(map(self.generate()) { $0 == "\n" ? ";" : $0 }) } else { fullString = String(map((name + ";" + self).generate()) { $0 == "\n" ? ";" : $0 }) } return fullString } }
mit
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/AviasalesSource/PassengersPicker/ASTPassengersInfo.swift
1
599
// // ASTPassengersInfo.swift // AviasalesSDKTemplate // // Copyright 2016 Go Travel Un Limited // This code is distributed under the terms and conditions of the MIT license. // import Foundation @objcMembers class ASTPassengersInfo: NSObject { let adults: Int let children: Int let infants: Int let travelClass: JRSDKTravelClass init(adults: Int, children: Int, infants: Int, travelClass: JRSDKTravelClass) { self.adults = adults self.children = children self.infants = infants self.travelClass = travelClass super.init() } }
mit
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Map/ImportantPointsMapVC.swift
1
318
class ImportantPointsMapVC: SingleHotelMapVC { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let mapView = mapView, let variant = variant { HLMapViewConfigurator.configure(mapView, toShowSelectedPoints: variant, filter: filter) } } }
mit
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/User/DeleteInboxMessageCall.swift
1
590
// // DeleteInboxMessageCall.swift // Habitica API Client // // Created by Phillip Thelen on 25.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import ReactiveSwift public class DeleteInboxMessageCall: ResponseObjectCall<EmptyResponseProtocol, APIEmptyResponse> { public init(message: InboxMessageProtocol, stubHolder: StubHolderProtocol? = StubHolder(responseCode: 200, stubFileName: "group.json")) { super.init(httpMethod: .DELETE, endpoint: "user/messages/\(message.id ?? "")", stubHolder: stubHolder) } }
gpl-3.0
MatrixHero/FlowSlideMenu
FlowSlideMenuCore/LLFlowSlideMenuEnum.swift
1
178
// // LLFlowSlideMenuEnum.swift // FlowSlideMenu // // Created by LL on 15/11/5. // Copyright © 2015 LL. All rights reserved. // public enum Orientation { case Left }
mit
domenicosolazzo/practice-swift
Views/NavigationBar/Styled Button in the NavigationBar/Styled Button in the NavigationBarTests/Styled_Button_in_the_NavigationBarTests.swift
1
971
// // Styled_Button_in_the_NavigationBarTests.swift // Styled Button in the NavigationBarTests // // Created by Domenico on 06/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit import XCTest class Styled_Button_in_the_NavigationBarTests: 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.measure() { // Put the code you want to measure the time of here. } } }
mit
dalu93/SwiftHelpSet
Sources/Utilities/Resource.swift
1
3424
// // Resource.swift // SwiftHelpSet // // Created by Luca D'Alberti on 7/15/16. // Copyright © 2016 dalu93. All rights reserved. // import Foundation /** Enum containing all the supported HTTP methods */ public enum HTTPMethod : String { case GET case POST case PUT case DELETE case OPTIONS case HEAD case PATCH case TRACE case CONNECT case ERROR } /** * The `HTTPHeader` struct contains the needed informations to describe * completely an HTTP header field */ public struct HTTPHeader { /// The name of the HTTP header field public let name: String /// The value of the HTTP header field public let value: String } // MARK: - DictionaryConvertible extension HTTPHeader: DictionaryConvertible { public func toDictionary() -> [String : String]? { return [ name : value ] } } // MARK: - Prefilled HTTPHeaders public extension HTTPHeader { static func HeaderWith(contentType: String) -> HTTPHeader { return HTTPHeader( name: "Content-Type", value: contentType ) } static var JSONContentType: HTTPHeader { return HTTPHeader.HeaderWith(contentType: "application/json") } } /** * The `Parameter` struct contains the needed informations to descibe * a request parameter. It can be query parameter or body parameter */ public struct Parameter { /// The parameter name public let field: String /// The parameter value public let value: AnyObject } // MARK: - DictionaryConvertible extension Parameter: DictionaryConvertible { public func toDictionary() -> [String : AnyObject]? { return [ field : value ] } } /** * The `Endpoint` struct contains all the info regarding * the endpoint you are trying to reach */ public struct Endpoint { /// The path public let path : String /// The HTTP method public let method : HTTPMethod /// The parameters fileprivate let _parameters : [Parameter]? /// The headers fileprivate let _headers : [HTTPHeader]? } // MARK: - Computed properties public extension Endpoint { /// The encoded parameters, ready for the use public var parameters: [String : AnyObject]? { guard let parameters = _parameters else { return nil } var encParameters: [String : AnyObject] = [:] parameters.forEach { guard let paramDict = $0.toDictionary() else { return } encParameters += paramDict } return encParameters } /// The encoded headers, ready for the use public var headers: [String : String]? { guard let headers = _headers else { return nil } var encHeaders: [String : String] = [:] headers.forEach { guard let headerDict = $0.toDictionary() else { return } encHeaders += headerDict } return encHeaders } } /** * The `Resource` struct contains the information about how to retrieve a * specific resource and how to parse it from a JSON response */ public struct Resource<A> { /// The endpont to reach public let endpoint : Endpoint /// A closure that indicates how to convert the response in a generic object public let parseJSON : (AnyObject) -> A? }
mit
MurphyL/StepInX
DevOps/OS/iOS/helloworld_01/helloworld_01Tests/helloworld_01Tests.swift
1
995
// // helloworld_01Tests.swift // helloworld_01Tests // // Created by MurphyLuo on 5/3/16. // Copyright © 2016 TeamImagine. All rights reserved. // import XCTest @testable import helloworld_01 class helloworld_01Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
WickedColdfront/Slide-iOS
Slide for Reddit/CommentDepthCell.swift
1
44817
// // UZTextViewCell.swift // Slide for Reddit // // Created by Carlos Crane on 12/31/16. // Copyright © 2016 Haptic Apps. All rights reserved. // import UIKit import reddift import UZTextView import ImageViewer import TTTAttributedLabel import RealmSwift import AudioToolbox protocol UZTextViewCellDelegate: class { func pushedMoreButton(_ cell: CommentDepthCell) func pushedSingleTap(_ cell: CommentDepthCell) func showCommentMenu(_ cell: CommentDepthCell) func hideCommentMenu(_ cell: CommentDepthCell) var menuShown : Bool {get set} var menuId : String {get set} } class CommentMenuCell: UITableViewCell { var upvote = UIButton() var downvote = UIButton() var reply = UIButton() var more = UIButton() var edit = UIButton() var delete = UIButton() var editShown = false var archived = false var comment : RComment? var commentView: CommentDepthCell? var parent : CommentViewController? func setComment(comment: RComment, cell: CommentDepthCell, parent: CommentViewController){ self.comment = comment self.parent = parent self.commentView = cell editShown = AccountController.isLoggedIn && comment.author == AccountController.currentName archived = comment.archived self.contentView.backgroundColor = ColorUtil.getColorForSub(sub: comment.subreddit) updateConstraints() } func edit(_ s: AnyObject){ self.parent!.editComment() } func doDelete(_ s: AnyObject){ self.parent!.deleteComment(cell: commentView!) } func upvote(_ s: AnyObject){ parent!.vote(comment: comment!, dir: .up) commentView!.refresh(comment: comment!, submissionAuthor: (parent!.submission?.author)!, text: commentView!.cellContent!) parent!.hideCommentMenu(commentView!) } func downvote(_ s: AnyObject){ parent!.vote(comment: comment!, dir: .down) commentView!.refresh(comment: comment!, submissionAuthor: (parent!.submission?.author)!, text: commentView!.cellContent!) parent!.hideCommentMenu(commentView!) } func more(_ s: AnyObject) { parent!.moreComment(commentView!) } func reply(_ s: AnyObject){ self.parent!.doReply() } var sideConstraint: [NSLayoutConstraint] = [] override func updateConstraints() { super.updateConstraints() var width = 375 width = width/(archived ? 1 : (editShown ? 6 : 4)) if(editShown){ edit.isHidden = false delete.isHidden = false } else { edit.isHidden = true delete.isHidden = true } if(archived){ edit.isHidden = true delete.isHidden = true upvote.isHidden = true downvote.isHidden = true reply.isHidden = true } let metrics:[String:Int]=["width":Int(width), "full": Int(self.contentView.frame.size.width)] let views=["upvote": upvote, "downvote":downvote, "edit":edit, "delete":delete, "view":contentView, "more":more, "reply":reply] as [String : Any] let replyStuff = !archived && AccountController.isLoggedIn ? "[reply(width)]-0-[downvote(width)]-0-[upvote(width)]-0-" : "" let editStuff = (!archived && editShown) ? "[edit(width)]-0-[delete(width)]-0-" : "" self.contentView.removeConstraints(sideConstraint) sideConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:[more(width)]-0-\(editStuff)\(replyStuff)|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[more(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[edit(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[delete(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[reply(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[downvote(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[upvote(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[view(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views)) self.contentView.addConstraints(sideConstraint) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.upvote = UIButton.init(type: .custom) self.downvote = UIButton.init(type: .custom) self.reply = UIButton.init(type: .custom) self.more = UIButton.init(type: .custom) self.edit = UIButton.init(type: .custom) self.delete = UIButton.init(type: .custom) upvote.setImage(UIImage.init(named: "upvote")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) downvote.setImage(UIImage.init(named: "downvote")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) reply.setImage(UIImage.init(named: "reply")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) more.setImage(UIImage.init(named: "ic_more_vert_white")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) edit.setImage(UIImage.init(named: "edit")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) delete.setImage(UIImage.init(named: "delete")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal) upvote.translatesAutoresizingMaskIntoConstraints = false downvote.translatesAutoresizingMaskIntoConstraints = false more.translatesAutoresizingMaskIntoConstraints = false reply.translatesAutoresizingMaskIntoConstraints = false edit.translatesAutoresizingMaskIntoConstraints = false delete.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(upvote) self.contentView.addSubview(more) self.contentView.addSubview(downvote) self.contentView.addSubview(reply) self.contentView.addSubview(edit) self.contentView.addSubview(delete) upvote.addTarget(self, action: #selector(CommentMenuCell.upvote(_:)), for: UIControlEvents.touchUpInside) downvote.addTarget(self, action: #selector(CommentMenuCell.downvote(_:)), for: UIControlEvents.touchUpInside) more.addTarget(self, action: #selector(CommentMenuCell.more(_:)), for: UIControlEvents.touchUpInside) reply.addTarget(self, action: #selector(CommentMenuCell.reply(_:)), for: UIControlEvents.touchUpInside) edit.addTarget(self, action: #selector(CommentMenuCell.edit(_:)), for: UIControlEvents.touchUpInside) delete.addTarget(self, action: #selector(CommentMenuCell.doDelete(_:)), for: UIControlEvents.touchUpInside) updateConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CommentDepthCell: MarginedTableViewCell, TTTAttributedLabelDelegate, UIViewControllerPreviewingDelegate { var moreButton: UIButton = UIButton() var sideView: UIView = UIView() var sideViewSpace: UIView = UIView() var topViewSpace: UIView = UIView() var title: TTTAttributedLabel = TTTAttributedLabel.init(frame: CGRect.zero) var c: UIView = UIView() var children: UILabel = UILabel() var comment:RComment? var depth:Int = 0 func attributedLabel(_ label: TTTAttributedLabel!, didLongPressLinkWith url: URL!, at point: CGPoint) { if parent != nil{ let sheet = UIAlertController(title: url.absoluteString, message: nil, preferredStyle: .actionSheet) sheet.addAction( UIAlertAction(title: "Close", style: .cancel) { (action) in sheet.dismiss(animated: true, completion: nil) } ) let open = OpenInChromeController.init() if(open.isChromeInstalled()){ sheet.addAction( UIAlertAction(title: "Open in Chrome", style: .default) { (action) in _ = open.openInChrome(url, callbackURL: nil, createNewTab: true) } ) } sheet.addAction( UIAlertAction(title: "Open in Safari", style: .default) { (action) in if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } sheet.dismiss(animated: true, completion: nil) } ) sheet.addAction( UIAlertAction(title: "Open", style: .default) { (action) in /* let controller = WebViewController(nibName: nil, bundle: nil) controller.url = url let nav = UINavigationController(rootViewController: controller) self.present(nav, animated: true, completion: nil)*/ } ) sheet.addAction( UIAlertAction(title: "Copy URL", style: .default) { (action) in UIPasteboard.general.setValue(url, forPasteboardType: "public.url") sheet.dismiss(animated: true, completion: nil) } ) sheet.modalPresentationStyle = .popover if let presenter = sheet.popoverPresentationController { presenter.sourceView = label presenter.sourceRect = label.bounds } parent?.present(sheet, animated: true, completion: nil) } } var parent: CommentViewController? func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { parent?.doShow(url: url) } func upvote(){ } var delegate: UZTextViewCellDelegate? = nil var content: Object? = nil override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.title = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) title.numberOfLines = 0 title.font = FontGenerator.fontOfSize(size: 12, submission: false) title.isUserInteractionEnabled = true title.delegate = self title.textColor = ColorUtil.fontColor self.children = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 15)) children.numberOfLines = 1 children.font = FontGenerator.boldFontOfSize(size: 12, submission: false) children.textColor = UIColor.white children.layer.shadowOffset = CGSize(width: 0, height: 0) children.layer.shadowOpacity = 0.4 children.layer.shadowRadius = 4 let padding = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) self.moreButton = UIButton(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) self.sideView = UIView(frame: CGRect(x: 0, y: 0, width: 4, height: CGFloat.greatestFiniteMagnitude)) self.sideViewSpace = UIView(frame: CGRect(x: 0, y: 0, width: 4, height: CGFloat.greatestFiniteMagnitude)) self.topViewSpace = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 4)) self.c = children.withPadding(padding: padding) c.alpha = 0 c.backgroundColor = ColorUtil.accentColorForSub(sub: "") c.layer.cornerRadius = 4 c.clipsToBounds = true moreButton.translatesAutoresizingMaskIntoConstraints = false sideView.translatesAutoresizingMaskIntoConstraints = false sideViewSpace.translatesAutoresizingMaskIntoConstraints = false topViewSpace.translatesAutoresizingMaskIntoConstraints = false title.translatesAutoresizingMaskIntoConstraints = false children.translatesAutoresizingMaskIntoConstraints = false c.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(moreButton) self.contentView.addSubview(sideView) self.contentView.addSubview(sideViewSpace) self.contentView.addSubview(topViewSpace) self.contentView.addSubview(title) self.contentView.addSubview(c) moreButton.addTarget(self, action: #selector(CommentDepthCell.pushedMoreButton(_:)), for: UIControlEvents.touchUpInside) let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.handleShortPress(_:))) tapGestureRecognizer.cancelsTouchesInView = false tapGestureRecognizer.delegate = self self.title.addGestureRecognizer(tapGestureRecognizer) long = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPress(_:))) long.minimumPressDuration = 0.25 long.delegate = self self.addGestureRecognizer(long) self.contentView.backgroundColor = ColorUtil.foregroundColor sideViewSpace.backgroundColor = ColorUtil.backgroundColor topViewSpace.backgroundColor = ColorUtil.backgroundColor self.clipsToBounds = true } func doLongClick(){ timer!.invalidate() AudioServicesPlaySystemSound(1519) if(!self.cancelled){ if(false){ if(self.delegate!.menuShown ){ //todo check if comment id is the same as this comment id self.showMenu(nil) } else { self.pushedSingleTap(nil) } } else { self.showMenu(nil) } } } var timer : Timer? var cancelled = false func handleLongPress(_ sender: UILongPressGestureRecognizer){ if(sender.state == UIGestureRecognizerState.began){ cancelled = false timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(self.doLongClick), userInfo: nil, repeats: false) } if (sender.state == UIGestureRecognizerState.ended) { timer!.invalidate() cancelled = true } } func handleShortPress(_ sender: UIGestureRecognizer){ if(false || (self.delegate!.menuShown && delegate!.menuId == (content as! RComment).getId())) { self.showMenu(sender) } else { self.pushedSingleTap(sender) } } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if(gestureRecognizer.view == self.title){ return self.title.link(at: touch.location(in: self.title)) == nil } return true } var long = UILongPressGestureRecognizer.init(target: self, action: nil) func showMenu(_ sender: AnyObject?){ if let del = self.delegate { if(del.menuShown && del.menuId == (content as! RComment).getId()){ del.hideCommentMenu(self) } else { del.showCommentMenu(self) } } } func vote(){ if(content is RComment){ let current = ActionStates.getVoteDirection(s: comment!) let dir = (current == VoteDirection.none) ? VoteDirection.up : VoteDirection.none var direction = dir switch(ActionStates.getVoteDirection(s: comment!)){ case .up: if(dir == .up){ direction = .none } break case .down: if(dir == .down){ direction = .none } break default: break } do { try parent?.session?.setVote(direction, name: (comment!.name), completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) case .success( _): break } }) } catch { print(error) } ActionStates.setVoteDirection(s: comment!, direction: direction) refresh(comment: content as! RComment, submissionAuthor: savedAuthor, text: cellContent!) } } func more(_ par: CommentViewController){ let alertController = UIAlertController(title: "Comment by /u/\(comment!.author)", message: "", preferredStyle: .actionSheet) let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in print("Cancel") } alertController.addAction(cancelActionButton) let profile: UIAlertAction = UIAlertAction(title: "/u/\(comment!.author)'s profile", style: .default) { action -> Void in par.show(ProfileViewController.init(name: self.comment!.author), sender: self) } alertController.addAction(profile) let share: UIAlertAction = UIAlertAction(title: "Share comment permalink", style: .default) { action -> Void in let activityViewController = UIActivityViewController(activityItems: [self.comment!.permalink], applicationActivities: nil) par.present(activityViewController, animated: true, completion: {}) } alertController.addAction(share) if(AccountController.isLoggedIn){ let save: UIAlertAction = UIAlertAction(title: "Save", style: .default) { action -> Void in par.saveComment(self.comment!) } alertController.addAction(save) } let report: UIAlertAction = UIAlertAction(title: "Report", style: .default) { action -> Void in par.report(self.comment!) } alertController.addAction(report) alertController.modalPresentationStyle = .popover if let presenter = alertController.popoverPresentationController { presenter.sourceView = moreButton presenter.sourceRect = moreButton.bounds } par.parent?.present(alertController, animated: true, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var sideConstraint: [NSLayoutConstraint]? func collapse(childNumber: Int){ children.text = "+\(childNumber)" UIView.animate(withDuration: 0.4, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.c.alpha = 1 }, completion: { finished in }) } func expand(){ UIView.animate(withDuration: 0.4, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.c.alpha = 0 }, completion: { finished in }) } var oldDepth = 0 func updateDepthConstraints(){ if(sideConstraint != nil){ self.contentView.removeConstraints(sideConstraint!) } let metrics=["marginTop": marginTop, "nmarginTop": -marginTop, "horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"labelMinHeight":75, "sidewidth":4*(depth ), "width":sideWidth] let views=["title": title, "topviewspace":topViewSpace, "more": moreButton, "side":sideView, "cell":self.contentView, "sideviewspace":sideViewSpace] as [String : Any] sideConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace(sidewidth)]-0-[side(width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views) sideConstraint!.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace(sidewidth)]-0-[side(width)]-12-[title]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) self.contentView.addConstraints(sideConstraint!) } var menuC : [NSLayoutConstraint] = [] func doHighlight(){ oldDepth = depth depth = 1 updateDepthConstraints() self.contentView.backgroundColor = ColorUtil.foregroundColor.add(overlay: ColorUtil.getColorForSub(sub: ((comment)!.subreddit)).withAlphaComponent(0.5)) } func doUnHighlight(){ depth = oldDepth updateDepthConstraints() self.contentView.backgroundColor = ColorUtil.foregroundColor } override func updateConstraints() { super.updateConstraints() let metrics=["marginTop": marginTop, "nmarginTop": -marginTop, "horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"labelMinHeight":75, "sidewidth":4*(depth ), "width":sideWidth] let views=["title": title, "topviewspace":topViewSpace, "children":c, "more": moreButton, "side":sideView, "cell":self.contentView, "sideviewspace":sideViewSpace] as [String : Any] contentView.bounds = CGRect.init(x: 0,y: 0, width: contentView.frame.size.width , height: contentView.frame.size.height + CGFloat(marginTop)) var constraint:[NSLayoutConstraint] = [] constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace]-0-[side]-12-[title]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[topviewspace]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) if(!menuC.isEmpty){ self.contentView.removeConstraints(menuC) } menuC = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-4-[title]-6-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views) constraint.append(contentsOf:menuC) constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-2-[more]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[children]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "H:[children]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-(nmarginTop)-[side]-(-1)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-(nmarginTop)-[sideviewspace]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) self.contentView.addConstraints(constraint) updateDepthConstraints() } var sideWidth: Int = 0 var marginTop: Int = 0 func setMore(more: RMore, depth: Int){ self.depth = depth loading = false c.alpha = 0 self.contentView.backgroundColor = ColorUtil.foregroundColor if (depth - 1 > 0) { sideWidth = 4 marginTop = 1 let i22 = depth - 2; if(SettingValues.disableColor){ if (i22 % 5 == 0) { sideView.backgroundColor = GMColor.grey100Color() } else if (i22 % 4 == 0) { sideView.backgroundColor = GMColor.grey200Color() } else if (i22 % 3 == 0) { sideView.backgroundColor = GMColor.grey300Color() } else if (i22 % 2 == 0) { sideView.backgroundColor = GMColor.grey400Color() } else { sideView.backgroundColor = GMColor.grey500Color() } } else { if (i22 % 5 == 0) { sideView.backgroundColor = GMColor.blue500Color() } else if (i22 % 4 == 0) { sideView.backgroundColor = GMColor.green500Color() } else if (i22 % 3 == 0) { sideView.backgroundColor = GMColor.yellow500Color() } else if (i22 % 2 == 0) { sideView.backgroundColor = GMColor.orange500Color() } else { sideView.backgroundColor = GMColor.red500Color() } } } else { marginTop = 8 sideWidth = 0 } var attr = NSMutableAttributedString() if(more.children.isEmpty){ attr = NSMutableAttributedString(string: "Continue this thread") } else { attr = NSMutableAttributedString(string: "Load \(more.count) more") } let font = FontGenerator.fontOfSize(size: 16, submission: false) let attr2 = attr.reconstruct(with: font, color: ColorUtil.fontColor, linkColor: .white) title.setText(attr2) updateDepthConstraints() } var numberOfDots = 3 var loading = false func animateMore() { loading = true let attr = NSMutableAttributedString(string: "Loading...") let font = FontGenerator.fontOfSize(size: 16, submission: false) let attr2 = NSMutableAttributedString(attributedString: attr.reconstruct(with: font, color: ColorUtil.fontColor, linkColor: UIColor.blue)) title.setText(attr2) /* possibly todo var timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in print("Firing") let range = NSMakeRange(attr2.length - self.numberOfDots, self.numberOfDots) attr2.addAttribute(NSForegroundColorAttributeName, value: UIColor.clear, range: range) self.textView.attributedString = attr2 self.numberOfDots -= 1 if self.numberOfDots < 0 { self.numberOfDots = 3 } if(self.loading == false){ timer.invalidate() } }*/ } func setComment(comment: RComment, depth: Int, parent: CommentViewController, hiddenCount: Int, date: Double, author: String?, text: NSAttributedString){ self.comment = comment self.cellContent = text self.contentView.backgroundColor = ColorUtil.foregroundColor loading = false if(self.parent == nil){ self.parent = parent } if(date != 0 && date < Double(comment.created.timeIntervalSince1970 )){ setIsNew(sub: comment.subreddit) } if(hiddenCount > 0){ c.alpha = 1 children.text = "+\(hiddenCount)" } else { c.alpha = 0 } self.depth = depth if (depth - 1 > 0) { sideWidth = 4 marginTop = 1 let i22 = depth - 2; if(SettingValues.disableColor){ if (i22 % 5 == 0) { sideView.backgroundColor = GMColor.grey100Color() } else if (i22 % 4 == 0) { sideView.backgroundColor = GMColor.grey200Color() } else if (i22 % 3 == 0) { sideView.backgroundColor = GMColor.grey300Color() } else if (i22 % 2 == 0) { sideView.backgroundColor = GMColor.grey400Color() } else { sideView.backgroundColor = GMColor.grey500Color() } } else { if (i22 % 5 == 0) { sideView.backgroundColor = GMColor.blue500Color() } else if (i22 % 4 == 0) { sideView.backgroundColor = GMColor.green500Color() } else if (i22 % 3 == 0) { sideView.backgroundColor = GMColor.yellow500Color() } else if (i22 % 2 == 0) { sideView.backgroundColor = GMColor.orange500Color() } else { sideView.backgroundColor = GMColor.red500Color() } } } else { //marginTop = 8 marginTop = 1 sideWidth = 0 } refresh(comment: comment, submissionAuthor: author, text: text) if(!registered){ parent.registerForPreviewing(with: self, sourceView: title) registered = true } updateDepthConstraints() } var cellContent: NSAttributedString? var savedAuthor: String = "" func refresh(comment: RComment, submissionAuthor: String?, text: NSAttributedString){ var color: UIColor savedAuthor = submissionAuthor! switch(ActionStates.getVoteDirection(s: comment)){ case .down: color = ColorUtil.downvoteColor break case .up: color = ColorUtil.upvoteColor break default: color = ColorUtil.fontColor break } let scoreString = NSMutableAttributedString(string: ((comment.scoreHidden ? "[score hidden]" : "\(getScoreText(comment: comment))") + (comment.controversiality > 0 ? "†" : "" )), attributes: [NSForegroundColorAttributeName: color]) let endString = NSMutableAttributedString(string:" • \(DateFormatter().timeSince(from: comment.created, numericDates: true))" + (comment.isEdited ? ("(edit \(DateFormatter().timeSince(from: comment.edited, numericDates: true)))") : ""), attributes: [NSForegroundColorAttributeName: ColorUtil.fontColor]) let authorString = NSMutableAttributedString(string: "\u{00A0}\(comment.author)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor]) let flairTitle = NSMutableAttributedString.init(string: "\u{00A0}\(comment.flair)\u{00A0}", attributes: [kTTTBackgroundFillColorAttributeName: ColorUtil.backgroundColor, NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3]) let pinned = NSMutableAttributedString.init(string: "\u{00A0}PINNED\u{00A0}", attributes: [kTTTBackgroundFillColorAttributeName: GMColor.green500Color(), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3]) let gilded = NSMutableAttributedString.init(string: "\u{00A0}x\(comment.gilded) ", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false)]) let spacer = NSMutableAttributedString.init(string: " ") let userColor = ColorUtil.getColorForUser(name: comment.author) if (comment.distinguished == "admin") { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#E57373"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } else if (comment.distinguished == "special") { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#F44336"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } else if (comment.distinguished == "moderator") { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#81C784"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } else if (AccountController.currentName == comment.author) { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#FFB74D"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } else if(submissionAuthor != nil && comment.author == submissionAuthor) { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#64B5F6"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } else if (userColor != ColorUtil.baseColor) { authorString.addAttributes([kTTTBackgroundFillColorAttributeName: userColor, NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) } let infoString = NSMutableAttributedString(string: "\u{00A0}") infoString.append(authorString) let tag = ColorUtil.getTagForUser(name: comment.author) if(!tag.isEmpty){ let tagString = NSMutableAttributedString(string: "\u{00A0}\(tag)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor]) tagString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor(rgb: 0x2196f3), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length)) infoString.append(spacer) infoString.append(tagString) } infoString.append(NSAttributedString(string:" • ", attributes: [NSFontAttributeName: FontGenerator.fontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor])) infoString.append(scoreString) infoString.append(endString) if(!comment.flair.isEmpty){ infoString.append(spacer) infoString.append(flairTitle) } if(comment.pinned){ infoString.append(spacer) infoString.append(pinned) } if(comment.gilded > 0){ infoString.append(spacer) let gild = NSMutableAttributedString.init(string: "G", attributes: [kTTTBackgroundFillColorAttributeName: GMColor.amber500Color(), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3]) infoString.append(gild) if(comment.gilded > 1){ infoString.append(gilded) } } infoString.append(NSAttributedString.init(string: "\n")) infoString.append(text) if(!setLinkAttrs){ let activeLinkAttributes = NSMutableDictionary(dictionary: title.activeLinkAttributes) activeLinkAttributes[NSForegroundColorAttributeName] = ColorUtil.accentColorForSub(sub: comment.subreddit) title.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any] title.linkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any] setLinkAttrs = true } title.setText(infoString) } var setLinkAttrs = false func setIsContext(){ self.contentView.backgroundColor = GMColor.yellow500Color().withAlphaComponent(0.5) } func setIsNew(sub: String){ self.contentView.backgroundColor = ColorUtil.getColorForSub(sub: sub).withAlphaComponent(0.5) } func getScoreText(comment: RComment) -> Int { var submissionScore = comment.score switch (ActionStates.getVoteDirection(s: comment)) { case .up: if(comment.likes != .up){ if(comment.likes == .down){ submissionScore += 1 } submissionScore += 1 } break case .down: if(comment.likes != .down){ if(comment.likes == .up){ submissionScore -= 1 } submissionScore -= 1 } break case .none: if(comment.likes == .up && comment.author == AccountController.currentName){ submissionScore -= 1 } } return submissionScore } var registered:Bool = false func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let locationInTextView = title.convert(location, to: title) if let (url, rect) = getInfo(locationInTextView: locationInTextView) { previewingContext.sourceRect = title.convert(rect, from: title) if let controller = parent?.getControllerForUrl(baseUrl: url){ return controller } } return nil } func getInfo(locationInTextView: CGPoint) -> (URL, CGRect)? { if let attr = title.link(at: locationInTextView) { if let url = attr.result.url { return (url, title.bounds) } } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { if(viewControllerToCommit is GalleryViewController || viewControllerToCommit is YouTubeViewController){ parent?.presentImageGallery(viewControllerToCommit as! GalleryViewController) } else { parent?.show(viewControllerToCommit, sender: parent ) } } func pushedMoreButton(_ sender: AnyObject?) { if let delegate = self.delegate { delegate.pushedMoreButton(self) } } func longPressed(_ sender: AnyObject?) { if self.delegate != nil { } } func pushedSingleTap(_ sender: AnyObject?) { if let delegate = self.delegate { delegate.pushedSingleTap(self) } } class func margin() -> UIEdgeInsets { return UIEdgeInsetsMake(4, 0, 2, 0) } } extension UIColor { func add(overlay: UIColor) -> UIColor { var bgR: CGFloat = 0 var bgG: CGFloat = 0 var bgB: CGFloat = 0 var bgA: CGFloat = 0 var fgR: CGFloat = 0 var fgG: CGFloat = 0 var fgB: CGFloat = 0 var fgA: CGFloat = 0 self.getRed(&bgR, green: &bgG, blue: &bgB, alpha: &bgA) overlay.getRed(&fgR, green: &fgG, blue: &fgB, alpha: &fgA) let r = fgA * fgR + (1 - fgA) * bgR let g = fgA * fgG + (1 - fgA) * bgG let b = fgA * fgB + (1 - fgA) * bgB return UIColor(red: r, green: g, blue: b, alpha: 1.0) } } extension UIView { func withPadding(padding: UIEdgeInsets) -> UIView { let container = UIView() self.translatesAutoresizingMaskIntoConstraints = false container.addSubview(self) container.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "|-(\(padding.left))-[view]-(\(padding.right))-|" , options: [], metrics: nil, views: ["view": self])) container.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|-(\(padding.top)@999)-[view]-(\(padding.bottom)@999)-|", options: [], metrics: nil, views: ["view": self])) return container } }
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/01318-swift-constraints-constraintgraph-addconstraint.swift
11
550
// 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 e?) { typealias e?) { } } func f(b: A<T) { func g: A, Any) -> d<Int>("\() -> String = T, Any, object2: b: d = { class b<T where I.A: String) -> (1)) for b wh
apache-2.0
abertelrud/swift-package-manager
Fixtures/DependencyResolution/External/PackageLookupCaseInsensitive/dep/Sources/Dep/dep.swift
2
100
public struct dep { public private(set) var text = "Hello, World!" public init() { } }
apache-2.0
nalexn/ViewInspector
Tests/ViewInspectorTests/ViewSearchTests.swift
1
12708
import XCTest import Combine import SwiftUI @testable import ViewInspector @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) private struct Test { struct InnerView: View, Inspectable { var body: some View { Button(action: { }, label: { HStack { Text("Btn") } }).mask(Group { Text("Test", tableName: "Test", bundle: (try? .testResources()) ?? .main) }) } } struct MainView: View, Inspectable { var body: some View { AnyView(Group { SwiftUI.EmptyView() .padding() .overlay(HStack { SwiftUI.EmptyView() .id("5") InnerView() .padding(15) .tag(9) }) Text("123") .font(.footnote) .tag(4) .id(7) .background(Button("xyz", action: { })) Divider() .modifier(Test.Modifier(text: "modifier_0")) .padding() .modifier(Test.Modifier(text: "modifier_1")) }) } } struct ConditionalView: View, Inspectable { let falseCondition = false let trueCondition = true var body: some View { HStack { if falseCondition { Text("1") } Text("2") if trueCondition { Text("3") } } } } struct Modifier: ViewModifier, Inspectable { let text: String func body(content: Modifier.Content) -> some View { AnyView(content.overlay(Text(text))) } } struct NonInspectableView: View { var body: some View { SwiftUI.EmptyView() } } struct EmptyView: View, Inspectable { var body: some View { Text("empty") } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) struct ConflictingViewTypeNamesStyle: ButtonStyle { public func makeBody(configuration: Configuration) -> some View { Group { Test.EmptyView() Label("", image: "") configuration.label } } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class ViewSearchTests: XCTestCase { func testFindAll() throws { let testView = Test.MainView() XCTAssertEqual(try testView.inspect().findAll(ViewType.ZStack.self).count, 0) XCTAssertEqual(try testView.inspect().findAll(ViewType.HStack.self).count, 2) XCTAssertEqual(try testView.inspect().findAll(ViewType.Button.self).count, 2) XCTAssertEqual(try testView.inspect().findAll(ViewType.Text.self).map({ try $0.string() }), ["Btn", "Test_en", "123", "xyz", "modifier_0", "modifier_1"]) XCTAssertEqual(try testView.inspect().findAll(Test.InnerView.self).count, 1) XCTAssertEqual(try testView.inspect().findAll(where: { (try? $0.overlay()) != nil }).count, 3) } func testFindText() throws { let testView = Test.MainView() XCTAssertEqual(try testView.inspect().find(text: "123").pathToRoot, "view(MainView.self).anyView().group().text(1)") XCTAssertEqual(try testView.inspect().find(text: "Test_en").pathToRoot, """ view(MainView.self).anyView().group().emptyView(0).overlay().hStack()\ .view(InnerView.self, 1).button().mask().group().text(0) """) XCTAssertEqual(try testView.inspect().find(text: "Btn").pathToRoot, """ view(MainView.self).anyView().group().emptyView(0).overlay().hStack()\ .view(InnerView.self, 1).button().labelView().hStack().text(0) """) XCTAssertEqual(try testView.inspect().find(text: "xyz").pathToRoot, "view(MainView.self).anyView().group().text(1).background().button().labelView().text()") XCTAssertEqual(try testView.inspect().find(text: "modifier_0").pathToRoot, """ view(MainView.self).anyView().group().divider(2).modifier(Modifier.self)\ .anyView().viewModifierContent().overlay().text() """) XCTAssertEqual(try testView.inspect().find(text: "modifier_1").pathToRoot, """ view(MainView.self).anyView().group().divider(2).modifier(Modifier.self, 1)\ .anyView().viewModifierContent().overlay().text() """) XCTAssertEqual(try testView.inspect().find( textWhere: { _, attr -> Bool in try attr.font() == .footnote }).string(), "123") XCTAssertThrows(try testView.inspect().find(text: "unknown"), "Search did not find a match") XCTAssertThrows(try testView.inspect().find(ViewType.Text.self, relation: .parent), "Search did not find a match") } func testSkipFound() throws { let testView = Test.MainView() let depthOrdered = try testView.inspect().findAll(ViewType.Text.self) .map { try $0.string() } XCTAssertEqual(depthOrdered, ["Btn", "Test_en", "123", "xyz", "modifier_0", "modifier_1"]) for index in 0..<depthOrdered.count { let string = try testView.inspect().find(ViewType.Text.self, traversal: .depthFirst, skipFound: index).string() XCTAssertEqual(string, depthOrdered[index]) } XCTAssertThrows(try testView.inspect().find( ViewType.Text.self, traversal: .depthFirst, skipFound: depthOrdered.count), "Search did only find 6 matches") } func testFindLocalizedTextWithLocaleParameter() throws { let testView = Test.MainView() XCTAssertThrows(try testView.inspect().find(text: "Test"), "Search did not find a match") XCTAssertNoThrow(try testView.inspect().find(text: "Test", locale: Locale(identifier: "fr"))) XCTAssertNoThrow(try testView.inspect().find(text: "Test_en")) XCTAssertNoThrow(try testView.inspect().find(text: "Test_en", locale: Locale(identifier: "en"))) XCTAssertNoThrow(try testView.inspect().find(text: "Test_en_au", locale: Locale(identifier: "en_AU"))) XCTAssertNoThrow(try testView.inspect().find(text: "Тест_ru", locale: Locale(identifier: "ru"))) XCTAssertThrows(try testView.inspect().find(text: "Тест_ru", locale: Locale(identifier: "en")), "Search did not find a match") } func testFindLocalizedTextWithGlobalDefault() throws { let testView = Test.MainView() let defaultLocale = Locale.testsDefault Locale.testsDefault = Locale(identifier: "ru") XCTAssertNoThrow(try testView.inspect().find(text: "Тест_ru")) Locale.testsDefault = defaultLocale } func testFindButton() throws { let testView = Test.MainView() XCTAssertNoThrow(try testView.inspect().find(button: "Btn")) XCTAssertNoThrow(try testView.inspect().find(button: "xyz")) XCTAssertThrows(try testView.inspect().find(button: "unknown"), "Search did not find a match") } func testFindViewWithId() throws { let testView = Test.MainView() XCTAssertNoThrow(try testView.inspect().find(viewWithId: "5").emptyView()) XCTAssertNoThrow(try testView.inspect().find(viewWithId: 7).text()) XCTAssertThrows(try testView.inspect().find(viewWithId: 0), "Search did not find a match") } func testFindViewWithTag() throws { let testView = Test.MainView() XCTAssertNoThrow(try testView.inspect().find(viewWithTag: 4).text()) XCTAssertNoThrow(try testView.inspect().find(viewWithTag: 9).view(Test.InnerView.self)) XCTAssertThrows(try testView.inspect().find(viewWithTag: 0), "Search did not find a match") } func testFindCustomView() throws { let testView = Test.MainView() XCTAssertNoThrow(try testView.inspect().find(Test.InnerView.self)) XCTAssertNoThrow(try testView.inspect().find(Test.InnerView.self, containing: "Btn")) XCTAssertThrows(try testView.inspect().find(Test.InnerView.self, containing: "123"), "Search did not find a match") } func testFindForConditionalView() throws { let testView = Test.ConditionalView() let texts = try testView.inspect().findAll(ViewType.Text.self) let values = try texts.map { try $0.string() } XCTAssertEqual(values, ["2", "3"]) } func testFindMatchingBlockerView() { let view = AnyView(Test.NonInspectableView().id(5)) XCTAssertNoThrow(try view.inspect().find(viewWithId: 5)) let err = "Search did not find a match. Possible blockers: NonInspectableView" XCTAssertThrows(try view.inspect().find(ViewType.EmptyView.self, traversal: .breadthFirst), err) XCTAssertThrows(try view.inspect().find(ViewType.EmptyView.self, traversal: .depthFirst), err) } func testConflictingViewTypeNames() throws { guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let style = Test.ConflictingViewTypeNamesStyle() let sut = try style.inspect(isPressed: true) XCTAssertEqual(try sut.find(text: "empty").pathToRoot, "group().view(EmptyView.self, 0).text()") XCTAssertEqual(try sut.find(ViewType.Label.self).pathToRoot, "group().label(1)") XCTAssertEqual(try sut.find(ViewType.StyleConfiguration.Label.self).pathToRoot, "group().styleConfigurationLabel(2)") } func testShapesSearching() throws { let sut = Group { Circle().inset(by: 5) Rectangle() Ellipse().offset(x: 2, y: 3) } XCTAssertThrows(try sut.inspect().find(text: "none"), "Search did not find a match") let testRect = CGRect(x: 0, y: 0, width: 10, height: 100) let refPath = Ellipse().offset(x: 2, y: 3).path(in: testRect) let ellipse = try sut.inspect().find(where: { try $0.shape().path(in: testRect) == refPath }) XCTAssertEqual(ellipse.pathToRoot, "group().shape(2)") } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) private extension Test { struct AccessibleView: View, Inspectable { var body: some View { Button(action: { }, label: { HStack { Text("text1").accessibilityLabel(Text("text1_access")) } }).mask(Group { Text("text2").accessibilityIdentifier("text2_access") }) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewSearchTests { func testFindViewWithAccessibilityLabel() throws { guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let sut = Test.AccessibleView() XCTAssertEqual(try sut.inspect().find(viewWithAccessibilityLabel: "text1_access").pathToRoot, "view(AccessibleView.self).button().labelView().hStack().text(0)") XCTAssertThrows( try sut.inspect().find(viewWithAccessibilityLabel: "abc"), "Search did not find a match" ) } func testFindViewWithAccessibilityIdentifier() throws { guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) else { throw XCTSkip() } let sut = Test.AccessibleView() XCTAssertEqual(try sut.inspect().find(viewWithAccessibilityIdentifier: "text2_access").pathToRoot, "view(AccessibleView.self).button().mask().group().text(0)") XCTAssertThrows( try sut.inspect().find(viewWithAccessibilityIdentifier: "abc"), "Search did not find a match" ) } }
mit
austinzheng/swift
benchmark/single-source/Exclusivity.swift
28
3495
//===--- Exclusivity.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // A set of tests for measuring the enforcement overhead of memory access // exclusivity rules. // //===----------------------------------------------------------------------===// import TestsUtils public let Exclusivity = [ // At -Onone // 25% swift_beginAccess // 15% tlv_get_addr // 15% swift_endAccess BenchmarkInfo( name: "ExclusivityGlobal", runFunction: run_accessGlobal, tags: [.runtime, .cpubench] ), // At -Onone // 23% swift_retain // 22% swift_release // 9% swift_beginAccess // 3% swift_endAccess BenchmarkInfo( name: "ExclusivityInMatSet", runFunction: run_accessInMatSet, tags: [.runtime, .cpubench, .unstable] ), // At -Onone // 25% swift_release // 23% swift_retain // 16% swift_beginAccess // 8% swift_endAccess BenchmarkInfo( name: "ExclusivityIndependent", runFunction: run_accessIndependent, tags: [.runtime, .cpubench] ), ] // Initially these benchmarks only measure access checks at -Onone. In // the future, access checks will also be emitted at -O. // Measure memory access checks on a trivial global. // --- public var globalCounter: Int = 0 // TODO: // - Merge begin/endAccess when no calls intervene (~2x speedup). // - Move Swift runtime into the OS (~2x speedup). // - Whole module analysis can remove exclusivity checks (> 10x speedup now, 4x speedup with runtime in OS). // (The global's "public" qualifier should make the benchmark immune to this optimization.) @inline(never) public func run_accessGlobal(_ N: Int) { globalCounter = 0 for _ in 1...10000*N { globalCounter += 1 } CheckResults(globalCounter == 10000*N) } // Measure memory access checks on a class property. // // Note: The end_unpaired_access forces a callback on the property's // materializeForSet! // --- // Hopefully the optimizer will not see this as "final" and optimize away the // materializeForSet. public class C { public var counter = 0 func inc() { counter += 1 } } // Thunk @inline(never) func updateClass(_ c: C) { c.inc() } // TODO: Replacing materializeForSet accessors with yield-once // accessors should make the callback overhead go away. @inline(never) public func run_accessInMatSet(_ N: Int) { let c = C() for _ in 1...10000*N { updateClass(c) } CheckResults(c.counter == 10000*N) } // Measure nested access to independent objects. // // A single access set is still faster than hashing for up to four accesses. // --- struct Var { var val = 0 } @inline(never) func update(a: inout Var, b: inout Var, c: inout Var, d: inout Var) { a.val += 1 b.val += 1 c.val += 1 d.val += 1 } @inline(never) public func run_accessIndependent(_ N: Int) { var a = Var() var b = Var() var c = Var() var d = Var() let updateVars = { update(a: &a, b: &b, c: &c, d: &d) } for _ in 1...1000*N { updateVars() } CheckResults(a.val == 1000*N && b.val == 1000*N && c.val == 1000*N && d.val == 1000*N) }
apache-2.0
codestergit/swift
test/Serialization/class.swift
2
2164
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -emit-object -emit-module -o %t %S/Inputs/def_class.swift -disable-objc-attr-requires-foundation-module // RUN: llvm-bcanalyzer %t/def_class.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Defs To Decls" -sil-debug-serialization -I %t %s | %FileCheck %s -check-prefix=SIL // RUN: echo "import def_class; struct A : ClassProto {}" | not %target-swift-frontend -typecheck -I %t - 2>&1 | %FileCheck %s -check-prefix=CHECK-STRUCT // CHECK-NOT: UnknownCode // CHECK-STRUCT: non-class type 'A' cannot conform to class protocol 'ClassProto' // Make sure we can "merge" def_class. // RUN: %target-swift-frontend -emit-module -o %t-merged.swiftmodule %t/def_class.swiftmodule -module-name def_class import def_class var a : Empty var b = TwoInts(a: 1, b: 2) var computedProperty : ComputedProperty var sum = b.x + b.y + computedProperty.value var intWrapper = ResettableIntWrapper() var r : Resettable = intWrapper r.reset() r.doReset() class AnotherIntWrapper : SpecialResettable, ClassProto { init() { value = 0 } var value : Int func reset() { value = 0 } func compute() { value = 42 } } var intWrapper2 = AnotherIntWrapper() r = intWrapper2 r.reset() var c : Cacheable = intWrapper2 c.compute() c.reset() var p = Pair(a: 1, b: 2.5) p.first = 2 p.second = 5.0 struct Int {} var gc = GenericCtor<Int>() gc.doSomething() a = StillEmpty() r = StillEmpty() var bp = BoolPair<Bool>() bp.bothTrue() var rawBP : Pair<Bool, Bool> rawBP = bp var rev : SpecialPair<Double> rev.first = 42 var comp : Computable = rev var simpleSub = ReadonlySimpleSubscript() var subVal = simpleSub[4] var complexSub = ComplexSubscript() complexSub[4, false] = complexSub[3, true] var rsrc = Resource() getReqPairLike() // SIL-LABEL: sil public_external [transparent] [serialized] @_T0s1poiS2i_SitF : $@convention(thin) (Int, Int) -> Int { func test(_ sharer: ResourceSharer) {} class HasNoOptionalReqs : ObjCProtoWithOptional { } HasNoOptionalReqs() OptionalImplementer().unrelated() extension def_class.ComputedProperty { }
apache-2.0
jairoeli/Habit
Zero/Sources/Utils/Snap.swift
1
597
// // Snap.swift // Zero // // Created by Jairo Eli de Leon on 5/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import UIKit /// Ceil to snap pixel func snap(_ x: CGFloat) -> CGFloat { let scale = UIScreen.main.scale return ceil(x * scale) / scale } func snap(_ point: CGPoint) -> CGPoint { return CGPoint(x: snap(point.x), y: snap(point.y)) } func snap(_ size: CGSize) -> CGSize { return CGSize(width: snap(size.width), height: snap(size.height)) } func snap(_ rect: CGRect) -> CGRect { return CGRect(origin: snap(rect.origin), size: snap(rect.size)) }
mit
rsmoz/swift-corelibs-foundation
TestFoundation/TestNSLocale.swift
1
4410
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSLocale : XCTestCase { var allTests : [(String, () throws -> Void)] { return [ ("test_constants", test_constants), ] } func test_constants() { XCTAssertEqual(NSCurrentLocaleDidChangeNotification, "kCFLocaleCurrentLocaleDidChangeNotification", "\(NSCurrentLocaleDidChangeNotification) is not equal to kCFLocaleCurrentLocaleDidChangeNotification") XCTAssertEqual(NSLocaleIdentifier, "kCFLocaleIdentifierKey", "\(NSLocaleIdentifier) is not equal to kCFLocaleIdentifierKey") XCTAssertEqual(NSLocaleLanguageCode, "kCFLocaleLanguageCodeKey", "\(NSLocaleLanguageCode) is not equal to kCFLocaleLanguageCodeKey") XCTAssertEqual(NSLocaleCountryCode, "kCFLocaleCountryCodeKey", "\(NSLocaleCountryCode) is not equal to kCFLocaleCountryCodeKey") XCTAssertEqual(NSLocaleScriptCode, "kCFLocaleScriptCodeKey", "\(NSLocaleScriptCode) is not equal to kCFLocaleScriptCodeKey") XCTAssertEqual(NSLocaleVariantCode, "kCFLocaleVariantCodeKey", "\(NSLocaleVariantCode) is not equal to kCFLocaleVariantCodeKey") XCTAssertEqual(NSLocaleExemplarCharacterSet, "kCFLocaleExemplarCharacterSetKey", "\(NSLocaleExemplarCharacterSet) is not equal to kCFLocaleExemplarCharacterSetKey") XCTAssertEqual(NSLocaleCalendar, "kCFLocaleCalendarKey", "\(NSLocaleCalendar) is not equal to kCFLocaleCalendarKey") XCTAssertEqual(NSLocaleCollationIdentifier, "collation", "\(NSLocaleCollationIdentifier) is not equal to collation") XCTAssertEqual(NSLocaleUsesMetricSystem, "kCFLocaleUsesMetricSystemKey", "\(NSLocaleUsesMetricSystem) is not equal to kCFLocaleUsesMetricSystemKey") XCTAssertEqual(NSLocaleMeasurementSystem, "kCFLocaleMeasurementSystemKey", "\(NSLocaleMeasurementSystem) is not equal to kCFLocaleMeasurementSystemKey") XCTAssertEqual(NSLocaleDecimalSeparator, "kCFLocaleDecimalSeparatorKey", "\(NSLocaleDecimalSeparator) is not equal to kCFLocaleDecimalSeparatorKey") XCTAssertEqual(NSLocaleGroupingSeparator, "kCFLocaleGroupingSeparatorKey", "\(NSLocaleGroupingSeparator) is not equal to kCFLocaleGroupingSeparatorKey") XCTAssertEqual(NSLocaleCurrencySymbol, "kCFLocaleCurrencySymbolKey", "\(NSLocaleCurrencySymbol) is not equal to kCFLocaleCurrencySymbolKey") XCTAssertEqual(NSLocaleCurrencyCode, "currency", "\(NSLocaleCurrencyCode) is not equal to currency") XCTAssertEqual(NSLocaleCollatorIdentifier, "kCFLocaleCollatorIdentifierKey", "\(NSLocaleCollatorIdentifier) is not equal to kCFLocaleCollatorIdentifierKey") XCTAssertEqual(NSLocaleQuotationBeginDelimiterKey, "kCFLocaleQuotationBeginDelimiterKey", "\(NSLocaleQuotationBeginDelimiterKey) is not equal to kCFLocaleQuotationBeginDelimiterKey") XCTAssertEqual(NSLocaleQuotationEndDelimiterKey, "kCFLocaleQuotationEndDelimiterKey", "\(NSLocaleQuotationEndDelimiterKey) is not equal to kCFLocaleQuotationEndDelimiterKey") XCTAssertEqual(NSLocaleAlternateQuotationBeginDelimiterKey, "kCFLocaleAlternateQuotationBeginDelimiterKey", "\(NSLocaleAlternateQuotationBeginDelimiterKey) is not equal to kCFLocaleAlternateQuotationBeginDelimiterKey") XCTAssertEqual(NSLocaleAlternateQuotationEndDelimiterKey, "kCFLocaleAlternateQuotationEndDelimiterKey", "\(NSLocaleAlternateQuotationEndDelimiterKey) is not equal to kCFLocaleAlternateQuotationEndDelimiterKey") } }
apache-2.0
belatrix/iOSAllStarsRemake
AllStars/AllStars/iPhone/Classes/Profile/EditProfileViewController.swift
1
11504
// // EditProfileViewController.swift // AllStars // // Created by Flavio Franco Tunqui on 6/2/16. // Copyright © 2016 Belatrix SF. All rights reserved. // import UIKit class EditProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate { @IBOutlet weak var viewHeader : UIView! @IBOutlet weak var imgUser : UIImageView! @IBOutlet weak var edtFirstName : UITextField! @IBOutlet weak var edtLastName : UITextField! @IBOutlet weak var edtSkypeId : UITextField! @IBOutlet weak var tableLocations : UITableView! @IBOutlet weak var scrollContent : UIScrollView! @IBOutlet weak var constraintHeightContent : NSLayoutConstraint! @IBOutlet weak var viewLoading : UIView! @IBOutlet weak var lblErrorMessage : UILabel! @IBOutlet weak var actUpdating : UIActivityIndicatorView! @IBOutlet weak var actLocations : UIActivityIndicatorView! @IBOutlet weak var btnCancel : UIButton! @IBOutlet weak var btnUploadPhoto : UIButton! @IBOutlet weak var viewFirstName : UIView! @IBOutlet weak var viewLastName : UIView! @IBOutlet weak var viewSkypeId : UIView! // photo var imagePickerController = UIImagePickerController() var hasNewImage = false var selectedImage = UIImage() var objUser : User? var arrayLocations = NSMutableArray() var isNewUser : Bool? override func viewDidLoad() { super.viewDidLoad() setViews() // imagePicker imagePickerController.delegate = self imagePickerController.allowsEditing = true self.updateUserInfo() } // MARK: - Style override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - UI func setViews() { if (isNewUser!) { btnCancel.hidden = true } OSPCrop.makeRoundView(self.imgUser) self.view.backgroundColor = UIColor.colorPrimary() viewHeader.backgroundColor = UIColor.colorPrimary() viewFirstName.backgroundColor = UIColor.colorPrimary() viewLastName.backgroundColor = UIColor.colorPrimary() viewSkypeId.backgroundColor = UIColor.colorPrimary() btnUploadPhoto.backgroundColor = UIColor.belatrix() } func lockScreen() { self.view.userInteractionEnabled = false self.actUpdating.startAnimating() } func unlockScreen() { self.view.userInteractionEnabled = true self.actUpdating.stopAnimating() } // MARK: - IBActions @IBAction func btnUploadPhotoTIU(sender: UIButton) { self.view.endEditing(true) let alert: UIAlertController = UIAlertController(title: "upload_from".localized, message: nil, preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "camera".localized, style: .Default, handler: {(alert: UIAlertAction) in self.imagePickerController.sourceType = .Camera self.presentViewController(self.imagePickerController, animated: true, completion: { imageP in }) }) let galleryAction = UIAlertAction(title: "gallery".localized, style: .Default, handler: {(alert: UIAlertAction) in self.imagePickerController.sourceType = .SavedPhotosAlbum self.presentViewController(self.imagePickerController, animated: true, completion: { imageP in }) }) let cancelAction = UIAlertAction(title: "Cancel".localized, style: .Cancel, handler: nil) alert.addAction(cameraAction) alert.addAction(galleryAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: {}) } @IBAction func btnCancelTUI(sender: UIButton) { self.view.endEditing(true) self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func btnDoneTUI(sender: UIButton) { self.view.endEditing(true) updateDataUser() } @IBAction func textFieldVCh(sender: UITextField) { if (sender == edtFirstName) { objUser!.user_first_name = edtFirstName.text } else if (sender == edtLastName) { objUser!.user_last_name = edtLastName.text } else if (sender == edtSkypeId) { objUser!.user_skype_id = edtSkypeId.text } } // MARK: - UITableViewDelegate, UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrayLocations.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "LocationTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LocationTableViewCell let locationBE = self.arrayLocations[indexPath.row] as! LocationBE cell.objLocationBE = locationBE cell.updateData() if (locationBE.location_pk == objUser!.user_location_id) { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let locationBE = self.arrayLocations[indexPath.row] as! LocationBE objUser!.user_location_id = locationBE.location_pk tableView.reloadData() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 36 } // MARK: - UIImagePickerController delegates func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage { hasNewImage = true selectedImage = pickedImage self.imgUser.image = selectedImage } else { hasNewImage = false } dismissViewControllerAnimated(true, completion: nil) } // MARK: - WebServices func listLocations() -> Void { self.actLocations.startAnimating() ProfileBC.listLocations {(arrayLocations) in self.actLocations.stopAnimating() self.arrayLocations = arrayLocations! self.lblErrorMessage.text = "no_availables_locations".localized self.viewLoading.alpha = CGFloat(!Bool(self.arrayLocations.count)) let height = Int(self.scrollContent.bounds.size.height) - 113 let newHeight = Int(self.tableLocations.frame.origin.y) + self.arrayLocations.count * 36 self.constraintHeightContent.constant = newHeight > height ? CGFloat(newHeight) : CGFloat(height) self.tableLocations.reloadData() } } func updateDataUser() -> Void { ProfileBC.updateInfoToUser(objUser!, newUser: isNewUser!, hasImage: hasNewImage, withController: self, withCompletion: {(user) in self.view.userInteractionEnabled = true self.actUpdating.stopAnimating() if (user != nil) { if (self.hasNewImage) { self.updatePhotoUser() } else { if (user!.user_base_profile_complete!) { if (self.isNewUser!) { self.openTabBar() } else { self.dismissViewControllerAnimated(true, completion: nil) } } } } }) } func updatePhotoUser() -> Void { lockScreen() let imageData = UIImageJPEGRepresentation(selectedImage, 0.5) ProfileBC.updatePhotoToUser(objUser!, withController: self, withImage: imageData!, withCompletion: {(user) in self.unlockScreen() if (user != nil) { if (user!.user_base_profile_complete!) { if (self.isNewUser!) { self.openTabBar() } else { self.dismissViewControllerAnimated(true, completion: nil) } } } }) } // MARK: - Other func openTabBar() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.login() appDelegate.addShortcutItems() } // MARK: - Configuration func updateDataUserUI() -> Void { if let firstName = self.objUser?.user_first_name { edtFirstName.text = firstName } if let lastName = self.objUser?.user_last_name { edtLastName.text = lastName } if let skypeId = self.objUser?.user_skype_id { edtSkypeId.text = skypeId } if let url_photo = self.objUser?.user_avatar{ if (url_photo != "") { OSPImageDownloaded.descargarImagenEnURL(url_photo, paraImageView: self.imgUser, conPlaceHolder: self.imgUser.image) } else { self.imgUser!.image = UIImage(named: "ic_user.png") } } else { self.imgUser!.image = UIImage(named: "ic_user.png") } } func updateUserInfo() -> Void { self.updateDataUserUI() self.listLocations() } // MARK: - UITextField delegates func textFieldShouldReturn(textField: UITextField!) -> Bool { if (textField == edtFirstName) { edtLastName.becomeFirstResponder() } else if (textField == edtLastName) { edtSkypeId.becomeFirstResponder() } textField.resignFirstResponder() return true } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "SkillsViewController" { let skillsNC = segue.destinationViewController as! UINavigationController let skillsVC = skillsNC.topViewController as! UserSkillsViewController skillsVC.objUser = self.objUser! } } }
mit
vector-im/vector-ios
RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationEmailInvites/Coordinator/SpaceCreationEmailInvitesCoordinator.swift
1
5458
// File created from SimpleUserProfileExample // $ createScreen.sh Spaces/SpaceCreation/SpaceCreationEmailInvites SpaceCreationEmailInvites /* 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 UIKit import SwiftUI final class SpaceCreationEmailInvitesCoordinator: Coordinator, Presentable { // MARK: - Properties // MARK: Private private let parameters: SpaceCreationEmailInvitesCoordinatorParameters private let spaceCreationEmailInvitesHostingController: UIViewController private var spaceCreationEmailInvitesViewModel: SpaceCreationEmailInvitesViewModelProtocol // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] var callback: ((SpaceCreationEmailInvitesCoordinatorAction) -> Void)? // MARK: - Setup @available(iOS 14.0, *) init(parameters: SpaceCreationEmailInvitesCoordinatorParameters) { self.parameters = parameters let service = SpaceCreationEmailInvitesService(session: parameters.session) let viewModel = SpaceCreationEmailInvitesViewModel(creationParameters: parameters.creationParams, service: service) let view = SpaceCreationEmailInvites(viewModel: viewModel.context) .addDependency(AvatarService.instantiate(mediaManager: parameters.session.mediaManager)) spaceCreationEmailInvitesViewModel = viewModel let hostingController = VectorHostingController(rootView: view) hostingController.isNavigationBarHidden = true spaceCreationEmailInvitesHostingController = hostingController } // MARK: - Public func start() { MXLog.debug("[SpaceCreationEmailInvitesCoordinator] did start.") spaceCreationEmailInvitesViewModel.completion = { [weak self] result in MXLog.debug("[SpaceCreationEmailInvitesCoordinator] SpaceCreationEmailInvitesViewModel did complete with result: \(result).") guard let self = self else { return } switch result { case .cancel: self.callback?(.cancel) case .back: self.callback?(.back) case .done: self.callback?(.done) case .inviteByUsername: self.callback?(.inviteByUsername) case .needIdentityServiceTerms(let baseUrl, let accessToken): self.presentIdentityServerTerms(with: baseUrl, accessToken: accessToken) case .identityServiceFailure(let error): self.showIdentityServiceFailure(error) } } } func toPresentable() -> UIViewController { return self.spaceCreationEmailInvitesHostingController } // MARK: - Identity service private var serviceTermsModalCoordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter? private func presentIdentityServerTerms(with baseUrl: String?, accessToken: String?) { guard let baseUrl = baseUrl, let accessToken = accessToken else { showIdentityServiceFailure(nil) return } let presenter = ServiceTermsModalCoordinatorBridgePresenter(session: parameters.session, baseUrl: baseUrl, serviceType: MXServiceTypeIdentityService, accessToken: accessToken) presenter.delegate = self presenter.present(from: self.toPresentable(), animated: true) serviceTermsModalCoordinatorBridgePresenter = presenter } private func showIdentityServiceFailure(_ error: Error?) { let alertController = UIAlertController(title: VectorL10n.findYourContactsIdentityServiceError, message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil)) self.toPresentable().present(alertController, animated: true, completion: nil); } } extension SpaceCreationEmailInvitesCoordinator: ServiceTermsModalCoordinatorBridgePresenterDelegate { func serviceTermsModalCoordinatorBridgePresenterDelegateDidAccept(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) { coordinatorBridgePresenter.dismiss(animated: true) { self.serviceTermsModalCoordinatorBridgePresenter = nil; self.callback?(.done) } } func serviceTermsModalCoordinatorBridgePresenterDelegateDidDecline(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter, session: MXSession) { coordinatorBridgePresenter.dismiss(animated: true) { self.serviceTermsModalCoordinatorBridgePresenter = nil; } } func serviceTermsModalCoordinatorBridgePresenterDelegateDidClose(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) { coordinatorBridgePresenter.dismiss(animated: true) { self.serviceTermsModalCoordinatorBridgePresenter = nil; } } }
apache-2.0
macacajs/XCTestWD
XCTestWD/XCTestWD/Server/Modules/Extensions/XCTestWDFindElementUtils.swift
1
1806
// // XCTestWDFindElementUtils.swift // XCTestWD // // Created by zhaoy on 7/5/17. // Copyright © 2017 XCTestWD. All rights reserved. // import Foundation class XCTestWDFindElementUtils { static func filterElement(usingText:String, withvalue:String, underElement:XCUIElement) throws -> XCUIElement? { return try filterElements(usingText:usingText, withValue:withvalue, underElement:underElement, returnAfterFirstMatch:true)?.first } // Routing for xpath, class name, name, id static func filterElements(usingText:String, withValue:String, underElement:XCUIElement, returnAfterFirstMatch:Bool) throws -> [XCUIElement]? { let isSearchByIdentifier = (usingText == "name" || usingText == "id" || usingText == "accessibility id") if usingText == "xpath" { return underElement.descendantsMatchingXPathQuery(xpathQuery: withValue, returnAfterFirstMatch: returnAfterFirstMatch) } else if usingText == "class name" { return underElement.descendantsMatchingClassName(className: withValue, returnAfterFirstMatch: returnAfterFirstMatch) } else if isSearchByIdentifier { return underElement.descendantsMatchingIdentifier(accessibilityId: withValue, returnAfterFirstMatch: returnAfterFirstMatch) } else if usingText == "predicate string" { let predicate = NSPredicate.xctestWDPredicate(withFormat: withValue) return underElement.descendantsMatching(Predicate: predicate!, returnAfterFirstMatch) } throw XCTestWDRoutingError.noSuchUsingMethod } }
mit
urbanthings/urbanthings-sdk-apple
UrbanThingsAPI/Internal/JSON/UInt+JSON.swift
1
1021
// // UInt+JSON.swift // UrbanThingsAPI // // Created by Mark Woollard on 29/04/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation /// Extend `UInt` to support JSONInitialization protocol for JSON parsing. extension UInt : JSONInitialization { /// Initializer to parse JSON object into `UInt`. A result is required and so if /// input is nil, or not parsable as `Bool` an error is thrown. /// - parameters: /// - required: Input JSON object that is required to be parsed into a `UInt`. /// - throws: Error.JSONParseError if unable to parse into `Uint`. public init(required:Any?) throws { guard let value = required as? UInt else { throw UTAPIError(expected:UInt.self, not:required, file:#file, function:#function, line:#line) } self = value } public init?(optional:Any?) throws { guard optional != nil else { return nil } try self.init(required: optional) } }
apache-2.0
hackcity2017/iOS-client-application
hackcity/Alert.swift
1
368
// // Alert.swift // hackcity // // Created by Remi Robert on 26/03/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit import RealmSwift class Alert: Object { dynamic var id: String = NSUUID().uuidString dynamic var date = Date() dynamic var value: Int = 0 override class func primaryKey() -> String? { return "id" } }
mit
muyang00/YEDouYuTV
YEDouYuZB/YEDouYuZB/Home/Views/CollectionAmuseHeadCell.swift
1
1849
// // CollectionAmuseHeadCell.swift // YEDouYuZB // // Created by yongen on 17/4/1. // Copyright © 2017年 yongen. All rights reserved. // import UIKit let kAmuseCellID = "kAmuseCellID" class CollectionAmuseHeadCell: UICollectionViewCell { @IBOutlet weak var collectionView: UICollectionView! var groups : [AnchorGroup]? { didSet{ collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kAmuseCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW = collectionView.bounds.width / 4 let itemH = collectionView.bounds.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) } } extension CollectionAmuseHeadCell : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseCellID, for: indexPath) as! CollectionGameCell //cell.backgroundColor = UIColor.randomColor() cell.baseGame = self.groups![indexPath.item] cell.clipsToBounds = true return cell } } extension CollectionAmuseHeadCell : UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("CollectionAmuseHeadCell") } }
apache-2.0
slightair/syu
Syu/Model/APIDocumentation.swift
1
3115
import Foundation import SQLite import RxSwift class APIDocumentation { let resourcesPath: URL var mapDBPath: URL { return resourcesPath.appendingPathComponent("external/map.db", isDirectory: false) } var cacheDBPath: URL { return resourcesPath.appendingPathComponent("external/cache.db", isDirectory: false) } var indexDBPath: URL { return SearchIndexCreator.indexFilePath } var mapDB: Connection! var cacheDB: Connection! var indexDB: Connection! required init(xcodePath: URL) { resourcesPath = xcodePath.appendingPathComponent("../SharedFrameworks/DNTDocumentationSupport.framework/Resources", isDirectory: true).standardizedFileURL } convenience init?() { guard let xcodePath = Xcode.currentPath else { return nil } self.init(xcodePath: xcodePath) } func prepare(completion: @escaping (() -> Void)) { createSearchIndexIfNeeded { self.openDatabases() completion() } } private func createSearchIndexIfNeeded(completion: @escaping (() -> Void)) { if SearchIndexCreator.existsIndexFile { completion() } else { let creator = SearchIndexCreator(resourcesPath: resourcesPath) creator.createSearchIndex { _ in completion() } } } private func openDatabases() { mapDB = try? Connection(mapDBPath.absoluteString, readonly: true) cacheDB = try? Connection(cacheDBPath.absoluteString, readonly: true) indexDB = try? Connection(indexDBPath.absoluteString, readonly: true) } func search(keyword: String) -> Observable<[SearchIndex]> { let query = Table("search_indexes").select(SearchIndex.Column.name, SearchIndex.Column.type, SearchIndex.Column.requestKey) .filter(SearchIndex.Column.name.like("\(keyword)%")) .limit(30) return Observable<[SearchIndex]>.create { observer in do { let indexes = try self.indexDB.prepare(query).map { record in SearchIndex(name: record[SearchIndex.Column.name], type: record[SearchIndex.Column.type], requestKey: record[SearchIndex.Column.requestKey]) } observer.onNext(indexes) observer.onCompleted() } catch let e { observer.onError(e) } return Disposables.create() } } func responseData(of key: String) -> ResponseData? { let requestKey = Expression<String>("request_key") let responseData = Expression<ResponseData>("response_data") let query = Table("response").select(responseData).filter(requestKey == key) if let row = try? cacheDB.pluck(query), let record = row { return record[responseData] } else { return nil } } }
mit
square/sqldelight
sample/iosApp/iosApp/PlayerRow.swift
2
547
// // PlayerCell.swift // iosApp // // Copyright © 2019 Square, Inc.. All rights reserved. // import Foundation import UIKit import common class PlayerRow: UITableViewCell { @IBOutlet weak var nameText: UILabel! @IBOutlet weak var teamText: UILabel! @IBOutlet weak var numberText: UILabel! func fillName(name: String) { nameText.text = name } func fillNumber(number: String) { numberText.text = number } func fillTeamName(teamName: String) { teamText.text = teamName } }
apache-2.0
ruddfawcett/Notepad
Notepad/Style.swift
1
674
// // Style.swift // Notepad // // Created by Rudd Fawcett on 10/14/16. // Copyright © 2016 Rudd Fawcett. All rights reserved. // import Foundation public struct Style { var regex: NSRegularExpression! public var attributes: [NSAttributedString.Key: Any] = [:] public init(element: Element, attributes: [NSAttributedString.Key: Any]) { self.regex = element.toRegex() self.attributes = attributes } public init(regex: NSRegularExpression, attributes: [NSAttributedString.Key: Any]) { self.regex = regex self.attributes = attributes } public init() { self.regex = Element.unknown.toRegex() } }
mit
onevcat/CotEditor
CotEditor/Sources/ProgressViewController.swift
1
4913
// // ProgressViewController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-06-07. // // --------------------------------------------------------------------------- // // © 2014-2022 1024jp // // 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 Combine import Cocoa final class ProgressViewController: NSViewController { // MARK: Private Properties @objc private dynamic let progress: Progress @objc private dynamic let message: String private let closesAutomatically: Bool private let appliesDescriptionImmediately: Bool private var progressSubscriptions: Set<AnyCancellable> = [] private var completionSubscriptions: Set<AnyCancellable> = [] @IBOutlet private weak var indicator: NSProgressIndicator? @IBOutlet private weak var descriptionField: NSTextField? @IBOutlet private weak var button: NSButton? // MARK: - // MARK: Lifecycle /// Initialize view with given progress instance. /// /// - Parameters: /// - coder: The coder to instantiate the view from a storyboard. /// - progress: The progress instance to indicate. /// - message: The text to display as the message label of the indicator. /// - closesAutomatically: Whether dismiss the view when the progress is finished. /// - appliesDescriptionImmediately: Whether throttle the update of the description field. init?(coder: NSCoder, progress: Progress, message: String, closesAutomatically: Bool = true, appliesDescriptionImmediately: Bool = false) { assert(!progress.isCancelled) assert(!progress.isFinished) self.progress = progress self.message = message self.closesAutomatically = closesAutomatically self.appliesDescriptionImmediately = appliesDescriptionImmediately super.init(coder: coder) progress.publisher(for: \.isFinished) .filter { $0 } .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.done() } .store(in: &self.completionSubscriptions) progress.publisher(for: \.isCancelled) .filter { $0 } .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.dismiss(nil) } .store(in: &self.completionSubscriptions) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear() { super.viewWillAppear() guard let indicator = self.indicator, let descriptionField = self.descriptionField else { return assertionFailure() } self.progressSubscriptions.removeAll() self.progress.publisher(for: \.fractionCompleted, options: .initial) .throttle(for: 0.2, scheduler: DispatchQueue.main, latest: true) .assign(to: \.doubleValue, on: indicator) .store(in: &self.progressSubscriptions) self.progress.publisher(for: \.localizedDescription, options: .initial) .throttle(for: self.appliesDescriptionImmediately ? 0 : 0.1, scheduler: DispatchQueue.main, latest: true) .assign(to: \.stringValue, on: descriptionField) .store(in: &self.progressSubscriptions) } override func viewDidDisappear() { super.viewDidDisappear() self.progressSubscriptions.removeAll() self.completionSubscriptions.removeAll() } // MARK: Public Methods /// Change the state of progress to finished. func done() { self.completionSubscriptions.removeAll() if self.closesAutomatically { return self.dismiss(self) } guard let button = self.button else { return assertionFailure() } self.descriptionField?.stringValue = self.progress.localizedDescription button.title = "OK".localized button.action = #selector(dismiss(_:) as (Any?) -> Void) button.keyEquivalent = "\r" } // MARK: Actions /// Cancel current process. @IBAction func cancel(_ sender: Any?) { self.progress.cancel() } }
apache-2.0
wangshuaidavid/WSDynamicAlbumMaker
WSDynamicAlbumMakerDemo/WSDynamicAlbumMaker/WSDynamicAlbumMaker.swift
1
9964
// // WSDynamicAlbumMaker.swift // WSDynamicAlbumMakerDemo // // Created by ennrd on 4/25/15. // Copyright (c) 2015 ws. All rights reserved. // import Foundation import AVFoundation import CoreMedia import AssetsLibrary public typealias WSDynamicAlbumMakerExportCompletionBlock = (NSURL!, NSError!) -> Void public class WSDynamicAlbumMaker { public class var sharedInstance: WSDynamicAlbumMaker { struct Static { static let instance: WSDynamicAlbumMaker = WSDynamicAlbumMaker() } return Static.instance } public func createDynamicAlbum (#videoURL: NSURL, renderLayer:CALayer, duration: Float, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) { self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: nil, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: false, completionBlock: completionBlock) } public func createDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) { self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: audioURL, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: false, completionBlock: completionBlock) } public func createDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, isSaveToPhotosAlbum: Bool, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) { self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: audioURL, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: isSaveToPhotosAlbum, completionBlock: completionBlock) } } //MARK: Utility functions extension WSDynamicAlbumMaker { public func getCoreAnimationBeginTimeAtZero() -> CFTimeInterval { return AVCoreAnimationBeginTimeAtZero } public func querySizeWithAssetURL(#videoURL: NSURL) -> CGSize { let videoAsset = AVURLAsset(URL: videoURL, options: nil) return self.querySize(video: videoAsset) } private func querySize(#video: AVAsset) -> CGSize { let videoAssetTrack = video.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack let videoTransform = videoAssetTrack.preferredTransform var isVideoAssetPortrait = false if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) { isVideoAssetPortrait = true } if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) { isVideoAssetPortrait = true } var natureSize = CGSizeZero if isVideoAssetPortrait { natureSize = CGSizeMake(videoAssetTrack.naturalSize.height, videoAssetTrack.naturalSize.width) } else { natureSize = videoAssetTrack.naturalSize } return natureSize } } //MARK: Main process functions extension WSDynamicAlbumMaker { private func goCreateDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, isSaveToPhotosAlbum: Bool, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) { // 0 - Get AVAsset from NSURL let videoAsset = AVURLAsset(URL: videoURL, options: nil) // 1 - Prepare VideoAssetTrack and DurationTimeRange for further use let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack let durationCMTime = CMTimeMakeWithSeconds(Float64(duration), 30) let durationTimeRange = CMTimeRangeMake(kCMTimeZero, durationCMTime) // 2 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances. let mixComposition = AVMutableComposition() // 3 - Get Video track let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) videoTrack.insertTimeRange(durationTimeRange, ofTrack: videoAssetTrack, atTime: kCMTimeZero, error: nil) // 3.0 - Handle Audio asset if let audiourl_ = audioURL { let audioAsset = AVURLAsset(URL: audiourl_, options: nil) let audioAssetTrack = audioAsset.tracksWithMediaType(AVMediaTypeAudio).first as! AVAssetTrack let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) audioTrack.insertTimeRange(durationTimeRange, ofTrack: audioAssetTrack, atTime: kCMTimeZero, error: nil) } // 3.1 - Create AVMutableVideoCompositionInstruction let mainInstruction = AVMutableVideoCompositionInstruction() mainInstruction.timeRange = durationTimeRange // 3.2 - Create an AVMutableVideoCompositionLayerInstruction for the video track and fix the orientation. let videolayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) videolayerInstruction.setTransform(videoAssetTrack.preferredTransform, atTime: kCMTimeZero) videolayerInstruction.setOpacity(0.0, atTime: videoAsset.duration) // 3.3 - Add instructions mainInstruction.layerInstructions = [videolayerInstruction] let mainCompositionInst = AVMutableVideoComposition() let naturalSize = self.querySize(video: videoAsset) let renderWidth = naturalSize.width let renderHeight = naturalSize.height mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight) mainCompositionInst.instructions = [mainInstruction] mainCompositionInst.frameDuration = CMTimeMake(1, 30) self.applyVideoEffectsToComposition(mainCompositionInst, size: naturalSize, overlayLayer: renderLayer) // 4 - Get path let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentDirectory = paths.first as! String let randomInt = arc4random() % 1000 let fullPathDocs = documentDirectory.stringByAppendingPathComponent("CreatedVideo-\(randomInt).mov") let createdVideoURL = NSURL.fileURLWithPath(fullPathDocs) // 5 - Create exporter let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) exporter.outputURL = createdVideoURL exporter.outputFileType = AVFileTypeQuickTimeMovie exporter.shouldOptimizeForNetworkUse = true exporter.videoComposition = mainCompositionInst exporter.exportAsynchronouslyWithCompletionHandler { let outputURL = exporter.outputURL switch (exporter.status) { case AVAssetExportSessionStatus.Completed: if isSaveToPhotosAlbum { self.exportCompletionHandleSaveToAssetLibrary(outputURL, block: completionBlock) }else { self.exportCompletionHandleNotSaveToAssetLibrary(outputURL, block: completionBlock) } break; case AVAssetExportSessionStatus.Failed: self.exportCompletionHandleWithError(-1, message: "Exporting Failed", block: completionBlock) break; case AVAssetExportSessionStatus.Cancelled: self.exportCompletionHandleWithError(-2, message: "Exporting Cancelled", block: completionBlock) break; default: self.exportCompletionHandleWithError(0, message: "Exporting Unkown error occured", block: completionBlock) break; } } } private func exportCompletionHandleNotSaveToAssetLibrary(fileAssetURL: NSURL, block: WSDynamicAlbumMakerExportCompletionBlock) { dispatch_async(dispatch_get_main_queue(), { block(fileAssetURL, nil) }) } private func exportCompletionHandleSaveToAssetLibrary(fileAssetURL: NSURL, block: WSDynamicAlbumMakerExportCompletionBlock) { let library = ALAssetsLibrary() if library.videoAtPathIsCompatibleWithSavedPhotosAlbum(fileAssetURL) { library.writeVideoAtPathToSavedPhotosAlbum(fileAssetURL, completionBlock: { (assetURL, error) -> Void in NSFileManager.defaultManager().removeItemAtURL(fileAssetURL, error: nil) dispatch_async(dispatch_get_main_queue(), { block(assetURL, error) }) }) } } private func exportCompletionHandleWithError(code: Int, message: String, block: WSDynamicAlbumMakerExportCompletionBlock) { dispatch_async(dispatch_get_main_queue(), { block(nil, NSError(domain: "Video_Export", code: code, userInfo: ["ErrorMsg": message])) }) } private func applyVideoEffectsToComposition(composition: AVMutableVideoComposition, size:CGSize, overlayLayer: CALayer) { let parentLayer = CALayer() let videoLayer = CALayer() parentLayer.frame = CGRectMake(0, 0, size.width, size.height) videoLayer.frame = CGRectMake(0, 0, size.width, size.height) parentLayer.addSublayer(videoLayer) parentLayer.addSublayer(overlayLayer) composition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer) } }
apache-2.0
Idomeneus/duo-iOS
Duo/Duo/UIImageViewHelpers.swift
1
259
// // UIImageViewHelpers.swift // Duo // // Created by Bobo on 10/24/15. // Copyright © 2015 Boris Emorine. All rights reserved. // import Foundation import UIKit extension UIImageView { func setImageWithURL(URL: NSURL) { } }
mit
net-a-porter-mobile/XCTest-Gherkin
Pod/Core/XCTestCase+Gherkin.swift
1
14375
// // File.swift // whats-new // // Created by Sam Dean on 26/10/2015. // Copyright © 2015 net-a-porter. All rights reserved. // import Foundation import XCTest import WebKit #if canImport(XCTest_Gherkin_ObjC) import XCTest_Gherkin_ObjC #endif /** I wanted this to work with both KIFTestCase and UITestCase which meant extending UITestCase - a subclass wouldn't work with both of them. It's nicer code IMHO to have the state as a single associated property beacuse of the grossness of setting/getting it. This means that anytime I want to access my extra properties I just do `state.{propertyName}` */ class GherkinState: NSObject, XCTestObservation { var test: XCTestCase? // Arbitrary user data associated with the current test scenario var scenarioContext: [String: MatchedStringRepresentable] = [:] // The list of all steps the system knows about var steps = Set<Step>() // Used to track step nesting i.e. steps calling out to other steps var currentStepDepth: Int = 0 // file and line from where currently executed step was invoked var currentStepLocation: (file: String, line: Int)! // When we are in an Outline block, this defines the examples to loop over var examples: [Example]? // The current example the Outline is running over var currentExample: Example? // currently executed example line when running test from feature file var currentNativeExampleLineNumber: Int? // Store the name of the current test to help debugging output var currentTestName: String = "NO TESTS RUN YET" var currentSuiteName: String = "NO TESTS RUN YET" // Store the name of the current step to help debugging output var currentStepName: String = "NO CURRENT STEP YET" fileprivate var missingStepsImplementations = [String]() override init() { super.init() XCTestObservationCenter.shared.addTestObserver(self) } func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: Int) { guard let test = self.test, let (file, line) = test.state.currentStepLocation else { return } if filePath == file && lineNumber == line { return } if #available(iOS 9.0, OSX 10.11, *) { if automaticScreenshotsBehaviour.contains(.onFailure) { test.attachScreenshot() } } test.recordFailure(withDescription: description, inFile: file, atLine: line, expected: false) if let exampleLineNumber = self.currentNativeExampleLineNumber, lineNumber != exampleLineNumber { test.recordFailure(withDescription: description, inFile: file, atLine: exampleLineNumber, expected: false) } } func testCaseDidFinish(_ testCase: XCTestCase) { testCase.scenarioContext = [:] } func testSuiteDidFinish(_ testSuite: XCTestSuite) { XCTestObservationCenter.shared.removeTestObserver(self) } func gherkinStepsAndMatchesMatchingExpression(_ expression: String) -> [(step: Step, match: NSTextCheckingResult)] { let range = NSMakeRange(0, expression.count) return self.steps.compactMap { step in step.regex.firstMatch(in: expression, options: [], range: range).map { (step: step, match: $0) } } } func gherkinStepsMatchingExpression(_ expression: String) -> [Step] { return self.gherkinStepsAndMatchesMatchingExpression(expression).map { $0.step } } // TODO: This needs to be refactored since function has a side effect (appends to missingStepsImplementations) func matchingGherkinStepExpressionFound(_ expression: String) -> Bool { let matches = self.gherkinStepsMatchingExpression(expression) switch matches.count { case 0: print("Step definition not found for '\(expression)'") self.missingStepsImplementations.append(expression) case 1: //no issues, so proceed return true default: matches.forEach { NSLog("Matching step : \(String(reflecting: $0))") } print("Multiple step definitions found for : '\(expression)'") } return false } func shouldPrintTemplateCodeForAllMissingSteps() -> Bool { return self.missingStepsImplementations.count > 0 } func resetMissingSteps() { self.missingStepsImplementations = [] } func printTemplatedCodeForAllMissingSteps() { self.missingStepsImplementations .printAsTemplatedCodeForAllMissingSteps(suggestedSteps: self.suggestedSteps(forStep:)) } func printStepDefinitions() { self.loadAllStepsIfNeeded() self.steps.printStepsDefinitions() } func loadAllStepsIfNeeded() { guard self.steps.count == 0 else { return } // Create an instance of each step definer and call it's defineSteps method allSubclassesOf(StepDefiner.self).forEach { subclass in subclass.init(test: self.test!).defineSteps() } UnusedStepsTracker.shared().setSteps(self.steps.map { String(reflecting: $0) }) UnusedStepsTracker.shared().printUnusedSteps = { $0.printAsUnusedSteps() } precondition(self.steps.count > 0, "No steps have been defined - there must be at least one subclass of StepDefiner which defines at least one step!") } } /** Add Gherkin methods to XCTestCase */ public extension XCTestCase { fileprivate struct AssociatedKeys { static var State = "AssociatedStateKey" } internal var state: GherkinState { type(of: self).state.test = self return type(of: self).state } internal static var state: GherkinState { get { guard let s = objc_getAssociatedObject(self, &AssociatedKeys.State) else { let initialState = GherkinState() objc_setAssociatedObject(self, &AssociatedKeys.State, initialState, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) return initialState } return s as! GherkinState } } /** Current scenario context used to share the state between steps in a single scenario. Note: Example values will override context values associated with the same key. */ var scenarioContext: [String: MatchedStringRepresentable] { get { return state.scenarioContext } set { state.scenarioContext = newValue } } /** Run the step matching the specified expression */ func Given(_ expression: String, file: String = #file, line: Int = #line) { self.performStep(expression, keyword: "Given", file: file, line: line) } /** Run the step matching the specified expression */ func When(_ expression: String, file: String = #file, line: Int = #line) { self.performStep(expression, keyword: "When", file: file, line: line) } /** Run the step matching the specified expression */ func Then(_ expression: String, file: String = #file, line: Int = #line) { self.performStep(expression, keyword: "Then", file: file, line: line) } /** Run the step matching the specified expression */ func And(_ expression: String, file: String = #file, line: Int = #line) { self.performStep(expression, keyword: "And", file: file, line: line) } /** Run the step matching the specified expression */ func But(_ expression: String, file: String = #file, line: Int = #line) { self.performStep(expression, keyword: "But", file: file, line: line) } } private var automaticScreenshotsBehaviour: AutomaticScreenshotsBehaviour = .none private var automaticScreenshotsQuality: XCTAttachment.ImageQuality = .medium private var automaticScreenshotsLifetime: XCTAttachment.Lifetime = .deleteOnSuccess public struct AutomaticScreenshotsBehaviour: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let onFailure = AutomaticScreenshotsBehaviour(rawValue: 1 << 0) public static let beforeStep = AutomaticScreenshotsBehaviour(rawValue: 1 << 1) public static let afterStep = AutomaticScreenshotsBehaviour(rawValue: 1 << 2) public static let none: AutomaticScreenshotsBehaviour = [] public static let all: AutomaticScreenshotsBehaviour = [.onFailure, .beforeStep, .afterStep] } @available(iOS 9.0, OSX 10.11, *) extension XCTestCase { /// Set behaviour for automatic screenshots (default is `.none`), their quality (default is `.medium`) and lifetime (default is `.deleteOnSuccess`) public static func setAutomaticScreenshotsBehaviour(_ behaviour: AutomaticScreenshotsBehaviour, quality: XCTAttachment.ImageQuality = .medium, lifetime: XCTAttachment.Lifetime = .deleteOnSuccess) { automaticScreenshotsBehaviour = behaviour automaticScreenshotsQuality = quality automaticScreenshotsLifetime = lifetime } func attachScreenshot() { // if tests have no host app there is no point in making screenshots guard Bundle.main.bundlePath.hasSuffix(".app") else { return } let screenshot = XCUIScreen.main.screenshot() let attachment = XCTAttachment(screenshot: screenshot, quality: automaticScreenshotsQuality) attachment.lifetime = automaticScreenshotsLifetime add(attachment) } } /** Put our package methods into this extension */ extension XCTestCase { fileprivate var testName: String? { guard let selector = self.invocation?.selector else { return nil } let rawName = String(describing: selector) let testName = rawName.hasPrefix("test") ? String(rawName.dropFirst(4)) : rawName return testName } // MARK: Adding steps /** Adds a step to the global store of steps, but only if this expression isn't already defined with a step */ func addStep(_ expression: String, options: NSRegularExpression.Options, file: String, line: Int, function: @escaping (StepMatches<String>)->()) { let step = Step(expression, options: options, file: file, line: line, function) state.steps.insert(step); } /** Finds and performs a step test based on expression */ func performStep(_ initialExpression: String, keyword: String, file: String = #file, line: Int = #line) { // Get a mutable copy - if we are in an outline we might be changing this var expression = initialExpression // Make sure that we have created our steps self.state.loadAllStepsIfNeeded() var variables = scenarioContext // If we are in an example, transform the step to reflect the current example's value if let example = state.currentExample { variables = scenarioContext.merging(example, uniquingKeysWith: { $1 }) } // For each variable go through the step expression and replace the placeholders if needed expression = expression.replacingExamplePlaceholders(variables) // Get the step and the matches inside it guard let (step, match) = self.state.gherkinStepsAndMatchesMatchingExpression(expression).first else { if !self.state.matchingGherkinStepExpressionFound(expression) && self.state.shouldPrintTemplateCodeForAllMissingSteps() { self.state.printStepDefinitions() self.state.printTemplatedCodeForAllMissingSteps() self.state.resetMissingSteps() } preconditionFailure("Failed to find a match for a step: \(expression)") } UnusedStepsTracker.shared().performedStep(String(reflecting: step)) // If this is the first step, debug the test (scenario) name and feature as well if state.currentStepDepth == 0 { let suiteName = String(describing: type(of: self)) if suiteName != state.currentSuiteName { print("Feature: \(suiteName)") state.currentSuiteName = suiteName } if let testName = self.testName, testName != state.currentTestName { print(" Scenario: \(testName.humanReadableString)") state.currentTestName = testName if state.currentExample == nil { performBackground() } } } state.currentStepName = expression let (matches, debugDescription) = step.matches(from: match, expression: expression) // Debug the step name print(" step \(keyword) \(currentStepDepthString())\(debugDescription) \(step.fullLocationDescription)") // Run the step XCTContext.runActivity(named: "\(keyword) \(debugDescription) \(step.shortLocationDescription)") { (_) in state.currentStepDepth += 1 state.currentStepLocation = (file, line) if #available(iOS 9.0, OSX 10.11, *) { if automaticScreenshotsBehaviour.contains(.beforeStep) { attachScreenshot() } } step.function(matches) if #available(iOS 9.0, OSX 10.11, *) { if automaticScreenshotsBehaviour.contains(.afterStep) { attachScreenshot() } } state.currentStepLocation = nil state.currentStepDepth -= 1 } } /** Converts the current step depth into a string to use for padding - returns: A String of spaces equal to the current step depth */ fileprivate func currentStepDepthString() -> String { return String(repeating: " ", count: state.currentStepDepth) } } func requireNotNil<T>(_ expr: @autoclosure () -> T?, _ message: String) -> T { guard let value = expr() else { preconditionFailure(message) } return value } func requireToConvert<T>(_ expr: @autoclosure () -> T?, _ match: String, _ expression: String) -> T { return requireNotNil(expr(), "Could not convert '\(match)' to \(T.self) in '\(expression)'") }
apache-2.0
phimage/Prephirences
Sources/Prephirences.swift
1
6367
// // Prephirences.swift // Prephirences /* The MIT License (MIT) Copyright (c) 2017 Eric Marchand (phimage) 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 /* Preferences manager class that contains some Preferences */ open class Prephirences { /** Shared preferences. Could be replaced by any other preferences */ public static var sharedInstance: PreferencesType = MutableDictionaryPreferences() // casting shortcut for sharedInstance public static var sharedMutableInstance: MutablePreferencesType? { return sharedInstance as? MutablePreferencesType } // MARK: register by key fileprivate static var _instances = [PrephirencesKey: PreferencesType]() /* Get Preferences for PrephirencesKey */ fileprivate class func instance(forKey key: PrephirencesKey, orRegister newOne: PreferencesType? = nil) -> PreferencesType? { if let value = self._instances[key] { return value } else if let toRegister = newOne { registerInstance(toRegister, forKey: key) } return newOne } /* Add Preferences for PrephirencesKey */ fileprivate class func register(preferences: PreferencesType, forKey key: PrephirencesKey) { self._instances[key] = preferences } /* Remove Preferences for PrephirencesKey */ fileprivate class func unregisterPreferences(forKey key: PrephirencesKey) -> PreferencesType? { return self._instances.removeValue(forKey: key) } /* Get Preferences for key */ open class func instance<Key: Hashable>(forKey key: Key, orRegister newOne: PreferencesType? = nil) -> PreferencesType? { return self.instance(forKey: PrephirencesKey(key), orRegister: newOne) } /* Add Preferences for key */ open class func registerInstance<Key: Hashable>(_ preferences: PreferencesType, forKey key: Key) { self.register(preferences: preferences, forKey: PrephirencesKey(key)) } /* Remove Preferences for key */ open class func unregisterInstance<Key: Hashable>(forKey key: Key) -> PreferencesType? { return self.unregisterPreferences(forKey: PrephirencesKey(key)) } /* allow to use subscript with desired key type */ public static func instances<KeyType: Hashable>() -> PrephirencesForType<KeyType> { return PrephirencesForType<KeyType>() } static func isEmpty<T>(_ value: T?) -> Bool { return value == nil } public static func unraw<T>(_ object: T.RawValue?) -> T? where T: RawRepresentable, T.RawValue: PreferenceObject { if let rawValue = object { return T(rawValue: rawValue) } return nil } public static func raw<T>(_ value: T?) -> T.RawValue? where T: RawRepresentable, T.RawValue: PreferenceObject { return value?.rawValue } } /* Allow to access or modify Preferences according to key type */ open class PrephirencesForType<Key: Hashable> { open subscript(key: PreferenceKey) -> PreferencesType? { get { return Prephirences.instance(forKey: key) } set { if let value = newValue { Prephirences.registerInstance(value, forKey: key) } else { _ = Prephirences.unregisterInstance(forKey: key) } } } } /* Generic key for dictionary */ struct PrephirencesKey: Hashable, Equatable { fileprivate let underlying: Any fileprivate let hashFunc: (inout Hasher) -> Void fileprivate let equalityFunc: (Any) -> Bool init<T: Hashable>(_ key: T) { underlying = key hashFunc = { key.hash(into: &$0) } equalityFunc = { if let other = $0 as? T { return key == other } return false } } func hash(into hasher: inout Hasher) { hashFunc(&hasher) } } internal func == (left: PrephirencesKey, right: PrephirencesKey) -> Bool { return left.equalityFunc(right.underlying) } // MARK: archive/unarchive extension Prephirences { public static func unarchive(fromPreferences preferences: PreferencesType, forKey key: PreferenceKey) -> PreferenceObject? { if let data = preferences.data(forKey: key) { return unarchive(data) } return nil } public static func archive(object value: PreferenceObject?, intoPreferences preferences: MutablePreferencesType, forKey key: PreferenceKey) { if let toArchive: PreferenceObject = value { let data = archive(toArchive) preferences.set(data, forKey: key) } else { preferences.removeObject(forKey: key) } } public static func unarchive(_ data: Data) -> PreferenceObject? { return NSKeyedUnarchiver.unarchiveObject(with: data) } public static func archive(_ object: PreferenceObject) -> Data { return NSKeyedArchiver.archivedData(withRootObject: object) } } extension PreferencesType { public func unarchiveObject(forKey key: PreferenceKey) -> PreferenceObject? { return Prephirences.unarchive(fromPreferences: self, forKey: key) } } extension MutablePreferencesType { public func set(objectToArchive value: PreferenceObject?, forKey key: PreferenceKey) { Prephirences.archive(object: value, intoPreferences: self, forKey: key) } }
mit
justindarc/focus
XCUITest/CopyTest.swift
4
1522
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest // Note: this test is tested as part of the base test case, and thus is disabled here. class CopyTest: BaseTestCase { override func setUp() { super.setUp() dismissFirstRunUI() } override func tearDown() { app.terminate() super.tearDown() } func testCopyMenuItem() { let urlBarTextField = app.textFields["URLBar.urlText"] loadWebPage("http://localhost:6573/licenses.html") // Must offset textfield press to support 5S. urlBarTextField.coordinate(withNormalizedOffset: CGVector.zero).withOffset(CGVector(dx: 10, dy: 0)).press(forDuration: 1.5) waitforHittable(element: app.menuItems["Copy"]) app.menuItems["Copy"].tap() waitforNoExistence(element: app.menuItems["Copy"]) loadWebPage("bing.com") urlBarTextField.tap() urlBarTextField.coordinate(withNormalizedOffset: CGVector.zero).withOffset(CGVector(dx: 10, dy: 0)).press(forDuration: 1.5) waitforHittable(element: app.menuItems["Paste & Go"]) app.menuItems["Paste & Go"].tap() waitForWebPageLoad() guard let text = urlBarTextField.value as? String else { XCTFail() return } XCTAssert(text == "http://localhost:6573/licenses.html") } }
mpl-2.0
AbelSu131/ios-charts
Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
1
19136
// // HorizontalBarChartRenderer.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/ios-charts // import Foundation import CoreGraphics import UIKit public class HorizontalBarChartRenderer: BarChartRenderer { private var xOffset: CGFloat = 0.0; private var yOffset: CGFloat = 0.0; public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler); } internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context); var barData = delegate!.barChartRendererData(self); var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency); var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self); var dataSetOffset = (barData.dataSetCount - 1); var groupSpace = barData.groupSpace; var groupSpaceHalf = groupSpace / 2.0; var barSpace = dataSet.barSpace; var barSpaceHalf = barSpace / 2.0; var containsStacks = dataSet.isStacked; var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency); var entries = dataSet.yVals as! [BarChartDataEntry]; var barWidth: CGFloat = 0.5; var phaseY = _animator.phaseY; var barRect = CGRect(); var barShadow = CGRect(); var y: Double; // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j]; // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf; var vals = e.values; if (!containsStacks || vals == nil) { y = e.value; var bottom = x - barWidth + barSpaceHalf; var top = x + barWidth - barSpaceHalf; var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0); var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0); // multiply the height of the rect with the phase if (right > 0) { right *= phaseY; } else { left *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue; } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break; } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = viewPortHandler.contentLeft; barShadow.origin.y = barRect.origin.y; barShadow.size.width = viewPortHandler.contentWidth; barShadow.size.height = barRect.size.height; CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor); CGContextFillRect(context, barShadow); } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); CGContextFillRect(context, barRect); } else { var all = e.value; // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value; var bottom = x - barWidth + barSpaceHalf; var top = x + barWidth - barSpaceHalf; var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0); var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0); // multiply the height of the rect with the phase if (right > 0) { right *= phaseY; } else { left *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); barShadow.origin.x = viewPortHandler.contentLeft; barShadow.origin.y = barRect.origin.y; barShadow.size.width = viewPortHandler.contentWidth; barShadow.size.height = barRect.size.height; CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor); CGContextFillRect(context, barShadow); } // fill the stack for (var k = 0; k < vals.count; k++) { all -= vals[k]; y = vals[k] + all; var bottom = x - barWidth + barSpaceHalf; var top = x + barWidth - barSpaceHalf; var right = y >= 0.0 ? CGFloat(y) : 0.0; var left = y <= 0.0 ? CGFloat(y) : 0.0; // multiply the height of the rect with the phase if (right > 0) { right *= phaseY; } else { left *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break; } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break; } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor); CGContextFillRect(context, barRect); } } } CGContextRestoreGState(context); } internal override func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5; var top = x - barWidth + barspacehalf; var bottom = x + barWidth - barspacehalf; var left = y >= from ? CGFloat(y) : CGFloat(from); var right = y <= from ? CGFloat(y) : CGFloat(from); rect.origin.x = left; rect.origin.y = top; rect.size.width = right - left; rect.size.height = bottom - top; trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY); } public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY); } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self); var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self); var dataSets = barData.dataSets; var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self); var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self); var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right; let valueOffsetPlus: CGFloat = 5.0; var posOffset: CGFloat; var negOffset: CGFloat; for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i]; if (!dataSet.isDrawValuesEnabled) { continue; } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency); var valueFont = dataSet.valueFont; var valueTextColor = dataSet.valueTextColor; var yOffset = -valueFont.lineHeight / 2.0; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency); var entries = dataSet.yVals as! [BarChartDataEntry]; var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i); // if only single values are drawn (sum) if (!drawValuesForWholeStackEnabled) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue; } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break; } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue; } var val = entries[j].value; var valueText = formatter!.stringFromNumber(val)!; // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width; posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)); negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus); if (isInverted) { posOffset = -posOffset - valueTextWidth; negOffset = -negOffset - valueTextWidth; } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: .Left, color: valueTextColor); } } else { // if each value of a potential stack should be drawn for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j]; var vals = e.values; // we still draw stacked bars, but there is one non-stacked in between if (vals == nil) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue; } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break; } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue; } var val = e.value; var valueText = formatter!.stringFromNumber(val)!; // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width; posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)); negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus); if (isInverted) { posOffset = -posOffset - valueTextWidth; negOffset = -negOffset - valueTextWidth; } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: .Left, color: valueTextColor); } else { var transformed = [CGPoint](); var cnt = 0; var add = e.value; for (var k = 0; k < vals.count; k++) { add -= vals[cnt]; transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0)); cnt++; } trans.pointValuesToPixel(&transformed); for (var k = 0; k < transformed.count; k++) { var val = vals[k]; var valueText = formatter!.stringFromNumber(val)!; // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width; posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)); negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus); if (isInverted) { posOffset = -posOffset - valueTextWidth; negOffset = -negOffset - valueTextWidth; } var x = transformed[k].x + (val >= 0 ? posOffset : negOffset); var y = valuePoints[j].y; if (!viewPortHandler.isInBoundsX(x)) { continue; } if (!viewPortHandler.isInBoundsTop(y)) { break; } if (!viewPortHandler.isInBoundsBottom(y)) { continue; } drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: .Left, color: valueTextColor); } } } } } } } internal override func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self); if (barData === nil) { return false; } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY; } }
apache-2.0
pedromsantos/Ellis
Ellis/Keys/Key.swift
1
6010
public enum Key: Int { case AMajor case AFlatMajor case BMajor case BFlatMajor case CMajor case CSharpMajor case DMajor case DFlatMajor case EMajor case EFlatMajor case FMajor case FSharpMajor case GMajor case GFlatMajor case AMinor case AFlatMinor case ASharpMinor case BMinor case BFlatMinor case CMinor case CSharpMinor case DMinor case EFlatMinor case EMinor case FMinor case FSharpMinor case GMinor case GSharpMinor private static let fifths = [Note.F, Note.C, Note.G, Note.D, Note.A, Note.E, Note.B] private static let allValues = [ (Relative: Key.FSharpMinor, Root: Note.A, Accidents: 3, Quality: KeyQuality.Major), (Relative: Key.FMinor, Root: Note.AFlat, Accidents: -4, Quality: KeyQuality.Major), (Relative: Key.GSharpMinor, Root: Note.B, Accidents: 5, Quality: KeyQuality.Major), (Relative: Key.GMinor, Root: Note.BFlat, Accidents: -2, Quality: KeyQuality.Major), (Relative: Key.AMinor, Root: Note.C, Accidents: 0, Quality: KeyQuality.Major), (Relative: Key.BFlatMinor, Root: Note.CSharp, Accidents: 7, Quality: KeyQuality.Major), (Relative: Key.BMinor, Root: Note.D, Accidents: 2, Quality: KeyQuality.Major), (Relative: Key.BFlatMinor, Root: Note.DFlat, Accidents: -5, Quality: KeyQuality.Major), (Relative: Key.CSharpMinor, Root: Note.E, Accidents: 4, Quality: KeyQuality.Major), (Relative: Key.CMinor, Root: Note.EFlat, Accidents: -3, Quality: KeyQuality.Major), (Relative: Key.DMinor, Root: Note.F, Accidents: -1, Quality: KeyQuality.Major), (Relative: Key.EFlatMinor, Root: Note.FSharp, Accidents: 6, Quality: KeyQuality.Major), (Relative: Key.EMinor, Root: Note.G, Accidents: 1, Quality: KeyQuality.Major), (Relative: Key.EFlatMinor, Root: Note.GFlat, Accidents: -6, Quality: KeyQuality.Major), (Relative: Key.CMajor, Root: Note.A, Accidents: 0, Quality: KeyQuality.Minor), (Relative: Key.BMajor, Root: Note.AFlat, Accidents: -7, Quality: KeyQuality.Minor), (Relative: Key.CSharpMinor, Root: Note.ASharp, Accidents: 7, Quality: KeyQuality.Minor), (Relative: Key.DMajor, Root: Note.B, Accidents: 2, Quality: KeyQuality.Minor), (Relative: Key.DFlatMajor, Root: Note.BFlat, Accidents: -5, Quality: KeyQuality.Minor), (Relative: Key.EFlatMajor, Root: Note.C, Accidents: -3, Quality: KeyQuality.Minor), (Relative: Key.EMajor, Root: Note.CSharp, Accidents: 4, Quality: KeyQuality.Minor), (Relative: Key.FMajor, Root: Note.D, Accidents: -1, Quality: KeyQuality.Minor), (Relative: Key.GFlatMajor, Root: Note.EFlat, Accidents: -6, Quality: KeyQuality.Minor), (Relative: Key.GMajor, Root: Note.E, Accidents: 1, Quality: KeyQuality.Minor), (Relative: Key.AFlatMajor, Root: Note.F, Accidents: -4, Quality: KeyQuality.Minor), (Relative: Key.AMajor, Root: Note.FSharp, Accidents: 3, Quality: KeyQuality.Minor), (Relative: Key.BFlatMajor, Root: Note.G, Accidents: -2, Quality: KeyQuality.Minor), (Relative: Key.BMajor, Root: Note.GSharp, Accidents: 5, Quality: KeyQuality.Minor) ] public var rootName: String { return root.Name } public var keyNotes:[Note] { return generateKeyNotes() } public var KeyNoteNames:[String] { return generateKeyNotes().map({ (note:Note) in return note.Name }) } public func i() -> Note { return generateKeyNotes()[0] } public func ii() -> Note { return generateKeyNotes()[1] } public func iii() -> Note { return generateKeyNotes()[2] } public func iv() -> Note { return generateKeyNotes()[3] } public func v() -> Note { return generateKeyNotes()[4] } public func vi() -> Note { return generateKeyNotes()[5] } public func vii() -> Note { return self.quality == KeyQuality.Minor ? generateKeyNotes()[6].sharp() : generateKeyNotes()[6] } public var quality: KeyQuality { return Key.allValues[self.rawValue].Quality } public var relativeKey: Key { return Key.allValues[self.rawValue].Relative } public func degreeForNote(note:Note) -> Int { return generateKeyNotes().indexOf(note)! + 1 } private func generateKeyNotes() -> [Note] { if self.accidents < 0 { return sortKeyNotes(createKeyFromFlatAccidents()) } if self.accidents > 0 { return sortKeyNotes(createKeyFromSharpAccidents()) } return sortKeyNotes(Key.fifths); } private func createKeyFromFlatAccidents() -> [Note] { var keyNotes = Array(Key.fifths.reverse()) let max = (-1) * accidents for i in 0 ..< max { keyNotes[i] = keyNotes[i].flat() } return keyNotes } private func createKeyFromSharpAccidents() -> [Note] { var keyNotes = Key.fifths let max = accidents for i in 0 ..< max { keyNotes[i] = keyNotes[i].sharp() } return keyNotes } private func sortKeyNotes(notes: [Note]) -> [Note] { var sortedkeyNotes = notes.sort({ n1, n2 in return n2 > n1 }) if(sortedkeyNotes.first == root) { return sortedkeyNotes } var last: Note? = nil while(last != root) { last = sortedkeyNotes.last sortedkeyNotes.removeLast() sortedkeyNotes.insert(last!, atIndex: 0) } return sortedkeyNotes } private var root: Note { return Key.allValues[self.rawValue].Root } private var accidents: Int { return Key.allValues[self.rawValue].Accidents } }
mit
YouareMylovelyGirl/Sina-Weibo
新浪微博/新浪微博/Classes/View(视图和控制器)/Profile/ProfileController.swift
1
858
// // ProfileController.swift // 新浪微博 // // Created by 阳光 on 2017/6/5. // Copyright © 2017年 YG. All rights reserved. // import UIKit class ProfileController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
wuzhenli/MyDailyTestDemo
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/property-observer.xcplaygroundpage/Contents.swift
2
1492
import Foundation class MyClass { let oneYearInSecond: TimeInterval = 365 * 24 * 60 * 60 var date: NSDate { willSet { let d = date print("即将将日期从 \(d) 设定至 \(newValue)") } didSet { if (date.timeIntervalSinceNow > oneYearInSecond) { print("设定的时间太晚了!") date = NSDate().addingTimeInterval(oneYearInSecond) } print("已经将日期从 \(oldValue) 设定至 \(date)") } } init() { date = NSDate() } } let foo = MyClass() foo.date = foo.date.addingTimeInterval(10086) // 输出 // 即将将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000 // 已经将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000 // 365 * 24 * 60 * 60 = 31_536_000 foo.date = foo.date.addingTimeInterval(100_000_000) // 输出 // 即将将日期从 2014-08-23 13:24:14 +0000 设定至 2017-10-23 23:10:54 +0000 // 设定的时间太晚了! // 已经将日期从 2014-08-23 13:24:14 +0000 设定至 2015-08-23 13:24:14 +0000 class A { var number :Int { get { print("get") return 1 } set {print("set")} } } class B: A { override var number: Int { willSet {print("willSet")} didSet {print("didSet")} } } let b = B() b.number = 0 // 输出 // get // willSet // set // didSet
apache-2.0
tlax/GaussSquad
GaussSquad/Controller/Home/CHome.swift
1
769
import UIKit class CHome:CController { let model:MHome private weak var viewHome:VHome! override init() { model = MHome() super.init() } required init?(coder:NSCoder) { return nil } override func loadView() { let viewHome:VHome = VHome(controller:self) self.viewHome = viewHome view = viewHome } //MARK: public func selected(item:MHomeItem) { guard let controller:CController = item.selected() else { return } parentController.push( controller:controller, horizontal:CParent.TransitionHorizontal.fromRight) } }
mit
achimk/Cars
CarsApp/Components/ErrorHandling/ErrorPresenterType.swift
1
512
// // ErrorPresenterType.swift // CarsApp // // Created by Joachim Kret on 30/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation protocol ErrorPresentable { func present(with error: Error) } protocol ErrorDismissible { func dismiss() } protocol ErrorPresenterType: ErrorPresentable, ErrorDismissible, ErrorHandlingChainable { } extension ErrorPresenterType { func can(handle error: Error) -> Bool { return next?.can(handle: error) ?? false } }
mit
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/iOS/PaintViewControllerInitStyle.swift
1
2015
// // PaintViewControllerInitStyle.swift // SwiftGL // // Created by jerry on 2015/12/5. // Copyright © 2015年 Jerry Chan. All rights reserved. // extension PaintViewController { func initAnimateState() { toolViewState = SubViewPanelAnimateState(view: toolView, constraint: toolViewLeadingConstraint, hideValue: -240, showValue: 0) //noteEditViewState = SubViewPanelAnimateState(view: noteEditView, constraint: noteEditViewTopConstraint, hideValue: -384 , showValue: 0) noteListViewState = SubViewPanelAnimateState(view: noteListView, constraint: noteListViewTrailingConstraint, hideValue: -240, showValue: 0) toolViewState.animateHide(0.2) noteListViewState.animateHide(0) //noteEditViewState.animateHide(0) noteListTableView.separatorStyle = .none //drawGreyBorder(noteListTableView) //drawGreyBorder(toolView) circleButton(showToolButton) } //Apearance func drawNoteEditTextViewStyle() { noteEditTextView.layer.borderColor = UIColor.lightGray.cgColor noteEditTextView.layer.borderWidth = 1 noteEditTextView.layer.cornerRadius = 5 noteEditTextView.clipsToBounds = true } func drawGreyBorder(_ view:UIView) { view.layer.borderColor = UIColor.lightGray.cgColor view.layer.borderWidth = 1 //view.layer.cornerRadius = } func circleButton(_ button:UIButton) { button.layer.cornerRadius = 0.5 * button.frame.width button.backgroundColor = UIColor.white button.layer.borderColor = UIColor.lightGray.cgColor button.layer.borderWidth = 1 //var tintedImage = button.imageForState(UIControlState.Normal) //tintedImage = button. [self tintedImageWithColor:color image:tintedImage]; //[self setImage:tintedImage forState:state]; } }
mit
iosyoujian/iOS8-day-by-day
24-presentation-controllers/BouncyPresent/BouncyPresent/BouncyViewControllerAnimator.swift
22
1541
// // Copyright 2014 Scott Logic // // 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 class BouncyViewControllerAnimator : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.8 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey) { let centre = presentedView.center presentedView.center = CGPointMake(centre.x, -presentedView.bounds.size.height) transitionContext.containerView().addSubview(presentedView) UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10.0, options: nil, animations: { presentedView.center = centre }, completion: { _ in transitionContext.completeTransition(true) }) } } }
apache-2.0
weekenlee/Dodo
Dodo/Utils/UnderKeyboardDistrib.swift
5
6026
// // An iOS libary for moving content from under the keyboard. // // https://github.com/exchangegroup/UnderKeyboard // // This file was automatically generated by combining multiple Swift source files. // // ---------------------------- // // UnderKeyboardLayoutConstraint.swift // // ---------------------------- import UIKit /** Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides. */ @objc public class UnderKeyboardLayoutConstraint: NSObject { private weak var bottomLayoutConstraint: NSLayoutConstraint? private weak var bottomLayoutGuide: UILayoutSupport? private var keyboardObserver = UnderKeyboardObserver() private var initialConstraintConstant: CGFloat = 0 private var minMargin: CGFloat = 10 private var viewToAnimate: UIView? public override init() { super.init() keyboardObserver.willAnimateKeyboard = keyboardWillAnimate keyboardObserver.animateKeyboard = animateKeyboard keyboardObserver.start() } deinit { stop() } /// Stop listening for keyboard notifications. public func stop() { keyboardObserver.stop() } /** Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides. - parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden. - parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint. - parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10. - parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations. */ public func setup(bottomLayoutConstraint: NSLayoutConstraint, view: UIView, minMargin: CGFloat = 10, bottomLayoutGuide: UILayoutSupport? = nil) { initialConstraintConstant = bottomLayoutConstraint.constant self.bottomLayoutConstraint = bottomLayoutConstraint self.minMargin = minMargin self.bottomLayoutGuide = bottomLayoutGuide self.viewToAnimate = view // Keyboard is already open when setup is called if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight where currentKeyboardHeight > 0 { keyboardWillAnimate(currentKeyboardHeight) } } func keyboardWillAnimate(height: CGFloat) { guard let bottomLayoutConstraint = bottomLayoutConstraint else { return } let layoutGuideHeight = bottomLayoutGuide?.length ?? 0 let correctedHeight = height - layoutGuideHeight if height > 0 { let newConstantValue = correctedHeight + minMargin if newConstantValue > initialConstraintConstant { // Keyboard height is bigger than the initial constraint length. // Increase constraint length. bottomLayoutConstraint.constant = newConstantValue } else { // Keyboard height is NOT bigger than the initial constraint length. // Show the initial constraint length. bottomLayoutConstraint.constant = initialConstraintConstant } } else { bottomLayoutConstraint.constant = initialConstraintConstant } } func animateKeyboard(height: CGFloat) { viewToAnimate?.layoutIfNeeded() } } // ---------------------------- // // UnderKeyboardObserver.swift // // ---------------------------- import UIKit /** Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard. */ public final class UnderKeyboardObserver: NSObject { public typealias AnimationCallback = (height: CGFloat) -> () let notificationCenter: NSNotificationCenter /// Function that will be called before the keyboard is shown and before animation is started. public var willAnimateKeyboard: AnimationCallback? /// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view. public var animateKeyboard: AnimationCallback? /// Current height of the keyboard. Has value `nil` if unknown. public var currentKeyboardHeight: CGFloat? public override init() { notificationCenter = NSNotificationCenter.defaultCenter() super.init() } deinit { stop() } /// Start listening for keyboard notifications. public func start() { stop() notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillShowNotification, object: nil); notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillHideNotification, object: nil); } /// Stop listening for keyboard notifications. public func stop() { notificationCenter.removeObserver(self) } // MARK: - Notification func keyboardNotification(notification: NSNotification) { let isShowing = notification.name == UIKeyboardWillShowNotification if let userInfo = notification.userInfo, let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().height, let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue, let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { let correctedHeight = isShowing ? height : 0 willAnimateKeyboard?(height: correctedHeight) UIView.animateWithDuration(duration, delay: NSTimeInterval(0), options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.unsignedLongValue), animations: { [weak self] in self?.animateKeyboard?(height: correctedHeight) }, completion: nil ) currentKeyboardHeight = correctedHeight } } }
mit
dejavu1988/google-services
ios/gcm/GcmExampleSwift/ViewController.swift
21
3259
// // Copyright (c) 2015 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 @objc(ViewController) // match the ObjC symbol name inside Storyboard class ViewController: UIViewController { @IBOutlet weak var registeringLabel: UILabel! @IBOutlet weak var registrationProgressing: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateRegistrationStatus:", name: appDelegate.registrationKey, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "showReceivedMessage:", name: appDelegate.messageKey, object: nil) registrationProgressing.hidesWhenStopped = true registrationProgressing.startAnimating() } func updateRegistrationStatus(notification: NSNotification) { registrationProgressing.stopAnimating() if let info = notification.userInfo as? Dictionary<String,String> { if let error = info["error"] { registeringLabel.text = "Error registering!" showAlert("Error registering with GCM", message: error) } else if let _ = info["registrationToken"] { registeringLabel.text = "Registered!" let message = "Check the xcode debug console for the registration token that you " + " can use with the demo server to send notifications to your device" showAlert("Registration Successful!", message: message) } } else { print("Software failure. Guru meditation.") } } func showReceivedMessage(notification: NSNotification) { if let info = notification.userInfo as? Dictionary<String,AnyObject> { if let aps = info["aps"] as? Dictionary<String, String> { showAlert("Message received", message: aps["alert"]!) } } else { print("Software failure. Guru meditation.") } } func showAlert(title:String, message:String) { if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil) alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) } else { // Fallback on earlier versions let alert = UIAlertView.init(title: title, message: message, delegate: nil, cancelButtonTitle: "Dismiss") alert.show() } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/01059-swift-constraints-constraintsystem-opengeneric.swift
11
453
// 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 struct d<U : d where H.c = b() func compose(#object1: H) { d
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/27650-swift-metatypetype-get.swift
11
474
// 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{ enum e{{}class c func a{ func c<I{ protocol d{ func b func b<T where I.c:b
apache-2.0
mirkofetter/TUIOSwift
TUIOSwift/TuioTime.swift
1
9021
// // TuioTime.swift // TUIOSwift // // Created by Mirko Fetter on 21.02.17. // Copyright © 2017 grugru. All rights reserved. // import Foundation /** * The TuioTime class is a simple structure that is used to reprent the time that has elapsed since the session start. * The time is internally represented as seconds and fractions of microseconds which should be more than sufficient for gesture related timing requirements. * Therefore at the beginning of a typical TUIO session the static method initSession() will set the reference time for the session. * Another important static method getSessionTime will return a TuioTime object representing the time elapsed since the session start. * The class also provides various addtional convience method, which allow some simple time arithmetics. * * @author Mirko Fetter * @version 0.9 * * 1:1 Swift port of the TUIO 1.1 Java Library by Martin Kaltenbrunner */ class TuioTime { /** * the time since session start in seconds */ internal var seconds:CLong = 0; /** * time fraction in microseconds */ internal var micro_seconds:CLong = 0; /** * the session start time in seconds */ internal static var start_seconds:CLong = 0; /** * start time fraction in microseconds */ internal static var start_micro_seconds:CLong = 0; /** * the associated frame ID */ internal var frame_id:CLong = 0; /** * The default constructor takes no arguments and sets * the Seconds and Microseconds attributes of the newly created TuioTime both to zero. */ init() { self.seconds = 0; self.micro_seconds = 0; } /** * This constructor takes the provided time represented in total Milliseconds * and assigs this value to the newly created TuioTime. * * @param msec the total time in Millseconds */ init ( msec:CLong) { self.seconds = msec/1000; self.micro_seconds = 1000*(msec%1000); } /** * This constructor takes the provided time represented in Seconds and Microseconds * and assigs these value to the newly created TuioTime. * * @param sec the total time in seconds * @param usec the microseconds time component */ init (sec:CLong, usec:CLong) { self.seconds = sec; self.micro_seconds = usec; } /** * This constructor takes the provided TuioTime * and assigs its Seconds and Microseconds values to the newly created TuioTime. * * @param ttime the TuioTime used to copy */ init(ttime:TuioTime) { self.seconds = ttime.getSeconds(); self.micro_seconds = ttime.getMicroseconds(); } /** * This constructor takes the provided TuioTime * and assigs its Seconds and Microseconds values to the newly created TuioTime. * * @param ttime the TuioTime used to copy * @param the Frame ID to associate */ init(ttime:TuioTime, f_id:CLong) { self.seconds = ttime.getSeconds(); self.micro_seconds = ttime.getMicroseconds(); self.frame_id = f_id; } /** * Sums the provided time value represented in total Microseconds to this TuioTime. * * @param us the total time to add in Microseconds * @return the sum of this TuioTime with the provided argument in microseconds */ func add(us:CLong) -> TuioTime{ let sec:CLong = seconds + us/1000000; let usec:CLong = micro_seconds + us%1000000; return TuioTime(sec: sec,usec: usec); } /** * Sums the provided TuioTime to the private Seconds and Microseconds attributes. * * @param ttime the TuioTime to add * @return the sum of this TuioTime with the provided TuioTime argument */ func add( ttime: TuioTime) -> TuioTime{ var sec:CLong = seconds + ttime.getSeconds(); var usec:CLong = micro_seconds + ttime.getMicroseconds(); sec += usec/1000000; usec = usec%1000000; return TuioTime(sec:sec,usec:usec); } /** * Subtracts the provided time represented in Microseconds from the private Seconds and Microseconds attributes. * * @param us the total time to subtract in Microseconds * @return the subtraction result of this TuioTime minus the provided time in Microseconds */ func subtract(us:CLong) -> TuioTime{ var sec:CLong = seconds - us/1000000; var usec:CLong = micro_seconds - us%1000000; if (usec<0) { usec += 1000000; sec-=1; } return TuioTime(sec:sec,usec:usec); } /** * Subtracts the provided TuioTime from the private Seconds and Microseconds attributes. * * @param ttime the TuioTime to subtract * @return the subtraction result of this TuioTime minus the provided TuioTime */ func subtract( ttime: TuioTime) -> TuioTime{ var sec:CLong = seconds - ttime.getSeconds(); var usec:CLong = micro_seconds - ttime.getMicroseconds(); if (usec<0) { usec += 1000000; sec-=1; } return TuioTime(sec:sec,usec:usec); } /** * Takes a TuioTime argument and compares the provided TuioTime to the private Seconds and Microseconds attributes. * * @param ttime the TuioTime to compare * @return true if the two TuioTime have equal Seconds and Microseconds attributes */ func equals( ttime: TuioTime) -> Bool{ if ((seconds==ttime.getSeconds()) && (micro_seconds==ttime.getMicroseconds())) { return true; }else { return false; } } /** * Resets the seconds and micro_seconds attributes to zero. */ func reset() { seconds = 0; micro_seconds = 0; } /** * Returns the TuioTime Seconds component. * @return the TuioTime Seconds component */ func getSeconds()->CLong { return seconds; } /** * Returns the TuioTime Microseconds component. * @return the TuioTime Microseconds component */ func getMicroseconds() ->CLong { return micro_seconds; } /** * Returns the total TuioTime in Milliseconds. * @return the total TuioTime in Milliseconds */ func getTotalMilliseconds()-> CLong{ return seconds*1000+micro_seconds/1000; } /** * This static method globally resets the TUIO session time. */ static func initSession() { let startTime:TuioTime = getSystemTime(); start_seconds = startTime.getSeconds(); start_micro_seconds = startTime.getMicroseconds(); } /** * Returns the present TuioTime representing the time since session start. * @return the present TuioTime representing the time since session start */ static func getSessionTime()->TuioTime{ let sessionTime:TuioTime = getSystemTime().subtract(ttime: getStartTime()); return sessionTime; } /** * Returns the absolut TuioTime representing the session start. * @return the absolut TuioTime representing the session start */ static func getStartTime()->TuioTime{ return TuioTime(sec: self.start_seconds, usec: self.start_micro_seconds) } /** * Returns the absolut TuioTime representing the current system time. * @return the absolut TuioTime representing the current system time */ static func getSystemTime()->TuioTime{ //ToDo check if this equals Java long usec = System.nanoTime()/1000; //-- let time = mach_absolute_time(); var timeBaseInfo = mach_timebase_info_data_t() mach_timebase_info(&timeBaseInfo) let elapsedNano = (time * UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))/1000; let usec:CLong = CLong(elapsedNano); //-- return TuioTime(sec: usec/1000000,usec: usec%1000000); } /** * associates a Frame ID to this TuioTime. * @param f_id the Frame ID to associate */ func setFrameID( f_id:CLong) { frame_id=f_id; } /** * Returns the Frame ID associated to this TuioTime. * @return the Frame ID associated to this TuioTime */ func getFrameID() -> CLong { return frame_id; } static func getSystemTimeMillis()->CLong{ //ToDo check if this equals Java long usec = System.nanoTime()/1000; //-- let time = mach_absolute_time(); var timeBaseInfo = mach_timebase_info_data_t() mach_timebase_info(&timeBaseInfo) let elapsedNano = (time * UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))/1000; return CLong(elapsedNano); } }
mit
liveminds/AERecord
AERecordExample/Event.swift
5
274
// // Event.swift // AERecordExample // // Created by Marko Tadic on 11/4/14. // Copyright (c) 2014 ae. All rights reserved. // import Foundation import CoreData class Event: NSManagedObject { @NSManaged var timeStamp: NSDate @NSManaged var selected: Bool }
mit
safetycase/Dl_student
Dl_student/DL_student/DL_student/AppDelegate.swift
1
2132
// // AppDelegate.swift // DL_student // // Created by Gao on 16/11/8. // Copyright © 2016年 Gao. 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:. } }
mit
ZevEisenberg/Padiddle
Padiddle/Padiddle/Utilities/HelpImageHandler.swift
1
1530
// // HelpImageProtocol.swift // Padiddle // // Created by Zev Eisenberg on 1/22/16. // Copyright © 2016 Zev Eisenberg. All rights reserved. // import Foundation import UIKit.UIImage import WebKit /// Handle asset://assetName requests from WKWebView and return the appropriate /// image asset. Built with the help of https://medium.com/glose-team/custom-scheme-handling-and-wkwebview-in-ios-11-72bc5113e344 class HelpImageHandler: NSObject, WKURLSchemeHandler { static var colorButtonImage: UIImage? func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { guard let url = urlSchemeTask.request.url, url.scheme == "asset", let imageName = url.host else { return } var image: UIImage? switch imageName { case "recordButton": image = UIImage.recordButtonImage() case "colorButton": image = HelpImageHandler.colorButtonImage default: image = UIImage(named: imageName) } guard let existingImage = image, let imageData = existingImage.pngData() else { return } let urlResponse = URLResponse(url: url, mimeType: "image/png", expectedContentLength: imageData.count, textEncodingName: nil) urlSchemeTask.didReceive(urlResponse) urlSchemeTask.didReceive(imageData) urlSchemeTask.didFinish() } func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { } }
mit
madbat/Set
Package.swift
1
989
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Set", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Set", targets: ["Set"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "Set", dependencies: []), .testTarget( name: "SetTests", dependencies: ["Set"]), ] )
mit
khillman84/music-social
music-social/music-social/FancyView.swift
1
580
// // FancyView.swift // music-social // // Created by Kyle Hillman on 4/22/17. // Copyright © 2017 Kyle Hillman. All rights reserved. // import UIKit class FancyView: UIView { override func awakeFromNib() { super.awakeFromNib() //Set the shadow size and look layer.shadowColor = UIColor(red: gShadowGray, green: gShadowGray, blue: gShadowGray, alpha: 0.6).cgColor layer.shadowOpacity = 0.8 layer.shadowRadius = 5.0 layer.shadowOffset = CGSize(width: 1.0, height: 1.0) layer.cornerRadius = 2.0 } }
mit
AcaiBowl/Closurable
Closurable/Releasable.swift
1
780
// // Releasable.swift // Closurable // // Created by Toru Asai on 2017/09/07. // Copyright © 2017年 AcaiBowl. All rights reserved. // import Foundation public protocol Releasable { func release() } public final class ActionReleasable: Releasable { private var _observer: Any? private var _action: (() -> Void)? public init(with observer: Any, action: @escaping () -> Void) { _observer = observer _action = action } public func release() { _action?() _observer = nil } } public final class NoOptionalReleasable: Releasable { private var _observer: Any? public init(with observer: Any) { _observer = observer } public func release() { _observer = nil } }
mit
ViacomInc/Router
Source/Router.swift
1
3871
//////////////////////////////////////////////////////////////////////////// // Copyright 2015 Viacom 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 public typealias RouteHandler = (_ req: Request) -> Void open class Router { fileprivate var orderedRoutes = [Route]() fileprivate var routes = [Route: RouteHandler]() public init() {} /** Binds a route to a router - parameter aRoute: A string reprsentation of the route. It can include url params, for example id in /video/:id - parameter callback: Triggered when a route is matched */ open func bind(_ aRoute: String, callback: @escaping RouteHandler) { do { let route = try Route(aRoute: aRoute) orderedRoutes.append(route) routes[route] = callback } catch let error as Route.RegexResult { print(error.debugDescription) } catch { fatalError("[\(aRoute)] unknown bind error") } } /** Matches an incoming URL to a route present in the router. Returns nil if none are matched. - parameter url: An URL of an incoming request to the router - returns: The matched route or nil */ open func match(_ url: URL) -> Route? { guard let routeComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } // form the host/path url let host = routeComponents.host.flatMap({"/\($0)"}) ?? "" let path = routeComponents.path let routeToMatch = "\(host)\(path)" let queryParams = routeComponents.queryItems var urlParams = [URLQueryItem]() // match the route! for route in orderedRoutes { guard let pattern = route.routePattern else { continue } var regex: NSRegularExpression do { regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) } catch let error as NSError { fatalError(error.localizedDescription) } let matches = regex.matches(in: routeToMatch, options: [], range: NSMakeRange(0, routeToMatch.characters.count)) // check if routeToMatch has matched if matches.count > 0 { let match = matches[0] // gather url params for i in 1 ..< match.numberOfRanges { let name = route.urlParamKeys[i-1] let value = (routeToMatch as NSString).substring(with: match.rangeAt(i)) urlParams.append(URLQueryItem(name: name, value: value)) } // fire callback if let callback = routes[route] { callback(Request(aRoute: route, urlParams: urlParams, queryParams: queryParams)) } // return route that was matched return route } } // nothing matched return nil } }
apache-2.0
sublimter/Meijiabang
KickYourAss/KickYourAss/LCYMyCommentTableViewCell.swift
3
1647
// // LCYMyCommentTableViewCell.swift // KickYourAss // // Created by eagle on 15/2/11. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class LCYMyCommentTableViewCell: UITableViewCell { @IBOutlet private weak var avatarImageView: UIImageView! var imagePath: String? { didSet { if let path = imagePath { avatarImageView.setImageWithURL(NSURL(string: path), placeholderImage: UIImage(named: "avatarPlaceholder")) } else { avatarImageView.image = UIImage(named: "avatarPlaceholder") } } } @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet private var starImageViews: [UIImageView]! /// 作品积分 var markCount: Double = 0 { didSet { for tinker in starImageViews { if Double(tinker.tag) > markCount { tinker.image = UIImage(named: "AboutMeHeaderEmpty") } else { tinker.image = UIImage(named: "AboutMeHeader") } } } } @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! class var identifier: String { return "LCYMyCommentTableViewCellIdentifier" } override func awakeFromNib() { super.awakeFromNib() // Initialization code avatarImageView.roundedCorner = true } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
peferron/algo
EPI/Heaps/Compute the k closest stars/swift/test.swift
1
1505
import Darwin func == (lhs: [Coordinates], rhs: [Coordinates]) -> Bool { guard lhs.count == rhs.count else { return false } for (index, element) in lhs.enumerated() { guard rhs[index] == element else { return false } } return true } let tests: [(stars: [Coordinates], k: Int, closest: [Coordinates])] = [ ( stars: [], k: 10, closest: [] ), ( stars: [ (3, 0, 0), (2, 0, 0), ], k: 10, closest: [ (3, 0, 0), (2, 0, 0), ] ), ( stars: [ (3, 0, 0), (0, 7, 0), (2, 0, 0), (5, 2, 0), (0, 4, 0), (0, 1, 1), (1, 2, 3), ], k: 1, closest: [ (0, 1, 1), ] ), ( stars: [ (3, 0, 0), (0, 7, 0), (2, 0, 0), (5, 2, 0), (0, 4, 0), (0, 1, 1), (1, 2, 3), ], k: 4, closest: [ (1, 2, 3), (3, 0, 0), (2, 0, 0), (0, 1, 1), ] ), ] for test in tests { let actual = closest(stars: test.stars, count: test.k) guard actual == test.closest else { print("For test stars \(test.stars) and k \(test.k), " + "expected k closest stars to be \(test.closest), but were \(actual)") exit(1) } }
mit
mobgeek/swift
Crie Seu Primeiro App/FiltroApp(v2) - Beta/FiltroApp(v2)Tests/FiltroApp_v2_Tests.swift
2
936
// // FiltroApp_v2_Tests.swift // FiltroApp(v2)Tests // // Created by Renan Siqueira de Souza Mesquita on 26/08/15. // Copyright (c) 2015 Mobgeek. All rights reserved. // import UIKit import XCTest class FiltroApp_v2_Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } 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. } } }
mit
whitehawks/CommoniOSViews
CommoniOSViews/Classes/UIViews/GradientView.swift
1
1712
// // GradientView.swift // Pods // // Created by Sharif Khaleel on 6/12/17. // // import Foundation import UIKit @IBDesignable public class GradientView: UIView { @IBInspectable var startColor: UIColor = .black { didSet { updateColors() }} @IBInspectable var endColor: UIColor = .white { didSet { updateColors() }} @IBInspectable var startLocation: Double = 0 { didSet { updateLocations() }} @IBInspectable var endLocation: Double = 1 { didSet { updateLocations() }} @IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }} @IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }} override public class var layerClass: AnyClass { return CAGradientLayer.self } var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } func updatePoints() { if horizontalMode { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) } else { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) } } func updateLocations() { gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] } func updateColors() { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } override public func layoutSubviews() { super.layoutSubviews() updatePoints() updateLocations() updateColors() } }
mit
ayunav/AudioKit
Tests/Tests/AKSimpleWaveGuideModel.swift
3
1753
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 11/30/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 11.0 class Instrument : AKInstrument { override init() { super.init() let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav" let audio = AKFileInput(filename: filename) let mono = AKMix(monoAudioFromStereoInput: audio) let simpleWaveGuideModel = AKSimpleWaveGuideModel(input: mono) let cutoffLine = AKLine(firstPoint: 1000.ak, secondPoint: 5000.ak, durationBetweenPoints: testDuration.ak) let frequencyLine = AKLine(firstPoint: 12.ak, secondPoint: 1000.ak, durationBetweenPoints: testDuration.ak) let feedbackLine = AKLine(firstPoint: 0.ak, secondPoint: 0.8.ak, durationBetweenPoints: testDuration.ak) simpleWaveGuideModel.cutoff = cutoffLine simpleWaveGuideModel.frequency = frequencyLine simpleWaveGuideModel.feedback = feedbackLine setAudioOutput(simpleWaveGuideModel) enableParameterLog( "Cutoff = ", parameter: simpleWaveGuideModel.cutoff, timeInterval:0.1 ) enableParameterLog( "Frequency = ", parameter: simpleWaveGuideModel.frequency, timeInterval:0.1 ) enableParameterLog( "Feedback = ", parameter: simpleWaveGuideModel.feedback, timeInterval:0.1 ) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() AKOrchestra.addInstrument(instrument) instrument.play() NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
apascual/braintree_ios
UnitTests/BTAPIClient_SwiftTests.swift
1
11418
import XCTest class BTAPIClient_SwiftTests: XCTestCase { // MARK: - Initialization func testAPIClientInitialization_withValidTokenizationKey_returnsClientWithTokenizationKey() { let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id")! XCTAssertEqual(apiClient.tokenizationKey, "development_testing_integration_merchant_id") } func testAPIClientInitialization_withInvalidTokenizationKey_returnsNil() { XCTAssertNil(BTAPIClient(authorization: "invalid")) } func testAPIClientInitialization_withEmptyTokenizationKey_returnsNil() { XCTAssertNil(BTAPIClient(authorization: "")) } func testAPIClientInitialization_withValidClientToken_returnsClientWithClientToken() { let clientToken = BTTestClientTokenFactory.token(withVersion: 2) let apiClient = BTAPIClient(authorization: clientToken!) XCTAssertEqual(apiClient?.clientToken?.originalValue, clientToken) } func testAPIClientInitialization_withVersionThreeClientToken_returnsClientWithClientToken() { let clientToken = BTTestClientTokenFactory.token(withVersion: 3) let apiClient = BTAPIClient(authorization: clientToken!) XCTAssertEqual(apiClient?.clientToken?.originalValue, clientToken) } func testAPIClientInitialization_withValidClientToken_performanceMeetsExpectations() { let clientToken = BTTestClientTokenFactory.token(withVersion: 2) self.measure() { _ = BTAPIClient(authorization: clientToken!) } } // MARK: - Copy func testCopyWithSource_whenUsingClientToken_usesSameClientToken() { let clientToken = BTTestClientTokenFactory.token(withVersion: 2) let apiClient = BTAPIClient(authorization: clientToken!) let copiedApiClient = apiClient?.copy(with: .unknown, integration: .unknown) XCTAssertEqual(copiedApiClient?.clientToken?.originalValue, clientToken) } func testCopyWithSource_whenUsingTokenizationKey_usesSameTokenizationKey() { let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id") let copiedApiClient = apiClient?.copy(with: .unknown, integration: .unknown) XCTAssertEqual(copiedApiClient?.tokenizationKey, "development_testing_integration_merchant_id") } func testCopyWithSource_setsMetadataSourceAndIntegration() { let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id") let copiedApiClient = apiClient?.copy(with: .payPalBrowser, integration: .dropIn) XCTAssertEqual(copiedApiClient?.metadata.source, .payPalBrowser) XCTAssertEqual(copiedApiClient?.metadata.integration, .dropIn) } func testCopyWithSource_copiesHTTP() { let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id") let copiedApiClient = apiClient?.copy(with: .payPalBrowser, integration: .dropIn) XCTAssertTrue(copiedApiClient !== apiClient) } // MARK: - fetchOrReturnRemoteConfiguration func testFetchOrReturnRemoteConfiguration_performsGETWithCorrectPayload() { let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id", sendAnalyticsEvent: false)! let mockHTTP = BTFakeHTTP()! mockHTTP.stubRequest("GET", toEndpoint: "/v1/configuration", respondWith: [], statusCode: 200) apiClient.configurationHTTP = mockHTTP let expectation = self.expectation(description: "Callback invoked") apiClient.fetchOrReturnRemoteConfiguration() { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/configuration") XCTAssertEqual(mockHTTP.lastRequestParameters?["configVersion"] as? String, "3") expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) } // MARK: - fetchPaymentMethods func testFetchPaymentMethods_performsGETWithCorrectParameter() { let apiClient = BTAPIClient(authorization: BTValidTestClientToken, sendAnalyticsEvent: false)! let mockHTTP = BTFakeHTTP()! mockHTTP.stubRequest("GET", toEndpoint: "/client_api/v1/payment_methods", respondWith: [], statusCode: 200) apiClient.http = mockHTTP var expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces() { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "false") XCTAssertEqual(mockHTTP.lastRequestParameters!["session_id"] as? String, apiClient.metadata.sessionId) expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces(true) { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "true") expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces(false) { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "false") expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testFetchPaymentMethods_returnsPaymentMethodNonces() { let apiClient = BTAPIClient(authorization: BTValidTestClientToken, sendAnalyticsEvent: false)! let stubHTTP = BTFakeHTTP()! let stubbedResponse = [ "paymentMethods": [ [ "default" : true, "description": "ending in 05", "details": [ "cardType": "American Express", "lastTwo": "05" ], "nonce": "fake-nonce", "type": "CreditCard" ], [ "default" : false, "description": "jane.doe@example.com", "details": [], "nonce": "fake-nonce", "type": "PayPalAccount" ] ] ] stubHTTP.stubRequest("GET", toEndpoint: "/client_api/v1/payment_methods", respondWith: stubbedResponse, statusCode: 200) apiClient.http = stubHTTP let expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces() { (paymentMethodNonces, error) in guard let paymentMethodNonces = paymentMethodNonces else { XCTFail() return } XCTAssertNil(error) XCTAssertEqual(paymentMethodNonces.count, 2) guard let cardNonce = paymentMethodNonces[0] as? BTCardNonce else { XCTFail() return } guard let paypalNonce = paymentMethodNonces[1] as? BTPayPalAccountNonce else { XCTFail() return } XCTAssertEqual(cardNonce.nonce, "fake-nonce") XCTAssertEqual(cardNonce.localizedDescription, "ending in 05") XCTAssertEqual(cardNonce.lastTwo, "05") XCTAssertTrue(cardNonce.cardNetwork == BTCardNetwork.AMEX) XCTAssertTrue(cardNonce.isDefault) XCTAssertEqual(paypalNonce.nonce, "fake-nonce") XCTAssertEqual(paypalNonce.localizedDescription, "jane.doe@example.com") XCTAssertFalse(paypalNonce.isDefault) expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testFetchPaymentMethods_withTokenizationKey_returnsError() { let apiClient = BTAPIClient(authorization: "development_tokenization_key", sendAnalyticsEvent: false)! let expectation = self.expectation(description: "Error returned") apiClient.fetchPaymentMethodNonces() { (paymentMethodNonces, error) -> Void in XCTAssertNil(paymentMethodNonces); guard let error = error as? NSError else {return} XCTAssertEqual(error._domain, BTAPIClientErrorDomain); XCTAssertEqual(error._code, BTAPIClientErrorType.notAuthorized.rawValue); expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) } // MARK: - V3 Client Token func testFetchPaymentMethods_performsGETWithCorrectParameter_withVersionThreeClientToken() { let clientToken = BTTestClientTokenFactory.token(withVersion: 3) let apiClient = BTAPIClient(authorization: clientToken!, sendAnalyticsEvent: false)! let mockHTTP = BTFakeHTTP()! mockHTTP.stubRequest("GET", toEndpoint: "/client_api/v1/payment_methods", respondWith: [], statusCode: 200) apiClient.http = mockHTTP let mockConfigurationHTTP = BTFakeHTTP()! mockConfigurationHTTP.stubRequest("GET", toEndpoint: "/client_api/v1/configuration", respondWith: [], statusCode: 200) apiClient.configurationHTTP = mockConfigurationHTTP XCTAssertEqual((apiClient.clientToken!.json["version"] as! BTJSON).asIntegerOrZero(), 3) var expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces() { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "false") XCTAssertEqual(mockHTTP.lastRequestParameters!["session_id"] as? String, apiClient.metadata.sessionId) expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces(true) { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "true") expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) expectation = self.expectation(description: "Callback invoked") apiClient.fetchPaymentMethodNonces(false) { _,_ in XCTAssertEqual(mockHTTP.lastRequestEndpoint, "v1/payment_methods") XCTAssertEqual(mockHTTP.lastRequestParameters!["default_first"] as? String, "false") expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) } // MARK: - Analytics func testAnalyticsService_byDefault_isASingleton() { let firstAPIClient = BTAPIClient(authorization: "development_testing_integration_merchant_id")! let secondAPIClient = BTAPIClient(authorization: "development_testing_integration_merchant_id")! XCTAssertTrue(firstAPIClient.analyticsService === secondAPIClient.analyticsService) } }
mit
cantinac/JSONCodable
JSONCodable/JSONCodable.swift
1
620
// // JSONCodable.swift // JSONCodable // // Created by Matthew Cheok on 17/7/15. // Copyright © 2015 matthewcheok. All rights reserved. // // convenience protocol public protocol JSONTranscodable: JSONEncodable, JSONDecodable {} // JSONCompatible - valid types in JSON public protocol JSONCompatible: JSONEncodable {} extension String: JSONCompatible {} extension Double: JSONCompatible {} extension Float: JSONCompatible {} extension Bool: JSONCompatible {} extension Int: JSONCompatible {} extension JSONCompatible { public func toJSON() throws -> AnyObject { return self as! AnyObject } }
mit
hardikdevios/HKKit
Pod/Classes/HKExtensions/UIKit+Extensions/UIButton+Extension.swift
1
1487
// // UIButton+Extension.swift // HKCustomization // // Created by Hardik on 10/18/15. // Copyright © 2015 . All rights reserved. // import UIKit extension UIButton{ public func hk_toggleOnOff()->Void{ self.isSelected = !self.isSelected; } public func hk_setDisableWithAlpha(_ isDisable:Bool){ if isDisable { self.isEnabled = false self.alpha = 0.5 }else{ self.isEnabled = true self.alpha = 1.0 } } public func hk_appleBootStrapTheme(_ color:UIColor = HKConstant.sharedInstance.main_color){ self.layer.borderWidth = 1 self.layer.cornerRadius = 2 self.layer.borderColor = color.cgColor self.setTitleColor(color, for: UIControl.State()) } public func hk_setAttributeString(_ mainString:String,attributeString:String,attributes:[NSAttributedString.Key:Any]){ let result = hk_getAttributeString(mainString, attributeString: attributeString, attributes: attributes) self.setAttributedTitle(result, for: .normal) } public func hk_setAttributesString(_ mainString:String,attributeStrings:[String],total_attributes:[[NSAttributedString.Key:Any]]) { let result = hk_getMultipleAttributesString(mainString, attributeStrings: attributeStrings, total_attributes: total_attributes) self.setAttributedTitle(result, for: .normal) } }
mit
running-LM/SwiftDictModel
iOS Example/iOS Example/ViewController.swift
1
1945
// // ViewController.swift // iOS Example // // Created by 刘敏 on 15/2/18. // Copyright (c) 2015年 joyios. All rights reserved. // import UIKit import SwiftDictModel class ViewController: UIViewController { let manager = DictModelManager.sharedManager override func viewDidLoad() { super.viewDidLoad() if let json = serializationJSON("Person.json") as? NSDictionary { var stu: Student? = manager.objectWithDictionary(json, cls: Student.self) as? Student println(manager.objectDictionary(stu!)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { testPerformence() } func testPerformence() { var json: NSDictionary = serializationJSON("Person.json") as! NSDictionary performenceRunFunction(10000) { autoreleasepool({ () -> () in var stu: Student? = self.manager.objectWithDictionary(json, cls: Student.self) as? Student }) } } func performenceRunFunction(var loopTimes:Int, testFunc: ()->()) { var start = CFAbsoluteTimeGetCurrent() println("测试开始...") for _ in 0...loopTimes { testFunc() } var end = CFAbsoluteTimeGetCurrent() println("运行 \(loopTimes) 次,耗时 \(end - start)") } func serializationJSON(filename: String) -> AnyObject? { if let fileURL = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) { if let data = NSData(contentsOfURL: fileURL) { return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) } } return nil } }
mit
erkie/ApiModel
Tests/ApiManagerResponseTests.swift
1
4726
// // ApiResponseTests.swift // ApiModel // // Created by Craig Heneveld on 1/14/16. // // import XCTest import ApiModel import Alamofire import OHHTTPStubs import RealmSwift class ApiManagerResponseTests: XCTestCase { var timeout: TimeInterval = 10 var testRealm: Realm! var host = "http://you-dont-party.com" override func setUp() { super.setUp() Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name testRealm = try! Realm() ApiSingleton.setInstance(ApiManager(config: ApiConfig(host: self.host))) } override func tearDown() { super.tearDown() try! testRealm.write { self.testRealm.deleteAll() } OHHTTPStubs.removeAllStubs() } func testNotFoundResponse() { var theResponse: ApiModelResponse<Post>? let readyExpectation = self.expectation(description: "ready") stub(condition: {_ in true}) { request in OHHTTPStubsResponse( data:"File not found".data(using: String.Encoding.utf8)!, statusCode: 404, headers: nil ) } Api<Post>.get("/v1/posts.json") { response in XCTAssertEqual(response.rawResponse!.status!, 404, "A response should have a status of 404") XCTAssertEqual(String(describing: response.rawResponse!.error!), "invalidRequest(code: 404)") XCTAssertTrue(response.rawResponse!.isInvalid, "A response status of 404 should be invalid") theResponse = response readyExpectation.fulfill() OHHTTPStubs.removeAllStubs() } waitForExpectations(timeout: self.timeout) { err in // By the time we reach this code, the while loop has exited // so the response has arrived or the test has timed out XCTAssertNotNil(theResponse, "Received data should not be nil") } } func testServerErrorResponse() { var theResponse: ApiModelResponse<Post>? let readyExpectation = self.expectation(description: "ready") stub(condition: {_ in true}) { request in OHHTTPStubsResponse(data :"Something went wrong!".data(using: String.Encoding.utf8)!, statusCode: 500, headers: nil ) } Api<Post>.get("/v1/posts.json") { response in XCTAssertEqual(response.rawResponse!.status!, 500, "A response should have a status of 500") XCTAssertEqual(String(describing: response.rawResponse!.error!), "badRequest(code: 500)") // XCTAssertTrue(response.rawResponse!.isInvalid, "A response status of 500 should be invalid") theResponse = response readyExpectation.fulfill() OHHTTPStubs.removeAllStubs() } waitForExpectations(timeout: self.timeout) { err in // By the time we reach this code, the while loop has exited // so the response has arrived or the test has timed out XCTAssertNotNil(theResponse, "Received data should not be nil") } } func testSessionConfig() { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 1 // seconds configuration.timeoutIntervalForResource = 1 ApiSingleton.setInstance(ApiManager(config: ApiConfig(host: self.host, urlSessionConfig:configuration))) let readyExpectation = expectation(description: "ready") stub(condition: { _ in true }) { request in OHHTTPStubsResponse( data: "Something went wrong!".data(using: String.Encoding.utf8)!, statusCode: 500, headers: nil ).requestTime(2.0, responseTime: 2.0) } Api<Post>.get("/v1/posts.json") { response in // -1001 indicates a timeout occured which is what's expected XCTAssertNil(response.rawResponse?.status, "We currently can't test for raw alamofire response codes so just checking if status is nil. Which failed.") readyExpectation.fulfill() OHHTTPStubs.removeAllStubs() } waitForExpectations(timeout: self.timeout) { err in // By the time we reach this code, the while loop has exited // so the response has arrived or the test has timed out XCTAssertNil(err, "Timeout occured") } } }
mit
PaulWoodIII/tipski
TipskyiOS/Tipski/AddEmojiViewController.swift
1
4020
// // AddEmojiViewController.swift // Tipski // // Created by Paul Wood on 9/15/16. // Copyright © 2016 Paul Wood. All rights reserved. // import Foundation import UIKit protocol AddEmojiDelegate : class { func didAddEmoji(tipEmoji: TipEmoji) } class AddEmojiViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate { weak var delegate : AddEmojiDelegate? @IBOutlet weak var emojiTextField: UITextField! @IBOutlet weak var tipTextField: UITextField! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var collectionView: UICollectionView! var filteredEmojis : [Emoji] = Emoji.allEmojis var newItem = TipEmoji(emoji: "",tipAmount: 0) override func viewDidLoad() { super.viewDidLoad() collectionView.isHidden = true Appearance.createWellFromView(view: containerView) Appearance.createInput(textField: emojiTextField) Appearance.createInput(textField: tipTextField) Appearance.createSubmitButton(button: addButton) } @IBAction func emojiTextDidChange(_ textField: UITextField) { if let text = textField.text , text != "", !collectionView.isHidden { filteredEmojis = Emoji.allEmojis.filter() { return ($0.fts as NSString).localizedCaseInsensitiveContains(text) } print(filteredEmojis) } collectionView.reloadData() if let newText = emojiTextField.text, newText.isEmoji { newItem.emoji = newText } } @IBAction func tipAmountDidChange(_ sender: AnyObject) { if let newTip = tipTextField.text, let tipDouble = Double(newTip){ newItem.tipAmount = tipDouble } else { newItem.tipAmount = Double(0) } } @IBAction func addButtonPressed(_ sender: AnyObject) { if newItem.isValid() { delegate?.didAddEmoji(tipEmoji: newItem) } else { //Display Error } } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return filteredEmojis.count } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCollectionViewCell", for: indexPath) print(cell.subviews) let label = cell.viewWithTag(1) as! UILabel label.text = filteredEmojis[indexPath.row].char return cell } // func textFieldDidBeginEditing(_ textField: UITextField) { // became first responder if textField == emojiTextField { //display the UICollectionView collectionView.isHidden = false } } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason){ if textField == emojiTextField { collectionView.isHidden = true } } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == emojiTextField { emojiTextDidChange(textField) } return true } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){ let char = filteredEmojis[indexPath.row].char if char.isEmoji { emojiTextField.text = char newItem.emoji = char } else { //display error in emoji text field } emojiTextField.resignFirstResponder() } }
mit