repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
AjayOdedara/CoreKitTest
refs/heads/master
CoreKit/Pods/SwiftDate/Sources/SwiftDate/TimeZoneName.swift
apache-2.0
16
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// MARK: - TimeZoneName Shortcut /// This enum allows you set a valid timezone using swift's type safe support public enum TimeZoneName: String { /// Return a valid TimeZone instance from an enum public var timeZone: TimeZone { switch self { case .current: return TimeZone.current case .currentAutoUpdating: return TimeZone.autoupdatingCurrent default: return TimeZone(identifier: self.rawValue)! } } /// Return a `TimeZone` instance with a fixed number of seconds from GMT zone /// /// - parameter seconds: seconds from GMT /// /// - returns: a new `TimeZone` instance public static func secondsFromGMT(seconds: Int) -> TimeZone? { return TimeZone(secondsFromGMT: seconds) } case current = "Current" case currentAutoUpdating = "CurrentAutoUpdating" case africaAbidjan = "Africa/Abidjan" case africaAccra = "Africa/Accra" case africaAddisAbaba = "Africa/Addis_Ababa" case africaAlgiers = "Africa/Algiers" case africaAsmara = "Africa/Asmara" case africaBamako = "Africa/Bamako" case africaBangui = "Africa/Bangui" case africaBanjul = "Africa/Banjul" case africaBissau = "Africa/Bissau" case africaBlantyre = "Africa/Blantyre" case africaBrazzaville = "Africa/Brazzaville" case africaBujumbura = "Africa/Bujumbura" case africaCairo = "Africa/Cairo" case africaCasablanca = "Africa/Casablanca" case africaCeuta = "Africa/Ceuta" case africaConakry = "Africa/Conakry" case africaDakar = "Africa/Dakar" case africaDarEsSalaam = "Africa/Dar_es_Salaam" case africaDjibouti = "Africa/Djibouti" case africaDouala = "Africa/Douala" case africaElAaiun = "Africa/El_Aaiun" case africaFreetown = "Africa/Freetown" case africaGaborone = "Africa/Gaborone" case africaHarare = "Africa/Harare" case africaJohannesburg = "Africa/Johannesburg" case africaJuba = "Africa/Juba" case africaKampala = "Africa/Kampala" case africaKhartoum = "Africa/Khartoum" case fricaKigali = "Africa/Kigali" case africaKinshasa = "Africa/Kinshasa" case africaLagos = "Africa/Lagos" case africaLibreville = "Africa/Libreville" case africaLome = "Africa/Lome" case africaLuanda = "Africa/Luanda" case africaLubumbashi = "Africa/Lubumbashi" case africaLusaka = "Africa/Lusaka" case africaMalabo = "Africa/Malabo" case africaMaputo = "Africa/Maputo" case africaMaseru = "Africa/Maseru" case africaMbabane = "Africa/Mbabane" case africaMogadishu = "Africa/Mogadishu" case africaMonrovia = "Africa/Monrovia" case africaNairobi = "Africa/Nairobi" case africaNdjamena = "Africa/Ndjamena" case africaNiamey = "Africa/Niamey" case africaNouakchott = "Africa/Nouakchott" case africaOuagadougou = "Africa/Ouagadougou" case africaPortoNovo = "Africa/Porto-Novo" case africaSaoTome = "Africa/Sao_Tome" case africaTripoli = "Africa/Tripoli" case africaTunis = "Africa/Tunis" case africaWindhoek = "Africa/Windhoek" case americaAdak = "America/Adak" case americaAnchorage = "America/Anchorage" case americaAnguilla = "America/Anguilla" case americaAntigua = "America/Antigua" case americaAraguaina = "America/Araguaina" case americaArgentinaBuenosAires = "America/Argentina/Buenos_Aires" case americaArgentinaCatamarca = "America/Argentina/Catamarca" case americaArgentinaCordoba = "America/Argentina/Cordoba" case americaArgentinaJujuy = "America/Argentina/Jujuy" case americaArgentinaLaRioja = "America/Argentina/La_Rioja" case americaArgentinaMendoza = "America/Argentina/Mendoza" case americaArgentinaRioGallegos = "America/Argentina/Rio_Gallegos" case americaArgentinaSalta = "America/Argentina/Salta" case americaArgentinaSanJuan = "America/Argentina/San_Juan" case americaArgentinaSanLuis = "America/Argentina/San_Luis" case americaArgentinaTucuman = "America/Argentina/Tucuman" case americaArgentinaUshuaia = "America/Argentina/Ushuaia" case americaAruba = "America/Aruba" case americaAsuncion = "America/Asuncion" case americaAtikokan = "America/Atikokan" case americaBahia = "America/Bahia" case americaBahiaBanderas = "America/Bahia_Banderas" case americaBarbados = "America/Barbados" case americaBelem = "America/Belem" case americaBelize = "America/Belize" case americaBlancSablon = "America/Blanc-Sablon" case americaBoaVista = "America/Boa_Vista" case americaBogota = "America/Bogota" case americaBoise = "America/Boise" case americaCambridgeBay = "America/Cambridge_Bay" case americaCampoGrande = "America/Campo_Grande" case americaCancun = "America/Cancun" case americaCaracas = "America/Caracas" case americaCayenne = "America/Cayenne" case americaCayman = "America/Cayman" case americaChicago = "America/Chicago" case americaChihuahua = "America/Chihuahua" case americaCostaRica = "America/Costa_Rica" case americaCreston = "America/Creston" case americaCuiaba = "America/Cuiaba" case americaCuracao = "America/Curacao" case americaDanmarkshavn = "America/Danmarkshavn" case americaDawson = "America/Dawson" case americaDawsonCreek = "America/Dawson_Creek" case americaDenver = "America/Denver" case americaDetroit = "America/Detroit" case americaDominica = "America/Dominica" case americaEdmonton = "America/Edmonton" case americaEirunepe = "America/Eirunepe" case americaElSalvador = "America/El_Salvador" case americaFortNelson = "America/Fort_Nelson" case americaFortaleza = "America/Fortaleza" case americaGlaceBay = "America/Glace_Bay" case americaGodthab = "America/Godthab" case americaGooseBay = "America/Goose_Bay" case americaGrandTurk = "America/Grand_Turk" case americaGrenada = "America/Grenada" case americaGuadeloupe = "America/Guadeloupe" case americaGuatemala = "America/Guatemala" case americaGuayaquil = "America/Guayaquil" case americaGuyana = "America/Guyana" case americaHalifax = "America/Halifax" case americaHavana = "America/Havana" case americaHermosillo = "America/Hermosillo" case americaIndianaIndianapolis = "America/Indiana/Indianapolis" case americaIndianaKnox = "America/Indiana/Knox" case americaIndianaMarengo = "America/Indiana/Marengo" case americaIndianaPetersburg = "America/Indiana/Petersburg" case americaIndianaTellCity = "America/Indiana/Tell_City" case americaIndianaVevay = "America/Indiana/Vevay" case americaIndianaVincennes = "America/Indiana/Vincennes" case americaIndianaWinamac = "America/Indiana/Winamac" case americaInuvik = "America/Inuvik" case americaIqaluit = "America/Iqaluit" case americaJamaica = "America/Jamaica" case americaJuneau = "America/Juneau" case americaKentuckyLouisville = "America/Kentucky/Louisville" case americaKentuckyMonticello = "America/Kentucky/Monticello" case americaKralendijk = "America/Kralendijk" case americaLaPaz = "America/La_Paz" case americaLima = "America/Lima" case americaLosAngeles = "America/Los_Angeles" case americaLowerPrinces = "America/Lower_Princes" case americaMaceio = "America/Maceio" case americaManagua = "America/Managua" case americaManaus = "America/Manaus" case americaMarigot = "America/Marigot" case americaMartinique = "America/Martinique" case americaMatamoros = "America/Matamoros" case americaMazatlan = "America/Mazatlan" case americaMenominee = "America/Menominee" case americaMerida = "America/Merida" case americaMetlakatla = "America/Metlakatla" case americaMexicoCity = "America/Mexico_City" case americaMiquelon = "America/Miquelon" case americaMoncton = "America/Moncton" case americaMonterrey = "America/Monterrey" case americaMontevideo = "America/Montevideo" case americaMontreal = "America/Montreal" case americaMontserrat = "America/Montserrat" case americaNassau = "America/Nassau" case americaNewYork = "America/New_York" case americaNipigon = "America/Nipigon" case americaNome = "America/Nome" case americaNoronha = "America/Noronha" case americaNorthDakotaBeulah = "America/North_Dakota/Beulah" case americaNorthDakotaCenter = "America/North_Dakota/Center" case americaNorthDakotaNewSalem = "America/North_Dakota/New_Salem" case americaOjinaga = "America/Ojinaga" case americaPanama = "America/Panama" case americaPangnirtung = "America/Pangnirtung" case americaParamaribo = "America/Paramaribo" case americaPhoenix = "America/Phoenix" case americaPortAuPrince = "America/Port-au-Prince" case americaPortOfSpain = "America/Port_of_Spain" case americaPortoVelho = "America/Porto_Velho" case americaPuertoRico = "America/Puerto_Rico" case americaRainyRiver = "America/Rainy_River" case americaRankinInlet = "America/Rankin_Inlet" case americaRecife = "America/Recife" case americaRegina = "America/Regina" case americaResolute = "America/Resolute" case americaRioBranco = "America/Rio_Branco" case americaSantaIsabel = "America/Santa_Isabel" case americaSantarem = "America/Santarem" case americaSantiago = "America/Santiago" case americaSantoDomingo = "America/Santo_Domingo" case americaSaoPaulo = "America/Sao_Paulo" case americaScoresbysund = "America/Scoresbysund" case americaShiprock = "America/Shiprock" case americaSitka = "America/Sitka" case americaStBarthelemy = "America/St_Barthelemy" case americaStJohns = "America/St_Johns" case americaStKitts = "America/St_Kitts" case americaStLucia = "America/St_Lucia" case americaStThomas = "America/St_Thomas" case americaStVincent = "America/St_Vincent" case americaSwiftCurrent = "America/Swift_Current" case americaTegucigalpa = "America/Tegucigalpa" case americaThule = "America/Thule" case americaThunderBay = "America/Thunder_Bay" case americaTijuana = "America/Tijuana" case americaToronto = "America/Toronto" case americaTortola = "America/Tortola" case americaVancouver = "America/Vancouver" case americaWhitehorse = "America/Whitehorse" case americaWinnipeg = "America/Winnipeg" case americaYakutat = "America/Yakutat" case americaYellowknife = "America/Yellowknife" case antarcticaCasey = "Antarctica/Casey" case antarcticaDavis = "Antarctica/Davis" case antarcticaDumontdurville = "Antarctica/DumontDUrville" case antarcticaMacquarie = "Antarctica/Macquarie" case antarcticaMawson = "Antarctica/Mawson" case antarcticaMcmurdo = "Antarctica/McMurdo" case antarcticaPalmer = "Antarctica/Palmer" case antarcticaRothera = "Antarctica/Rothera" case antarcticaSouthPole = "Antarctica/South_Pole" case antarcticaSyowa = "Antarctica/Syowa" case antarcticaTroll = "Antarctica/Troll" case antarcticaVostok = "Antarctica/Vostok" case arcticLongyearbyen = "Arctic/Longyearbyen" case asiaAden = "Asia/Aden" case asiaAlmaty = "Asia/Almaty" case asiaAmman = "Asia/Amman" case asiaAnadyr = "Asia/Anadyr" case asiaAqtau = "Asia/Aqtau" case asiaAqtobe = "Asia/Aqtobe" case asiaAshgabat = "Asia/Ashgabat" case asiaBaghdad = "Asia/Baghdad" case asiaBahrain = "Asia/Bahrain" case asiaBaku = "Asia/Baku" case asiaBangkok = "Asia/Bangkok" case asiaBeirut = "Asia/Beirut" case asiaBishkek = "Asia/Bishkek" case asiaBrunei = "Asia/Brunei" case asiaChita = "Asia/Chita" case asiaChoibalsan = "Asia/Choibalsan" case asiaChongqing = "Asia/Chongqing" case asiaColombo = "Asia/Colombo" case asiaDamascus = "Asia/Damascus" case asiaDhaka = "Asia/Dhaka" case asiaDili = "Asia/Dili" case asiaDubai = "Asia/Dubai" case asiaDushanbe = "Asia/Dushanbe" case asiaGaza = "Asia/Gaza" case asiaHarbin = "Asia/Harbin" case asiaHebron = "Asia/Hebron" case asiaHoChiMinh = "Asia/Ho_Chi_Minh" case asiaHongKong = "Asia/Hong_Kong" case asiaHovd = "Asia/Hovd" case asiaIrkutsk = "Asia/Irkutsk" case asiaJakarta = "Asia/Jakarta" case asiaJayapura = "Asia/Jayapura" case asiaJerusalem = "Asia/Jerusalem" case asiaKabul = "Asia/Kabul" case asiaKamchatka = "Asia/Kamchatka" case asiaKarachi = "Asia/Karachi" case asiaKashgar = "Asia/Kashgar" case asiaKathmandu = "Asia/Kathmandu" case asiaKatmandu = "Asia/Katmandu" case asiaKhandyga = "Asia/Khandyga" case asiaKolkata = "Asia/Kolkata" case asiaKrasnoyarsk = "Asia/Krasnoyarsk" case asiaKualaLumpur = "Asia/Kuala_Lumpur" case asiaKuching = "Asia/Kuching" case asiaKuwait = "Asia/Kuwait" case asiaMacau = "Asia/Macau" case asiaMagadan = "Asia/Magadan" case asiaMakassar = "Asia/Makassar" case asiaManila = "Asia/Manila" case asiaMuscat = "Asia/Muscat" case asiaNicosia = "Asia/Nicosia" case asiaNovokuznetsk = "Asia/Novokuznetsk" case asiaNovosibirsk = "Asia/Novosibirsk" case asiaOmsk = "Asia/Omsk" case asiaOral = "Asia/Oral" case asiaPhnomPenh = "Asia/Phnom_Penh" case asiaPontianak = "Asia/Pontianak" case asiaPyongyang = "Asia/Pyongyang" case asiaQatar = "Asia/Qatar" case asiaQyzylorda = "Asia/Qyzylorda" case asiaRangoon = "Asia/Rangoon" case asiaRiyadh = "Asia/Riyadh" case asiaSakhalin = "Asia/Sakhalin" case asiaSamarkand = "Asia/Samarkand" case asiaSeoul = "Asia/Seoul" case asiaShanghai = "Asia/Shanghai" case asiaSingapore = "Asia/Singapore" case asiaSrednekolymsk = "Asia/Srednekolymsk" case asiaTaipei = "Asia/Taipei" case asiaTashkent = "Asia/Tashkent" case asiaTbilisi = "Asia/Tbilisi" case asiaTehran = "Asia/Tehran" case asiaThimphu = "Asia/Thimphu" case asiaTokyo = "Asia/Tokyo" case asiaUlaanbaatar = "Asia/Ulaanbaatar" case asiaUrumqi = "Asia/Urumqi" case asiaUstNera = "Asia/Ust-Nera" case asiaVientiane = "Asia/Vientiane" case asiaVladivostok = "Asia/Vladivostok" case asiaYakutsk = "Asia/Yakutsk" case asiaYekaterinburg = "Asia/Yekaterinburg" case asiaYerevan = "Asia/Yerevan" case atlanticAzores = "Atlantic/Azores" case atlanticBermuda = "Atlantic/Bermuda" case atlanticCanary = "Atlantic/Canary" case atlanticCapeVerde = "Atlantic/Cape_Verde" case atlanticFaroe = "Atlantic/Faroe" case atlanticMadeira = "Atlantic/Madeira" case atlanticReykjavik = "Atlantic/Reykjavik" case atlanticSouthGeorgia = "Atlantic/South_Georgia" case atlanticStHelena = "Atlantic/St_Helena" case atlanticStanley = "Atlantic/Stanley" case australiaAdelaide = "Australia/Adelaide" case australiaBrisbane = "Australia/Brisbane" case australiaBrokenHill = "Australia/Broken_Hill" case australiaCurrie = "Australia/Currie" case australiaDarwin = "Australia/Darwin" case australiaEucla = "Australia/Eucla" case australiaHobart = "Australia/Hobart" case australiaLindeman = "Australia/Lindeman" case australiaLordHowe = "Australia/Lord_Howe" case australiaMelbourne = "Australia/Melbourne" case australiaPerth = "Australia/Perth" case australiaSydney = "Australia/Sydney" case europeAmsterdam = "Europe/Amsterdam" case europeAndorra = "Europe/Andorra" case europeAthens = "Europe/Athens" case europeBelgrade = "Europe/Belgrade" case europeBerlin = "Europe/Berlin" case europeBratislava = "Europe/Bratislava" case europeBrussels = "Europe/Brussels" case europeBucharest = "Europe/Bucharest" case europeBudapest = "Europe/Budapest" case europeBusingen = "Europe/Busingen" case europeChisinau = "Europe/Chisinau" case europeCopenhagen = "Europe/Copenhagen" case europeDublin = "Europe/Dublin" case europeGibraltar = "Europe/Gibraltar" case europeGuernsey = "Europe/Guernsey" case europeHelsinki = "Europe/Helsinki" case europeIsleOfMan = "Europe/Isle_of_Man" case europeIstanbul = "Europe/Istanbul" case europeJersey = "Europe/Jersey" case europeKaliningrad = "Europe/Kaliningrad" case europeKiev = "Europe/Kiev" case europeLisbon = "Europe/Lisbon" case europeLjubljana = "Europe/Ljubljana" case europeLondon = "Europe/London" case europeLuxembourg = "Europe/Luxembourg" case europeMadrid = "Europe/Madrid" case europeMalta = "Europe/Malta" case europeMariehamn = "Europe/Mariehamn" case europeMinsk = "Europe/Minsk" case europeMonaco = "Europe/Monaco" case europeMoscow = "Europe/Moscow" case europeOslo = "Europe/Oslo" case europeParis = "Europe/Paris" case europePodgorica = "Europe/Podgorica" case europePrague = "Europe/Prague" case europeRiga = "Europe/Riga" case europeRome = "Europe/Rome" case europeSamara = "Europe/Samara" case europeSanMarino = "Europe/San_Marino" case europeSarajevo = "Europe/Sarajevo" case europeSimferopol = "Europe/Simferopol" case europeSkopje = "Europe/Skopje" case europeSofia = "Europe/Sofia" case europeStockholm = "Europe/Stockholm" case europeTallinn = "Europe/Tallinn" case europeTirane = "Europe/Tirane" case europeUzhgorod = "Europe/Uzhgorod" case europeVaduz = "Europe/Vaduz" case europeVatican = "Europe/Vatican" case europeVienna = "Europe/Vienna" case europeVilnius = "Europe/Vilnius" case europeVolgograd = "Europe/Volgograd" case europeWarsaw = "Europe/Warsaw" case europeZagreb = "Europe/Zagreb" case europeZaporozhye = "Europe/Zaporozhye" case europeZurich = "Europe/Zurich" case gmt = "GMT" case IndianAntananarivo = "Indian/Antananarivo" case indianChagos = "Indian/Chagos" case indianChristmas = "Indian/Christmas" case indianCocos = "Indian/Cocos" case indianComoro = "Indian/Comoro" case indianKerguelen = "Indian/Kerguelen" case indianMahe = "Indian/Mahe" case indianMaldives = "Indian/Maldives" case indianMauritius = "Indian/Mauritius" case indianMayotte = "Indian/Mayotte" case indianReunion = "Indian/Reunion" case pacificApia = "Pacific/Apia" case pacificAuckland = "Pacific/Auckland" case pacificBougainville = "Pacific/Bougainville" case pacificChatham = "Pacific/Chatham" case pacificChuuk = "Pacific/Chuuk" case pacificEaster = "Pacific/Easter" case pacificEfate = "Pacific/Efate" case pacificEnderbury = "Pacific/Enderbury" case pacificFakaofo = "Pacific/Fakaofo" case pacificFiji = "Pacific/Fiji" case pacificFunafuti = "Pacific/Funafuti" case pacificGalapagos = "Pacific/Galapagos" case pacificGambier = "Pacific/Gambier" case pacificGuadalcanal = "Pacific/Guadalcanal" case pacificGuam = "Pacific/Guam" case pacificHonolulu = "Pacific/Honolulu" case pacificJohnston = "Pacific/Johnston" case pacificKiritimati = "Pacific/Kiritimati" case pacificKosrae = "Pacific/Kosrae" case pacificKwajalein = "Pacific/Kwajalein" case pacificMajuro = "Pacific/Majuro" case pacificMarquesas = "Pacific/Marquesas" case pacificMidway = "Pacific/Midway" case pacificNauru = "Pacific/Nauru" case pacificNiue = "Pacific/Niue" case pacificNorfolk = "Pacific/Norfolk" case pacificNoumea = "Pacific/Noumea" case pacificPagoPago = "Pacific/Pago_Pago" case pacificPalau = "Pacific/Palau" case pacificPitcairn = "Pacific/Pitcairn" case pacificPohnpei = "Pacific/Pohnpei" case pacificPonape = "Pacific/Ponape" case pacificPortMoresby = "Pacific/Port_Moresby" case pacificRarotonga = "Pacific/Rarotonga" case pacificSaipan = "Pacific/Saipan" case pacificTahiti = "Pacific/Tahiti" case pacificTarawa = "Pacific/Tarawa" case pacificTongatapu = "Pacific/Tongatapu" case pacificTruk = "Pacific/Truk" case pacificWake = "Pacific/Wake" case pacificWallis = "Pacific/Wallis" }
80ca255ce70eb76277f93e33d5a2d9d7
40.363071
121
0.776446
false
false
false
false
dduan/swift
refs/heads/master
stdlib/public/core/Map.swift
apache-2.0
1
//===--- Map.swift - Lazily map over a Sequence ---------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// The `IteratorProtocol` used by `MapSequence` and `MapCollection`. /// Produces each element by passing the output of the `Base` /// `IteratorProtocol` through a transform function returning `Element`. public struct LazyMapIterator< Base : IteratorProtocol, Element > : IteratorProtocol, Sequence { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> Element? { return _base.next().map(_transform) } public var base: Base { return _base } internal var _base: Base internal let _transform: (Base.Element) -> Element } /// A `Sequence` whose elements consist of those in a `Base` /// `Sequence` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. public struct LazyMapSequence<Base : Sequence, Element> : LazySequenceProtocol { public typealias Elements = LazyMapSequence /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> { return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform) } /// Returns a value less than or equal to the number of elements in /// `self`, **nondestructively**. /// /// - Complexity: O(N). public var underestimatedCount: Int { return _base.underestimatedCount } /// Create an instance with elements `transform(x)` for each element /// `x` of base. internal init(_base: Base, transform: (Base.Iterator.Element) -> Element) { self._base = _base self._transform = transform } internal var _base: Base internal let _transform: (Base.Iterator.Element) -> Element } //===--- Collections ------------------------------------------------------===// /// A `Collection` whose elements consist of those in a `Base` /// `Collection` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. public struct LazyMapCollection<Base : Collection, Element> : LazyCollectionProtocol { // FIXME: Should be inferrable. public typealias Index = Base.Index public var startIndex: Base.Index { return _base.startIndex } public var endIndex: Base.Index { return _base.endIndex } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Base.Index) -> Element { return _transform(_base[position]) } /// Returns `true` iff `self` is empty. public var isEmpty: Bool { return _base.isEmpty } public var first: Element? { return _base.first.map(_transform) } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> { return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform) } public var underestimatedCount: Int { return _base.underestimatedCount } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; /// O(N) otherwise. public var count: Base.Index.Distance { return _base.count } /// Create an instance with elements `transform(x)` for each element /// `x` of base. internal init(_base: Base, transform: (Base.Iterator.Element) -> Element) { self._base = _base self._transform = transform } internal var _base: Base internal let _transform: (Base.Iterator.Element) -> Element } //===--- Support for s.lazy -----------------------------------------------===// extension LazySequenceProtocol { /// Returns a `LazyMapSequence` over this `Sequence`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @warn_unused_result public func map<U>( transform: (Elements.Iterator.Element) -> U ) -> LazyMapSequence<Self.Elements, U> { return LazyMapSequence(_base: self.elements, transform: transform) } } extension LazyCollectionProtocol { /// Returns a `LazyMapCollection` over this `Collection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @warn_unused_result public func map<U>( transform: (Elements.Iterator.Element) -> U ) -> LazyMapCollection<Self.Elements, U> { return LazyMapCollection(_base: self.elements, transform: transform) } } @available(*, unavailable, renamed: "LazyMapIterator") public struct LazyMapGenerator<Base : IteratorProtocol, Element> {} extension LazyMapSequence { @available(*, unavailable, message: "use '.lazy.map' on the sequence") public init(_ base: Base, transform: (Base.Iterator.Element) -> Element) { fatalError("unavailable function can't be called") } } extension LazyMapCollection { @available(*, unavailable, message: "use '.lazy.map' on the collection") public init(_ base: Base, transform: (Base.Iterator.Element) -> Element) { fatalError("unavailable function can't be called") } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
391eda460e2f87cdeac00e5483219b9e
33.655172
80
0.668823
false
false
false
false
linbin00303/Dotadog
refs/heads/master
DotaDog/DotaDog/Classes/Main/AppDelegate.swift
mit
1
// // AppDelegate.swift // DotaDog // // Created by 林彬 on 16/4/27. // Copyright © 2016年 linbin. All rights reserved. // import UIKit import FMDB @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var leftView : UIView? private var heroesInfo : NSDictionary? private var heroesNameEN : NSArray? private var abilitys : NSDictionary? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // 设置根控制器 window = UIWindow(frame: UIScreen.mainScreen().bounds) let baseVC = DDogBaseViewController() window?.rootViewController = baseVC window?.backgroundColor = UIColor.blackColor() window?.makeKeyAndVisible() canConnectToNet { (result) in if result == "no"{ let controller = getAlert("网络状态", message: "未能连接到服务器", doWhat: { (action) in }) baseVC.presentViewController(controller, animated: true, completion: nil) } } // 发送请求,保存数据到数据库 saveDataIntoSqlite() // 非正常启动 if launchOptions != nil { if launchOptions![UIApplicationLaunchOptionsLocalNotificationKey] != nil { } } registerAuthor() // 测试时间 1464551470 // let str = DDogTimeTransform.timeTransUTCtoDate(1464921390) // print(str) // let basePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first // let fullPath = basePath! + "/dotadog.sqlite" // print(fullPath) return true } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { let state = application.applicationState if state == .Active { // 前台 var dic = notification.userInfo let str = dic!["key"] as! String let alert = UIAlertView(title: "比赛通知", message: str, delegate: nil, cancelButtonTitle: "OK") alert.show() let navView = window?.rootViewController?.childViewControllers[1].childViewControllers[2] as? DDogNavController let matchVC = navView?.childViewControllers[0] as? DDogMatchController matchVC?.tableView.reloadData() } if state == .Inactive { // 如果当前不在前台, 接收到通知, 要求, 用户点击通知之后, 跳转到会话详情 } } 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) { // 如果应用程序的图标数字值为0, 就可以隐藏图标数字 UIApplication.sharedApplication().applicationIconBadgeNumber = 0 UIView.setAnimationBeginsFromCurrentState(true) } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } private func saveDataIntoSqlite() { var herocount : Int32 = 0 var itemcount : Int32 = 0 var abilitycount : Int32 = 0 // print(isTableLive("hero"),isTableLive("items"),isTableLive("ability")) // 开启子线程,进行网络请求和数据存储 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // 如果表都存在,计算每一个表的列数 if isTableLive("hero")&&isTableLive("items")&&isTableLive("ability") { DDogFMDBTool.shareInstance.columnsFromTable("hero") { (result) in herocount = result } DDogFMDBTool.shareInstance.columnsFromTable("items") { (result) in itemcount = result } DDogFMDBTool.shareInstance.columnsFromTable("ability") { (result) in abilitycount = result } } if herocount == 111 && itemcount == 189 && abilitycount == 503{ return } DDogFMDBTool.shareInstance.update_deleteData("hero") DDogFMDBTool.shareInstance.update_deleteData("items") DDogFMDBTool.shareInstance.update_deleteData("ability") // 处理英雄数据,网络请求+存入数据库 DDogHeroesAndItemsDataSync.shareInstance.handleHeroesInfoData { (results) in } // 处理物品数据,网络请求+存入数据库 DDogHeroesAndItemsDataSync.shareInstance.handleItemsInfoData { (results) in } // 处理完毕,通知主线程 dispatch_async(dispatch_get_main_queue()) { } } } } extension AppDelegate { // 一般请求授权的方法, 写在应用程序启动的代理方法里面, 主要是为了刚启动, 就请求用户的权限(此处, 写在这里, 是方便查看代码) func registerAuthor() -> () { // 在ios8.0以后, 如果想要发送本地通知, 需要主动请求授权 // 另外, 做好版本适配(可以把项目的最低部署版本调低, 让他自动报错修复即可) if #available(iOS 8.0, *) { // 1. 指定需要请求的授权类型(哪些权限,比如弹框, 声音, 图标数字等等) let typeValue = UIUserNotificationType.Alert.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Badge.rawValue let type = UIUserNotificationType(rawValue: typeValue) // 2. 根据请求的授权类型, 创建一个通知设置对象 let setting = UIUserNotificationSettings(forTypes: type, categories: nil) // 3. 注册通知设置对象(这时, 系统会自动弹出一个授权窗口, 让用户进行授权) UIApplication.sharedApplication().registerUserNotificationSettings(setting) } } }
ae00290047eb90c0a8ba8a36e8ae4cca
34.755102
285
0.608162
false
false
false
false
CodaFi/swift
refs/heads/master
test/DebugInfo/transparent.swift
apache-2.0
3
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | %FileCheck %s func use<T>(_ t: T) {} @inline(never) public func noinline(_ x: Int64) -> Int64 { return x } @_transparent public func transparent(_ y: Int64) -> Int64 { var local = y return noinline(local) } let z = transparent(0) use(z) // Check that a transparent function has no debug information. // CHECK: define {{.*}}$s11transparentAA // CHECK-SAME: !dbg ![[SP:[0-9]+]] // CHECK-NEXT: entry: // CHECK-NEXT: !dbg ![[ZERO:[0-9]+]] // CHECK-NEXT: } // CHECK: ![[FILE:[0-9]+]] = {{.*}}"<compiler-generated>" // CHECK: ![[SP]] = {{.*}}name: "transparent" // CHECK-SAME: file: ![[FILE:[0-9]+]] // CHECK-NOT: line: // CHECK: ![[ZERO]] = !DILocation(line: 0,
bd11ec8bc45a347e9aad4a96ce02bcc6
25.035714
75
0.591221
false
false
false
false
shanksyang/SwiftRegex
refs/heads/master
SwiftRegex/SwiftRegex.swift
bsd-3-clause
1
// // SwiftRegex.swift // SwiftRegex // // Created by Gregory Todd Williams on 6/7/14. // Copyright (c) 2014 Gregory Todd Williams. All rights reserved. // import Foundation //extension String { // func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? { // let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex) // let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex) // if let from = String.Index(from16, within: self), // let to = String.Index(to16, within: self) { // return from ..< to // } // return nil // } //} // // //extension String { // func NSRangeFromRange(range : Range<String.Index>) -> NSRange { // let utf16view = self.utf16 // let from = String.UTF16View.Index(range.startIndex, within: utf16view) // let to = String.UTF16View.Index(range.endIndex, within: utf16view) // return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to)) // } //} infix operator =~ {} func =~ (value : String, pattern : String) -> RegexMatchResult { let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange) let options : NSRegularExpressionOptions = [] do { let re = try NSRegularExpression(pattern: pattern, options: options) let all = NSRange(location: 0, length: nsstr.length) var matches : Array<String> = [] var captureResult : [RegexCaptureResult] = [RegexCaptureResult]() re.enumerateMatchesInString(value, options: [], range: all) { (result, flags, ptr) -> Void in guard let result = result else { return } var captureItems : [String] = [] for i in 0..<result.numberOfRanges { let range = result.rangeAtIndex(i) print(range) let string = nsstr.substringWithRange(range) if(i > 0) { captureItems.append(string) continue } matches.append(string) } captureResult.append(RegexCaptureResult(items: captureItems)) print(matches) } return RegexMatchResult(items: matches, captureItems: captureResult) } catch { return RegexMatchResult(items: [], captureItems: []) } } struct RegexMatchCaptureGenerator : GeneratorType { var items: Array<String> mutating func next() -> String? { if items.isEmpty { return nil } let ret = items[0] items = Array(items[1..<items.count]) return ret } } struct RegexMatchResult : SequenceType, BooleanType { var items: Array<String> var captureItems: [RegexCaptureResult] func generate() -> RegexMatchCaptureGenerator { print(items) return RegexMatchCaptureGenerator(items: items) } var boolValue: Bool { return items.count > 0 } subscript (i: Int) -> String { return items[i] } } struct RegexCaptureResult { var items: Array<String> } class SwiftRegex { //是否包含 class func containsMatch(pattern: String, inString string: String) -> Bool { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: matchOptions, range: range) != nil } //匹配 class func match(pattern: String, inString string: String) -> RegexMatchResult { return string =~ pattern } //替换 class func replaceMatches(pattern: String, inString string: String, withString replacementString: String) -> String? { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.stringByReplacingMatchesInString(string, options: matchOptions, range: range, withTemplate: replacementString) } }
5666a89041fe1285347feca186ff8492
32.648438
131
0.621082
false
false
false
false
syoutsey/swift-corelibs-foundation
refs/heads/master
Foundation/NSString.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public typealias unichar = UInt16 extension unichar : UnicodeScalarLiteralConvertible { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } #if os(OSX) || os(iOS) internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.MacRoman.rawValue internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.WindowsLatin1.rawValue internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.ISOLatin1.rawValue internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.NextStepLatin.rawValue internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.Unicode.rawValue internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.NonLossyASCII.rawValue internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue #endif public struct NSStringEncodingConversionOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let AllowLossy = NSStringEncodingConversionOptions(rawValue: 1) public static let ExternalRepresentation = NSStringEncodingConversionOptions(rawValue: 2) } public struct NSStringEnumerationOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ByLines = NSStringEnumerationOptions(rawValue: 0) public static let ByParagraphs = NSStringEnumerationOptions(rawValue: 1) public static let ByComposedCharacterSequences = NSStringEnumerationOptions(rawValue: 2) public static let ByWords = NSStringEnumerationOptions(rawValue: 3) public static let BySentences = NSStringEnumerationOptions(rawValue: 4) public static let Reverse = NSStringEnumerationOptions(rawValue: 1 << 8) public static let SubstringNotRequired = NSStringEnumerationOptions(rawValue: 1 << 9) public static let Localized = NSStringEnumerationOptions(rawValue: 1 << 10) } extension String : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSString.self } public func _bridgeToObjectiveC() -> NSString { return NSString(self) } public static func _forceBridgeFromObjectiveC(x: NSString, inout result: String?) { if x.dynamicType == NSString.self || x.dynamicType == NSMutableString.self { result = x._storage } else if x.dynamicType == _NSCFString.self { let cf = unsafeBitCast(x, CFStringRef.self) let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) if str != nil { result = String.fromCString(str) } else { let length = CFStringGetLength(cf) let buffer = UnsafeMutablePointer<UniChar>.alloc(length) CFStringGetCharacters(cf, CFRangeMake(0, length), buffer) let str = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: buffer, count: length)) buffer.destroy(length) buffer.dealloc(length) result = str } } else if x.dynamicType == _NSCFConstantString.self { let conststr = unsafeBitCast(x, _NSCFConstantString.self) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length))) result = str } else { NSUnimplemented() // TODO: subclasses } } public static func _conditionallyBridgeFromObjectiveC(x: NSString, inout result: String?) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } public struct NSStringCompareOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let CaseInsensitiveSearch = NSStringCompareOptions(rawValue: 1) public static let LiteralSearch = NSStringCompareOptions(rawValue: 2) public static let BackwardsSearch = NSStringCompareOptions(rawValue: 4) public static let AnchoredSearch = NSStringCompareOptions(rawValue: 8) public static let NumericSearch = NSStringCompareOptions(rawValue: 64) public static let DiacriticInsensitiveSearch = NSStringCompareOptions(rawValue: 128) public static let WidthInsensitiveSearch = NSStringCompareOptions(rawValue: 256) public static let ForcedOrderingSearch = NSStringCompareOptions(rawValue: 512) public static let RegularExpressionSearch = NSStringCompareOptions(rawValue: 1024) } public class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID()) internal var _storage: String public var length: Int { get { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { return _storage.utf16.count } else { NSRequiresConcreteImplementation() } } } public func characterAtIndex(index: Int) -> unichar { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { let start = _storage.utf16.startIndex return _storage.utf16[start.advancedBy(index)] } else { NSRequiresConcreteImplementation() } } deinit { _CFDeinit(self) } public override convenience init() { let characters = Array<unichar>(count: 1, repeatedValue: 0) self.init(characters: characters, length: 0) } internal init(_ string: String) { _storage = string } public convenience required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func copyWithZone(zone: NSZone) -> AnyObject { return self } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { let contents = _fastContents if contents != nil { return NSMutableString(characters: contents, length: length) } } let characters = UnsafeMutablePointer<unichar>.alloc(length) self.getCharacters(characters, range: NSMakeRange(0, length)) let result = NSMutableString(characters: characters, length: length) characters.destroy() characters.dealloc(length) return result } public static func supportsSecureCoding() -> Bool { return true } public func encodeWithCoder(aCoder: NSCoder) { } public init(characters: UnsafePointer<unichar>, length: Int) { _storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { _storage = String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.byteSize))) } else { var uintValue = value.unicodeScalar.value _storage = String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)) } } internal var _fastCStringContents: UnsafePointer<Int8> { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if _storage._core.isASCII { return unsafeBitCast(_storage._core.startASCII, UnsafePointer<Int8>.self) } } return nil } internal var _fastContents: UnsafePointer<UniChar> { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if !_storage._core.isASCII { return unsafeBitCast(_storage._core.startUTF16, UnsafePointer<UniChar>.self) } } return nil } override internal var _cfTypeID: CFTypeID { return CFStringGetTypeID() } public override func isEqual(object: AnyObject?) -> Bool { guard let string = (object as? NSString)?._swiftObject else { return false } return self.isEqualToString(string) } } extension NSString { public func getCharacters(buffer: UnsafeMutablePointer<unichar>, range: NSRange) { for var idx = 0; idx < range.length; idx++ { buffer[idx] = characterAtIndex(idx + range.location) } } public func substringFromIndex(from: Int) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return String(_storage.utf16.suffixFrom(_storage.utf16.startIndex.advancedBy(from))) } else { return self.substringWithRange(NSMakeRange(from, self.length - from)) } } public func substringToIndex(to: Int) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return String(_storage.utf16.prefixUpTo(_storage.utf16.startIndex .advancedBy(to))) } else { return self.substringWithRange(NSMakeRange(0, to)) } } public func substringWithRange(range: NSRange) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { let start = _storage.utf16.startIndex return String(_storage.utf16[Range<String.UTF16View.Index>(start: start.advancedBy(range.location), end: start.advancedBy(range.location + range.length))]) } else { let buff = UnsafeMutablePointer<unichar>.alloc(range.length) self.getCharacters(buff, range: range) let result = String(buff) buff.destroy() buff.dealloc(range.length) return result } } public func compare(string: String) -> NSComparisonResult { return compare(string, options: [], range:NSMakeRange(0, self.length), locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions) -> NSComparisonResult { return compare(string, options: mask, range:NSMakeRange(0, self.length), locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions, range compareRange: NSRange) -> NSComparisonResult { return compare(string, options: [], range:compareRange, locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions, range compareRange: NSRange, locale: AnyObject?) -> NSComparisonResult { if let _ = locale { NSUnimplemented() } #if os(Linux) var cfflags = CFStringCompareFlags(mask.rawValue) if mask.contains(.LiteralSearch) { cfflags |= UInt(kCFCompareNonliteral) } #else var cfflags = CFStringCompareFlags(rawValue: mask.rawValue) if mask.contains(.LiteralSearch) { cfflags.unionInPlace(.CompareNonliteral) } #endif let cfresult = CFStringCompareWithOptionsAndLocale(self._cfObject, string._cfObject, CFRangeMake(compareRange.location, compareRange.length), cfflags, nil) #if os(Linux) return NSComparisonResult(rawValue: cfresult)! #else return NSComparisonResult(rawValue: cfresult.rawValue)! #endif } public func caseInsensitiveCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: nil) } public func localizedCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func localizedCaseInsensitiveCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func localizedStandardCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch, .NumericSearch, .WidthInsensitiveSearch, .ForcedOrderingSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func isEqualToString(aString: String) -> Bool { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return _storage == aString } else { return self.length == aString._nsObject.length && self.compare(aString, options: [.LiteralSearch], range: NSMakeRange(0, self.length)) == .OrderedSame } } public func hasPrefix(str: String) -> Bool { return _swiftObject.hasPrefix(str) } public func hasSuffix(str: String) -> Bool { return _swiftObject.hasSuffix(str) } public func commonPrefixWithString(str: String, options mask: NSStringCompareOptions) -> String { NSUnimplemented() } public func containsString(str: String) -> Bool { return self.rangeOfString(str).location != NSNotFound } public func localizedCaseInsensitiveContainsString(str: String) -> Bool { return self.rangeOfString(str, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()).location != NSNotFound } public func localizedStandardContainsString(str: String) -> Bool { return self.rangeOfString(str, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()).location != NSNotFound } public func localizedStandardRangeOfString(str: String) -> NSRange { return self.rangeOfString(str, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func rangeOfString(searchString: String) -> NSRange { return self.rangeOfString(searchString, options: [], range: NSMakeRange(0, self.length), locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions) -> NSRange { return self.rangeOfString(searchString, options: mask, range: NSMakeRange(0, self.length), locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange { return self.rangeOfString(searchString, options: mask, range: searchRange, locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions, range searchRange: NSRange, locale: NSLocale?) -> NSRange { if let _ = locale { NSUnimplemented() } if mask.contains(.RegularExpressionSearch) { NSUnimplemented() } if searchString.length == 0 || searchRange.length == 0 { return NSMakeRange(NSNotFound, 0) } #if os(Linux) var cfflags = CFStringCompareFlags(mask.rawValue) if mask.contains(.LiteralSearch) { cfflags |= UInt(kCFCompareNonliteral) } #else var cfflags = CFStringCompareFlags(rawValue: mask.rawValue) if mask.contains(.LiteralSearch) { cfflags.unionInPlace(.CompareNonliteral) } #endif var result = CFRangeMake(kCFNotFound, 0) if CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRangeMake(searchRange.location, searchRange.length), cfflags, nil, &result) { return NSMakeRange(result.location, result.length) } else { return NSMakeRange(NSNotFound, 0) } } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet) -> NSRange { NSUnimplemented() } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet, options mask: NSStringCompareOptions) -> NSRange { NSUnimplemented() } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange { NSUnimplemented() } public func rangeOfComposedCharacterSequenceAtIndex(index: Int) -> NSRange { NSUnimplemented() } public func rangeOfComposedCharacterSequencesForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func stringByAppendingString(aString: String) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return _storage + aString } else { NSUnimplemented() } } public var doubleValue: Double { get { NSUnimplemented() } } public var floatValue: Float { get { NSUnimplemented() } } public var intValue: Int32 { get { NSUnimplemented() } } public var integerValue: Int { get { NSUnimplemented() } } public var longLongValue: Int64 { get { NSUnimplemented() } } public var boolValue: Bool { get { NSUnimplemented() } } public var uppercaseString: String { get { NSUnimplemented() } } public var lowercaseString: String { get { NSUnimplemented() } } public var capitalizedString: String { get { NSUnimplemented() } } public var localizedUppercaseString: String { get { NSUnimplemented() } } public var localizedLowercaseString: String { get { NSUnimplemented() } } public var localizedCapitalizedString: String { get { NSUnimplemented() } } public func uppercaseStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func lowercaseStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func capitalizedStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func getLineStart(startPtr: UnsafeMutablePointer<Int>, end lineEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange) { NSUnimplemented() } public func lineRangeForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func getParagraphStart(startPtr: UnsafeMutablePointer<Int>, end parEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange) { NSUnimplemented() } public func paragraphRangeForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func enumerateSubstringsInRange(range: NSRange, options opts: NSStringEnumerationOptions, usingBlock block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateLinesUsingBlock(block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public var UTF8String: UnsafePointer<Int8> { get { NSUnimplemented() } } public var fastestEncoding: UInt { get { NSUnimplemented() } } public var smallestEncoding: UInt { get { NSUnimplemented() } } public func dataUsingEncoding(encoding: UInt, allowLossyConversion lossy: Bool) -> NSData? { NSUnimplemented() } public func dataUsingEncoding(encoding: UInt) -> NSData? { NSUnimplemented() } public func canBeConvertedToEncoding(encoding: UInt) -> Bool { NSUnimplemented() } public func cStringUsingEncoding(encoding: UInt) -> UnsafePointer<Int8> { NSUnimplemented() } public func getCString(buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if _storage._core.isASCII { let len = min(self.length, maxBufferCount) buffer.moveAssignFrom(unsafeBitCast(_storage._core.startASCII, UnsafeMutablePointer<Int8>.self) , count: len) return true } } return false } public func getBytes(buffer: UnsafeMutablePointer<Void>, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: UInt, options: NSStringEncodingConversionOptions, range: NSRange, remainingRange leftover: NSRangePointer) -> Bool { NSUnimplemented() } public func maximumLengthOfBytesUsingEncoding(enc: UInt) -> Int { NSUnimplemented() } public func lengthOfBytesUsingEncoding(enc: UInt) -> Int { NSUnimplemented() } public class func availableStringEncodings() -> UnsafePointer<UInt> { NSUnimplemented() } public class func localizedNameOfStringEncoding(encoding: UInt) -> String { NSUnimplemented() } public class func defaultCStringEncoding() -> UInt { NSUnimplemented() } public var decomposedStringWithCanonicalMapping: String { get { NSUnimplemented() } } public var precomposedStringWithCanonicalMapping: String { get { NSUnimplemented() } } public var decomposedStringWithCompatibilityMapping: String { get { NSUnimplemented() } } public var precomposedStringWithCompatibilityMapping: String { get { NSUnimplemented() } } public func componentsSeparatedByString(separator: String) -> [String] { NSUnimplemented() } public func componentsSeparatedByCharactersInSet(separator: NSCharacterSet) -> [String] { NSUnimplemented() } public func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String { NSUnimplemented() } public func stringByPaddingToLength(newLength: Int, withString padString: String, startingAtIndex padIndex: Int) -> String { NSUnimplemented() } public func stringByFoldingWithOptions(options: NSStringCompareOptions, locale: NSLocale?) -> String { NSUnimplemented() } public func stringByReplacingOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions, range searchRange: NSRange) -> String { NSUnimplemented() } public func stringByReplacingOccurrencesOfString(target: String, withString replacement: String) -> String { NSUnimplemented() } public func stringByReplacingCharactersInRange(range: NSRange, withString replacement: String) -> String { NSUnimplemented() } public func stringByApplyingTransform(transform: String, reverse: Bool) -> String? { NSUnimplemented() } public func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { NSUnimplemented() } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { NSUnimplemented() } public convenience init?(UTF8String nullTerminatedCString: UnsafePointer<Int8>) { NSUnimplemented() } public convenience init(string aString: String) { NSUnimplemented() } public convenience init(format: String, arguments argList: CVaListPointer) { NSUnimplemented() } public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) { NSUnimplemented() } public convenience init?(data: NSData, encoding: UInt) { self.init(bytes: data.bytes, length: data.length, encoding: encoding) } public convenience init?(bytes: UnsafePointer<Void>, length len: Int, encoding: UInt) { guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, UnsafePointer<UInt8>(bytes), len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } self.init(cf._swiftObject) } public convenience init?(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { NSUnimplemented() } public convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { guard let cf = CFStringCreateWithCString(kCFAllocatorDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else { return nil } self.init(cf._swiftObject) } public convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(contentsOfFile path: String, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<UInt>) throws { NSUnimplemented() } public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>) throws { NSUnimplemented() } } extension NSString : StringLiteralConvertible { } public class NSMutableString : NSString { public func replaceCharactersInRange(range: NSRange, withString aString: String) { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { // this is incorrectly calculated for grapheme clusters that have a size greater than a single unichar let start = _storage.startIndex let subrange = Range(start: start.advancedBy(range.location), end: start.advancedBy(range.location + range.length)) _storage.replaceRange(subrange, with: aString) } else { NSRequiresConcreteImplementation() } } public required override init(characters: UnsafePointer<unichar>, length: Int) { super.init(characters: characters, length: length) } public required init(capacity: Int) { super.init(characters: nil, length: 0) } public convenience required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.byteSize)))) } else { var uintValue = value.unicodeScalar.value super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1))) } } internal func appendCharacters(characters: UnsafePointer<unichar>, length: Int) { if self.dynamicType == NSMutableString.self { _storage.appendContentsOf(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } else { replaceCharactersInRange(NSMakeRange(self.length, 0), withString: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } } internal func _cfAppendCString(characters: UnsafePointer<Int8>, length: Int) { if self.dynamicType == NSMutableString.self { _storage.appendContentsOf(String.fromCString(characters)!) } } } extension NSMutableString { public func insertString(aString: String, atIndex loc: Int) { self.replaceCharactersInRange(NSMakeRange(loc, 0), withString: aString) } public func deleteCharactersInRange(range: NSRange) { self.replaceCharactersInRange(range, withString: "") } public func appendString(aString: String) { self.replaceCharactersInRange(NSMakeRange(self.length, 0), withString: aString) } public func setString(aString: String) { self.replaceCharactersInRange(NSMakeRange(0, self.length), withString: aString) } public func replaceOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions, range searchRange: NSRange) -> Int { NSUnimplemented() } public func applyTransform(transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer) -> Bool { NSUnimplemented() } } extension String { /// Returns an Array of the encodings string objects support /// in the application’s environment. private static func _getAvailableStringEncodings() -> [NSStringEncoding] { let encodings = CFStringGetListOfAvailableEncodings() var numEncodings = 0 var encodingArray = Array<NSStringEncoding>() while encodings.advancedBy(numEncodings).memory != CoreFoundation.kCFStringEncodingInvalidId { encodingArray.append(CFStringConvertEncodingToNSStringEncoding(encodings.advancedBy(numEncodings).memory)) numEncodings++ } return encodingArray } private static var _availableStringEncodings = String._getAvailableStringEncodings() @warn_unused_result public static func availableStringEncodings() -> [NSStringEncoding] { return _availableStringEncodings } @warn_unused_result public static func defaultCStringEncoding() -> NSStringEncoding { return NSUTF8StringEncoding } @warn_unused_result public static func localizedNameOfStringEncoding(encoding: NSStringEncoding) -> String { return CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject } // this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters internal var length: Int { return utf16.count } public func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool { if encoding == NSUnicodeStringEncoding || encoding == NSNonLossyASCIIStringEncoding || encoding == NSUTF8StringEncoding { return true } return false } public var capitalizedString: String { get { return capitalizedStringWithLocale(nil) } } public var localizedCapitalizedString: String { get { return capitalizedStringWithLocale(NSLocale.currentLocale()) } } @warn_unused_result public func capitalizedStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func caseInsensitiveCompare(aString: String) -> NSComparisonResult { return compare(aString, options: .CaseInsensitiveSearch, range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func compare(aString: String, options mask: NSStringCompareOptions = [], range: NSRange? = nil, locale: NSLocale? = nil) -> NSComparisonResult { NSUnimplemented() } #if os(Linux) public func hasPrefix(prefix: String) -> Bool { let characters = utf16 let prefixCharacters = prefix.utf16 let start = characters.startIndex let prefixStart = prefixCharacters.startIndex if characters.count < prefixCharacters.count { return false } for var idx = 0; idx < prefixCharacters.count; idx++ { if characters[start.advancedBy(idx)] != prefixCharacters[prefixStart.advancedBy(idx)] { return false } } return true } public func hasSuffix(suffix: String) -> Bool { let characters = utf16 let suffixCharacters = suffix.utf16 let start = characters.startIndex let suffixStart = suffixCharacters.startIndex if characters.count < suffixCharacters.count { return false } for var idx = 0; idx < suffixCharacters.count; idx++ { let charactersIdx = start.advancedBy(characters.count - idx - 1) let suffixIdx = suffixStart.advancedBy(suffixCharacters.count - idx - 1) if characters[charactersIdx] != suffixCharacters[suffixIdx] { return false } } return true } #endif } extension NSString : _CFBridgable, _SwiftBridgable { typealias SwiftType = String internal var _cfObject: CFStringRef { return unsafeBitCast(self, CFStringRef.self) } internal var _swiftObject: String { var str: String? String._forceBridgeFromObjectiveC(self, result: &str) return str! } } extension CFStringRef : _NSBridgable, _SwiftBridgable { typealias NSType = NSString typealias SwiftType = String internal var _nsObject: NSType { return unsafeBitCast(self, NSString.self) } internal var _swiftObject: String { return _nsObject._swiftObject } } extension String : _NSBridgable, _CFBridgable { typealias NSType = NSString typealias CFType = CFStringRef internal var _nsObject: NSType { return _bridgeToObjectiveC() } internal var _cfObject: CFType { return _nsObject._cfObject } } extension String : Bridgeable { public func bridge() -> NSString { return _nsObject } } extension NSString : Bridgeable { public func bridge() -> String { return _swiftObject } }
52f8beb5f76911927a74d7ddd8ab2924
36.405602
273
0.667018
false
false
false
false
imitationgame/pokemonpassport
refs/heads/master
pokepass/Model/Main/Transition/MMainTransitionReplace.swift
mit
1
import UIKit class MMainTransitionReplace:MMainTransition { private let kAnimationDuration:TimeInterval = 0 init() { super.init(animationDuration:kAnimationDuration) } override func positionAfter() { let barHeight:CGFloat if parent.bar == nil { barHeight = 0 } else { barHeight = parent.kBarHeight } parent.layoutTopTemporal = NSLayoutConstraint( item:next.view, attribute:NSLayoutAttribute.top, relatedBy:NSLayoutRelation.equal, toItem:parent.view, attribute:NSLayoutAttribute.top, multiplier:1, constant:barHeight) parent.layoutBottomTemporal = NSLayoutConstraint( item:next.view, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:parent.view, attribute:NSLayoutAttribute.bottom, multiplier:1, constant:0) parent.layoutLeftTemporal = NSLayoutConstraint( item:next.view, attribute:NSLayoutAttribute.left, relatedBy:NSLayoutRelation.equal, toItem:parent.view, attribute:NSLayoutAttribute.left, multiplier:1, constant:0) parent.layoutRightTemporal = NSLayoutConstraint( item:next.view, attribute:NSLayoutAttribute.right, relatedBy:NSLayoutRelation.equal, toItem:parent.view, attribute:NSLayoutAttribute.right, multiplier:1, constant:0) parent.view.addConstraint(parent.layoutLeftTemporal!) parent.view.addConstraint(parent.layoutRightTemporal!) parent.view.addConstraint(parent.layoutTopTemporal!) parent.view.addConstraint(parent.layoutBottomTemporal!) parent.layoutTop = parent.layoutTopTemporal parent.layoutBottom = parent.layoutBottomTemporal parent.layoutRight = parent.layoutRightTemporal parent.layoutLeft = parent.layoutLeftTemporal } }
735ee1db8a5a0d1e83be6b89e7c027b8
31.089552
63
0.617209
false
false
false
false
qualaroo/QualarooSDKiOS
refs/heads/master
Qualaroo/Filters/PropertyInjector.swift
mit
1
// // TextConverter.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation protocol TextConverter: class { func convert(_ text: String) -> String } class PropertyInjector { let customProperties: CustomProperties init(customProperties: CustomProperties) { self.customProperties = customProperties } private func check(survey: Survey) -> Bool { var missing = [String]() for node in survey.nodeList { missing.append(contentsOf: missingProperties(node: node)) } if missing.count > 0 { Qualaroo.log(""" Not showing survey with id: \(survey.surveyId). Missing custom properties: \(missing.joined(separator: ", ")) """) return false } return true } private func missingProperties(node: Node) -> [String] { switch node { case let question as Question: var missing = missingProperties(question.title) missing.append(contentsOf: missingProperties(question.description)) return missing case let leadGen as LeadGenForm: return missingProperties(leadGen.description) case let message as Message: return missingProperties(message.description) default: return [] } } private func missingProperties(_ text: String) -> [String] { var properties = findAllProperties(in: text) properties = properties.map { removeBrackets($0) } return customProperties.checkForMissing(withKeywords: properties) } private func injectProperties(_ text: String) -> String { var replacedText = text let properties = findAllProperties(in: text) for property in properties { let value = customProperties.dictionary[removeBrackets(property)] ?? "" replacedText = replacedText.replacingOccurrences(of: property, with: value) } return replacedText } private func removeBrackets(_ text: String) -> String { let start = text.index(text.startIndex, offsetBy: 2) let end = text.index(before: text.endIndex) let range = start..<end return String(text[range]) } private func findAllProperties(in text: String) -> [String] { let pattern = "\\$\\{.*?\\}" //swiftlint:disable:next force_try let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.count)) return matches.map { String(text[text.range(from: $0.range)]) } } } extension PropertyInjector: TextConverter { func convert(_ text: String) -> String { return injectProperties(text) } } extension PropertyInjector: FilterProtocol { func shouldShow(survey: Survey) -> Bool { return check(survey: survey) } }
e5870b55cd5213290c9363598597190e
29.79798
77
0.646113
false
false
false
false
fqhuy/minimind
refs/heads/master
miniminds/AppDelegate.swift
mit
1
// // AppDelegate.swift // miniminds // // Created by Phan Quoc Huy on 6/4/17. // Copyright © 2017 Phan Quoc Huy. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "miniminds") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
6ff2840dd3bfba6ecfbd558a27c31c64
48.408602
285
0.685528
false
false
false
false
The9Labs/AudioMate
refs/heads/develop
AudioMate/PreferencesTabViewController.swift
mit
2
// // PreferencesTabViewController.swift // AudioMate // // Created by Ruben Nine on 12/15/16. // Copyright © 2016 Ruben Nine. All rights reserved. // import Cocoa class PreferencesTabViewController: NSTabViewController { lazy var originalSizes = [NSTabViewItem : NSSize]() override func viewDidLoad() { super.viewDidLoad() Utils.transformAppIntoForegroundMode() // Activate (give focus to) our app NSApplication.shared().activate(ignoringOtherApps: true) transitionOptions = [.crossfade, .allowUserInteraction] } // MARK: - Lifecycle functions deinit { Utils.transformAppIntoUIElementMode() } // MARK: - NSViewController overrides override func viewWillAppear() { setOriginalSizeFor(tabViewItem: tabViewItems[selectedTabViewItemIndex]) animateTabViewTransitionTo(tabViewItem: tabViewItems[selectedTabViewItemIndex]) super.viewWillAppear() } // MARK: - NSTabViewDelegate override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { super.tabView(tabView, willSelect: tabViewItem) if let tabViewItem = tabViewItem { setOriginalSizeFor(tabViewItem: tabViewItem) } } override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { super.tabView(tabView, didSelect: tabViewItem) if let tabViewItem = tabViewItem { animateTabViewTransitionTo(tabViewItem: tabViewItem) } } // MARK: - Private functions private func setOriginalSizeFor(tabViewItem: NSTabViewItem) { if (originalSizes[tabViewItem] == nil) { originalSizes[tabViewItem] = tabViewItem.view?.frame.size } } private func animateTabViewTransitionTo(tabViewItem: NSTabViewItem) { guard let window = view.window else { return } if let size = originalSizes[tabViewItem] { window.title = tabViewItem.label let contentFrame = window.frameRect(forContentRect: NSRect(origin: .zero, size: size)) var frame = window.frame frame.origin.y += (frame.height - contentFrame.height) frame.size = contentFrame.size window.setFrame(frame, display: false, animate: true) } } }
f1dd3d41ad2fcdaf06dcf89aab2e2e11
25.393258
98
0.661984
false
false
false
false
pinterest/PINRemoteImage
refs/heads/master
Examples/Swift-Example/Swift-Example/ScrollViewController.swift
apache-2.0
1
// // ScrollViewController.swift // Swift-Example // // Created by Marius Landwehr on 23.01.16. // Copyright © 2016 Marius Landwehr. All rights reserved. // import UIKit import PINRemoteImage import PINCache struct Kitten { let imageUrl : URL let size : CGSize var dominantColor : UIColor? init(urlString : String, size : CGSize) { self.imageUrl = URL(string: urlString)! self.size = size } } class PinImageCell : UICollectionViewCell { let imageView : UIImageView override init(frame: CGRect) { imageView = UIImageView() super.init(frame: frame) imageView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(imageView) let view = ["imageView" : imageView] let constraintsH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[imageView]-0-|", options: [], metrics: nil, views: view) let constraintsV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[imageView]-0-|", options: [], metrics: nil, views: view) contentView.addConstraints(constraintsH) contentView.addConstraints(constraintsV) layer.cornerRadius = 7 layer.masksToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } } class ScrollViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { let kittens = [ Kitten(urlString: "https://i.pinimg.com/736x/92/5d/5a/925d5ac74db0dcfabc238e1686e31d16.jpg", size: CGSize(width: 503, height: 992)), Kitten(urlString: "https://i.pinimg.com/736x/ff/b3/ae/ffb3ae40533b7f9463cf1c04d7ab69d1.jpg", size: CGSize(width: 500, height: 337)), Kitten(urlString: "https://i.pinimg.com/736x/e4/b7/7c/e4b77ca06e1d4a401b1a49d7fadd90d9.jpg", size: CGSize(width: 522, height: 695)), Kitten(urlString: "https://i.pinimg.com/736x/46/e1/59/46e159d76b167ed9211d662f95e7bf6f.jpg", size: CGSize(width: 557, height: 749)), Kitten(urlString: "https://i.pinimg.com/736x/7a/72/77/7a72779329942c06f888c148eb8d7e34.jpg", size: CGSize(width: 710, height: 1069)), Kitten(urlString: "https://i.pinimg.com/736x/60/21/8f/60218ff43257fb3b6d7c5b888f74a5bf.jpg", size: CGSize(width: 522, height: 676)), Kitten(urlString: "https://i.pinimg.com/736x/90/e8/e4/90e8e47d53e71e0d97691dd13a5617fb.jpg", size: CGSize(width: 500, height: 688)), Kitten(urlString: "https://i.pinimg.com/736x/96/ae/31/96ae31fbc52d96dd3308d2754a6ca37e.jpg", size: CGSize(width: 377, height: 700)), Kitten(urlString: "https://i.pinimg.com/736x/9b/7b/99/9b7b99ff63be31bba8f9863724b3ebbc.jpg", size: CGSize(width: 334, height: 494)), Kitten(urlString: "https://i.pinimg.com/736x/80/23/51/802351d953dd2a8b232d0da1c7ca6880.jpg", size: CGSize(width: 625, height: 469)), Kitten(urlString: "https://i.pinimg.com/736x/f5/c4/f0/f5c4f04fa2686338dc3b08420d198484.jpg", size: CGSize(width: 625, height: 833)), Kitten(urlString: "https://i.pinimg.com/736x/2b/06/4f/2b064f3e0af984a556ac94b251ff7060.jpg", size: CGSize(width: 625, height: 469)), Kitten(urlString: "https://i.pinimg.com/736x/17/1f/c0/171fc02398143269d8a507a15563166a.jpg", size: CGSize(width: 625, height: 469)), Kitten(urlString: "https://i.pinimg.com/736x/8a/35/33/8a35338bbf67c86a198ba2dd926edd82.jpg", size: CGSize(width: 625, height: 791)), Kitten(urlString: "https://i.pinimg.com/736x/4d/6e/3c/4d6e3cf970031116c57486e85c2a4cab.jpg", size: CGSize(width: 625, height: 833)), Kitten(urlString: "https://i.pinimg.com/736x/54/25/ee/5425eeccba78731cf7be70f0b8808bd2.jpg", size: CGSize(width: 605, height: 605)), Kitten(urlString: "https://i.pinimg.com/736x/04/f1/3f/04f13fdb7580dcbe8c4d6b7d5a0a5ec2.jpg", size: CGSize(width: 504, height: 750)), Kitten(urlString: "https://i.pinimg.com/736x/dc/16/4e/dc164ed33af9d899e5ed188e642f00e9.jpg", size: CGSize(width: 500, height: 500)), Kitten(urlString: "https://i.pinimg.com/736x/c1/06/13/c106132936189b6cb654671f2a2183ed.jpg", size: CGSize(width: 640, height: 640)), Kitten(urlString: "https://i.pinimg.com/736x/46/43/ed/4643eda4e1be4273721a76a370b90346.jpg", size: CGSize(width: 500, height: 473)), ] var collectionKittens = [Kitten]() var collectionView : UICollectionView? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) PINRemoteImageManager.shared().cache.removeAllObjects() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) PINRemoteImageManager.shared().cache.removeAllObjects() } override func viewDidLoad() { super.viewDidLoad() collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout()) collectionView?.register(PinImageCell.self, forCellWithReuseIdentifier: String(describing: PinImageCell.self)) collectionView?.delegate = self collectionView?.dataSource = self if let cView = collectionView { view.addSubview(cView) } createRandomKittens() } func createRandomKittens() { let dispatchGroup = DispatchGroup() if let bounds = collectionView?.bounds { var tmpKittens = [Kitten]() DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(group: dispatchGroup) { () -> Void in for _ in 1...500 { let randGreen : CGFloat = CGFloat(drand48()) let randBlue : CGFloat = CGFloat(drand48()) let randRed : CGFloat = CGFloat(drand48()) let randomColor = UIColor(red: randRed, green: randGreen, blue: randBlue, alpha: 1) let kittenIndex : Int = Int(arc4random() % 20) let randKitten = self.kittens[kittenIndex] var width = randKitten.size.width var height = randKitten.size.height if width > (bounds.size.width) { height = height / (width / bounds.size.width) width = bounds.size.width } var newKitten = Kitten(urlString: randKitten.imageUrl.absoluteString, size: CGSize(width: width, height: height)) newKitten.dominantColor = randomColor DispatchQueue.main.sync(execute: { () -> Void in tmpKittens.append(newKitten) }) } } dispatchGroup.notify(queue: DispatchQueue.main, execute: { () -> Void in self.collectionKittens += tmpKittens self.collectionView?.reloadData() }) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let kitten = collectionKittens[indexPath.row] return kitten.size } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PinImageCell.self), for: indexPath) if let pinCell = cell as? PinImageCell { let kitten = collectionKittens[indexPath.row] pinCell.backgroundColor = kitten.dominantColor pinCell.alpha = 0 weak var weakPinCell = pinCell pinCell.imageView.pin_setImage(from: kitten.imageUrl, completion: { (result) in if result.requestDuration > 0.25 { UIView.animate(withDuration: 0.3, animations: { weakPinCell?.alpha = 1 }) } else { weakPinCell?.alpha = 1 } }) } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collectionKittens.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } }
ca37fd152ce163901fda79ca790c98ef
45.178947
160
0.630157
false
false
false
false
gbuela/kanjiryokucha
refs/heads/master
KanjiRyokucha/LoginViewController.swift
mit
1
// // LoginViewController.swift // KanjiRyokucha // // Created by German Buela on 3/15/17. // Copyright © 2017 German Buela. All rights reserved. // import UIKit import ReactiveSwift class LoginViewController: UIViewController { @IBOutlet weak var loggingInLabel: UILabel! @IBOutlet weak var errorMessageLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var retryButton: UIButton! @IBOutlet weak var manualLoginButton: UIButton! let viewModel = LoginViewModel(sendLoginNotification: true) var started = false override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .ryokuchaFaint wireUp() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !started { started = true viewModel.autologin() } } private func wireUp() { activityIndicator.reactive.isHidden <~ viewModel.state.map { !$0.isLoggingIn() } loggingInLabel.reactive.isHidden <~ viewModel.state.map { !$0.isLoggingIn() } activityIndicator.reactive.isAnimating <~ viewModel.state.map { $0.isLoggingIn() } errorMessageLabel.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() } retryButton.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() } manualLoginButton.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() } errorMessageLabel.reactive.text <~ viewModel.state.map { (state: LoginState) -> String in switch state { case .failure(let message): return message default: return "" } } retryButton.reactive.controlEvents(.touchUpInside).react { [weak self] _ in self?.viewModel.autologin() } manualLoginButton.reactive.controlEvents(.touchUpInside).react { [weak self] _ in self?.viewModel.credentialsRequired.value = true } viewModel.credentialsRequired.uiReact { [weak self] required in if required { self?.promptForCredentials() } } } private func promptForCredentials() { let credentialsVC = CredentialsViewController() credentialsVC.enteredCredentialsCallback = { [weak self] (username: String, password: String) in self?.viewModel.attemptLogin(withUsername: username, password: password) } present(credentialsVC, animated: true, completion: nil) } }
5e5e2aed2ae56a6207797cd812f79f5c
32.576923
104
0.633066
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Group/Cells/AAGroupMemberCell.swift
mit
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit public class AAGroupMemberCell: AATableViewCell { // Views public var nameLabel = UILabel() public var onlineLabel = UILabel() public var avatarView = AAAvatarView() public var adminLabel = UILabel() // Binder public var binder = AABinder() // Contstructors public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) adminLabel.text = AALocalized("GroupMemberAdmin") adminLabel.sizeToFit() contentView.addSubview(avatarView) nameLabel.font = UIFont.systemFontOfSize(18.0) nameLabel.textColor = appStyle.cellTextColor contentView.addSubview(nameLabel) onlineLabel.font = UIFont.systemFontOfSize(14.0) contentView.addSubview(onlineLabel) adminLabel.font = UIFont.systemFontOfSize(14.0) adminLabel.textColor = appStyle.cellDestructiveColor contentView.addSubview(adminLabel) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Binding public func setUsername(username: String) { nameLabel.text = username } public func bind(user: ACUserVM, isAdmin: Bool) { // Bind name and avatar let name = user.getNameModel().get() nameLabel.text = name avatarView.bind(name, id: Int(user.getId()), avatar: user.getAvatarModel().get()) // Bind admin flag adminLabel.hidden = !isAdmin // Bind onlines if user.isBot() { self.onlineLabel.textColor = self.appStyle.userOnlineColor self.onlineLabel.text = "bot" self.onlineLabel.alpha = 1 } else { binder.bind(user.getPresenceModel()) { (value: ACUserPresence?) -> () in if value != nil { self.onlineLabel.showView() self.onlineLabel.text = Actor.getFormatter().formatPresence(value!, withSex: user.getSex()) if value!.state.ordinal() == ACUserPresence_State.ONLINE().ordinal() { self.onlineLabel.textColor = self.appStyle.userOnlineColor } else { self.onlineLabel.textColor = self.appStyle.userOfflineColor } } else { self.onlineLabel.alpha = 0 self.onlineLabel.text = "" } } } } public override func prepareForReuse() { super.prepareForReuse() binder.unbindAll() } // Layouting public override func layoutSubviews() { super.layoutSubviews() let userAvatarViewFrameSize: CGFloat = CGFloat(44) avatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize) var w: CGFloat = contentView.bounds.size.width - 65.0 - 8.0 if !adminLabel.hidden { adminLabel.frame = CGRect(x: contentView.width - adminLabel.width - 8, y: 5, width: adminLabel.width, height: 42) w -= adminLabel.width + 8 } nameLabel.frame = CGRect(x: 65.0, y: 5, width: w, height: 22) onlineLabel.frame = CGRect(x: 65.0, y: 27, width: w, height: 16) } }
5fcf775c8d952940944a809b699f3e64
32.045455
176
0.579917
false
false
false
false
AmitaiB/AmazingAgeTrick
refs/heads/master
AmazingAgeTrick/CardID-enum.swift
mit
1
// // CardID-enum.swift // AmazingAgeTrick // // Created by Amitai Blickstein on 1/13/16. // Copyright © 2016 Amitai Blickstein, LLC. All rights reserved. // import UIKit import UIColor_Hex_Swift //MARK: === CardID enum === /// CardID contains the 6 possible card values, and some convenience accessors. enum CardID:Int { case Card1 = 1, Card2 = 2, Card3 = 4, Card4 = 8, Card5 = 16, Card6 = 32 static let allValues = [Card1, Card2, Card3, Card4, Card5, Card6] func cardInfoArray()->[Int] { switch self { case .Card1: return [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59] case .Card2: return [2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31,34,35,38,39,42,43,46,47,50,51,54,55,58,59] case .Card3: return [4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31,36,37,38,39,44,45,46,47,52,53,54,55,60] case .Card4: return [8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31,40,41,42,43,44,45,46,47,56,57,58,59,60] case .Card5: return [16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,48,49,50,51,52,53,54,55,56,57,58,59,60] case .Card6: return [32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60] } } func altColorForCardID()->UIColor { switch self { case .Card1: return UIColor(red:0.74, green:0.16, blue:0.16, alpha:1) case .Card2: return UIColor(red:0.13, green:0.52, blue:0.85, alpha:1) case .Card3: return UIColor(red:0.96, green:0.95, blue:0.16, alpha:1) case .Card4: return UIColor(red:0.37, green:0.63, blue:0.21, alpha:1) case .Card5: return UIColor(red:0.77, green:0.41, blue:0.14, alpha:1) case .Card6: return UIColor(red:0.45, green:0.13, blue:0.49, alpha:1) } } func cellImageForCardID()->UIImage? { switch self { case .Card1: return UIImage(named: "Oval 24-red") case .Card2: return UIImage(named: "Oval 24-orange") case .Card3: return UIImage(named: "Oval 24-green") case .Card4: return UIImage(named: "Oval 24-blue") case .Card5: return UIImage(named: "Oval 24-violet") case .Card6: return UIImage(named: "Oval 24-midnight") } } }
3391397072f128b5a2df270a4a25b67d
40.392857
116
0.595772
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
Swift_Algorithm/Swift_Algorithm/Edge.swift
mit
1
// // Edge.swift // Swift_Algorithm // // Created by Hanguang on 23/11/2016. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation public struct Edge<T>: Equatable where T: Equatable, T: Hashable { public let from: Vertex<T> public let to: Vertex<T> public let weight: Double? } extension Edge: CustomStringConvertible { public var description: String { get { guard let unwrappedWeight = weight else { return "\(from.description) -> \(to.description)" } return "\(from.description) -(\(unwrappedWeight))-> \(to.description)" } } } extension Edge: Hashable { public var hashValue: Int { get { var string = "\(from.description)\(to.description)" if weight != nil { string.append("\(weight)") } return string.hashValue } } } public func == <T>(lhs: Edge<T>, rhs: Edge<T>) -> Bool { guard lhs.from == rhs.from else { return false } guard lhs.to == rhs.to else { return false } guard lhs.weight == rhs.weight else { return false } return true }
ed509765f1184be41bf7d6e508abfa9e
19.932203
82
0.5417
false
false
false
false
mitochrome/complex-gestures-demo
refs/heads/master
Roulette/Carthage/Checkouts/RxDataSources/Example/Example4_DifferentSectionAndItemTypes.swift
mit
3
// // MultipleSectionModelViewController.swift // RxDataSources // // Created by Segii Shulga on 4/26/16. // Copyright © 2016 kzaher. All rights reserved. // import UIKit import RxDataSources import RxCocoa import RxSwift // the trick is to just use enum for different section types class MultipleSectionModelViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let sections: [MultipleSectionModel] = [ .ImageProvidableSection(title: "Section 1", items: [.ImageSectionItem(image: UIImage(named: "settings")!, title: "General")]), .ToggleableSection(title: "Section 2", items: [.ToggleableSectionItem(title: "On", enabled: true)]), .StepperableSection(title: "Section 3", items: [.StepperSectionItem(title: "1")]) ] let dataSource = RxTableViewSectionedReloadDataSource<MultipleSectionModel>() skinTableViewDataSource(dataSource) Observable.just(sections) .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) } func skinTableViewDataSource(_ dataSource: RxTableViewSectionedReloadDataSource<MultipleSectionModel>) { dataSource.configureCell = { (dataSource, table, idxPath, _) in switch dataSource[idxPath] { case let .ImageSectionItem(image, title): let cell: ImageTitleTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.titleLabel.text = title cell.cellImageView.image = image return cell case let .StepperSectionItem(title): let cell: TitleSteperTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.titleLabel.text = title return cell case let .ToggleableSectionItem(title, enabled): let cell: TitleSwitchTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath) cell.switchControl.isOn = enabled cell.titleLabel.text = title return cell } } dataSource.titleForHeaderInSection = { dataSource, index in let section = dataSource[index] return section.title } } } enum MultipleSectionModel { case ImageProvidableSection(title: String, items: [SectionItem]) case ToggleableSection(title: String, items: [SectionItem]) case StepperableSection(title: String, items: [SectionItem]) } enum SectionItem { case ImageSectionItem(image: UIImage, title: String) case ToggleableSectionItem(title: String, enabled: Bool) case StepperSectionItem(title: String) } extension MultipleSectionModel: SectionModelType { typealias Item = SectionItem var items: [SectionItem] { switch self { case .ImageProvidableSection(title: _, items: let items): return items.map {$0} case .StepperableSection(title: _, items: let items): return items.map {$0} case .ToggleableSection(title: _, items: let items): return items.map {$0} } } init(original: MultipleSectionModel, items: [Item]) { switch original { case let .ImageProvidableSection(title: title, items: _): self = .ImageProvidableSection(title: title, items: items) case let .StepperableSection(title, _): self = .StepperableSection(title: title, items: items) case let .ToggleableSection(title, _): self = .ToggleableSection(title: title, items: items) } } } extension MultipleSectionModel { var title: String { switch self { case .ImageProvidableSection(title: let title, items: _): return title case .StepperableSection(title: let title, items: _): return title case .ToggleableSection(title: let title, items: _): return title } } }
761e6096aa0a71dda60373aa36d6013d
33.909091
108
0.621922
false
false
false
false
adrfer/swift
refs/heads/master
test/1_stdlib/DispatchTypes.swift
apache-2.0
4
// RUN: %target-swift-frontend -parse %s // REQUIRES: objc_interop import Dispatch func getAnyValue<T>(opt: T?) -> T { return opt! } // dispatch/io.h _ = dispatch_io_create(DISPATCH_IO_STREAM, 0, getAnyValue(nil), getAnyValue(nil)) dispatch_io_close(getAnyValue(nil), DISPATCH_IO_STOP) dispatch_io_set_interval(getAnyValue(nil), 0, DISPATCH_IO_STRICT_INTERVAL) // dispatch/queue.h _ = dispatch_queue_create("", DISPATCH_QUEUE_SERIAL) _ = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT) dispatch_set_target_queue(getAnyValue(nil), DISPATCH_TARGET_QUEUE_DEFAULT) _ = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) _ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) _ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) // QOS_CLASS_DEFAULT is not always available if #available(iOS 8.0, OSX 10.10, *) { _ = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0) } // dispatch/source.h dispatch_source_merge_data(getAnyValue(nil), DISPATCH_MACH_SEND_DEAD) dispatch_source_merge_data(getAnyValue(nil), DISPATCH_MEMORYPRESSURE_NORMAL) dispatch_source_merge_data(getAnyValue(nil), DISPATCH_PROC_EXIT) dispatch_source_merge_data(getAnyValue(nil), DISPATCH_PROC_SIGNAL) dispatch_source_merge_data(getAnyValue(nil), DISPATCH_VNODE_DELETE) dispatch_source_merge_data(getAnyValue(nil), DISPATCH_TIMER_STRICT) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_OR, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_SEND, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, 0, 0, getAnyValue(nil)) _ = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, 0, 0, getAnyValue(nil)) // dispatch/time.h _ = dispatch_time(DISPATCH_TIME_FOREVER, 0)
d8894759a3112273b3154c271a5e4789
47.808511
87
0.755885
false
false
false
false
MaartenBrijker/project
refs/heads/back
project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/FM Oscillator/AKFMOscillatorPresets.swift
apache-2.0
1
// // AKFMOscillatorPresets.swift // AudioKit // // Created by Aurelius Prochazka on 4/12/16. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Preset for the AKFMOscillator public extension AKFMOscillator { /// Stun Ray Preset public func presetStunRay() { baseFrequency = 200 carrierMultiplier = 90 modulatingMultiplier = 10 modulationIndex = 25 } /// Fog Horn Preset public func presetFogHorn() { baseFrequency = 25 carrierMultiplier = 10 modulatingMultiplier = 5 modulationIndex = 10 } /// Buzzer Preset public func presetBuzzer() { baseFrequency = 400 carrierMultiplier = 28 modulatingMultiplier = 0.5 modulationIndex = 100 } /// Spiral Preset public func presetSpiral() { baseFrequency = 5 carrierMultiplier = 280 modulatingMultiplier = 0.2 modulationIndex = 100 } /// Wobble Preset public func presetWobble() { baseFrequency = 20 carrierMultiplier = 10 modulatingMultiplier = 0.9 modulationIndex = 20 } }
cf1c4413de7a576be01de01101d9fbea
21.037037
51
0.603869
false
false
false
false
JGiola/swift
refs/heads/main
test/SILGen/switch_resilience.swift
apache-2.0
7
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift // RUN: %target-swift-emit-silgen -I %t %s | %FileCheck %s import resilient_struct // CHECK-LABEL: sil hidden [ossa] @$s17switch_resilience29resilientTupleEltCaseEnumTestyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[STACK_SLOT:%.*]] = alloc_stack $Enum // // CHECK: bb1: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[STACK_SLOT]] : $*Enum // CHECK: [[STACK_SLOT_COPY:%.*]] = alloc_stack [lexical] $(url: ResilientRef, void: ()), let, name "value" // CHECK: copy_addr [[VALUE]] to [initialization] [[STACK_SLOT_COPY]] // CHECK: cond_br {{%.*}}, bb2, bb3 // // CHECK: bb2: // CHECK: destroy_addr [[STACK_SLOT_COPY]] // CHECK-NEXT: dealloc_stack [[STACK_SLOT_COPY]] // CHECK-NEXT: destroy_addr [[VALUE]] // CHECK-NEXT: dealloc_stack [[STACK_SLOT]] // CHECK-NEXT: br bb4 // // CHECK: bb3: // CHECK-NEXT: destroy_addr [[STACK_SLOT_COPY]] // CHECK-NEXT: dealloc_stack [[STACK_SLOT_COPY]] // CHECK-NEXT: [[REPROJECT:%.*]] = tuple_element_addr [[VALUE]] // CHECK: destroy_addr [[REPROJECT]] // CHECK-NEXT: dealloc_stack [[STACK_SLOT]] // CHECK: br bb4 // // CHECK: } // end sil function '$s17switch_resilience29resilientTupleEltCaseEnumTestyyF' func resilientTupleEltCaseEnumTest() { enum Enum { case first(url: ResilientRef, void: Void) } func getEnum() -> Enum { let url = ResilientRef(r: Referent()) return .first(url: url, void: ()) } func getBool() -> Bool { return false } func urlUser(_ u: ResilientRef) {} func kraken() {} switch getEnum() { case let .first(value) where getBool(): urlUser(value.0) case .first: kraken() } }
384ea25c74d75a7ce4348485af442201
33.480769
155
0.650864
false
true
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/Room/ContextualMenu/RoomContextualMenuAction.swift
apache-2.0
1
/* Copyright 2019 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 @objc enum RoomContextualMenuAction: Int { case copy case reply case replyInThread case edit case more case resend case delete // MARK: - Properties var title: String { let title: String switch self { case .copy: title = VectorL10n.roomEventActionCopy case .reply: title = VectorL10n.roomEventActionReply case .replyInThread: title = VectorL10n.roomEventActionReplyInThread case .edit: title = VectorL10n.roomEventActionEdit case .more: title = VectorL10n.roomEventActionMore case .resend: title = VectorL10n.retry case .delete: title = VectorL10n.roomEventActionDelete } return title } var image: UIImage? { let image: UIImage? switch self { case .copy: image = Asset.Images.roomContextMenuCopy.image case .reply: image = Asset.Images.roomContextMenuReply.image case .replyInThread: image = Asset.Images.roomContextMenuThread.image case .edit: image = Asset.Images.roomContextMenuEdit.image case .more: image = Asset.Images.roomContextMenuMore.image case .resend: image = Asset.Images.roomContextMenuRetry.image case .delete: image = Asset.Images.roomContextMenuDelete.image default: image = nil } return image } }
c86e03965a0fb3423323dc77bab8619e
27.181818
73
0.623502
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILGen/guaranteed_closure_context.swift
apache-2.0
12
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s func use<T>(_: T) {} func escape(_ f: () -> ()) {} protocol P {} class C: P {} struct S {} // CHECK-LABEL: sil hidden [ossa] @$s26guaranteed_closure_context0A9_capturesyyF func guaranteed_captures() { // CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S } var mutableTrivial = S() // CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C } var mutableRetainable = C() // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var P } var mutableAddressOnly: P = C() // CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S let immutableTrivial = S() // CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C let immutableRetainable = C() // CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P let immutableAddressOnly: P = C() func captureEverything() { use((mutableTrivial, mutableRetainable, mutableAddressOnly, immutableTrivial, immutableRetainable, immutableAddressOnly)) } // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[B_MUTABLE_TRIVIAL_BOX:%.*]] = begin_borrow [[MUTABLE_TRIVIAL_BOX]] : ${ var S } // CHECK: [[B_MUTABLE_RETAINABLE_BOX:%.*]] = begin_borrow [[MUTABLE_RETAINABLE_BOX]] : ${ var C } // CHECK: [[B_MUTABLE_ADDRESS_ONLY_BOX:%.*]] = begin_borrow [[MUTABLE_ADDRESS_ONLY_BOX]] : ${ var P } // CHECK: [[B_IMMUTABLE_RETAINABLE:%.*]] = begin_borrow [[IMMUTABLE_RETAINABLE]] : $C // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[B_IMMUTABLE_AO_BOX:%.*]] = begin_borrow [[IMMUTABLE_AO_BOX]] : ${ var P } // CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@\$s26guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]] // CHECK: apply [[FN]]([[B_MUTABLE_TRIVIAL_BOX]], [[B_MUTABLE_RETAINABLE_BOX]], [[B_MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[B_IMMUTABLE_RETAINABLE]], [[B_IMMUTABLE_AO_BOX]]) captureEverything() // CHECK: destroy_value [[IMMUTABLE_AO_BOX]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // -- partial_apply still takes ownership of its arguments. // CHECK: [[FN:%.*]] = function_ref [[FN_NAME]] // CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_AO_BOX]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]] // CHECK: apply {{.*}}[[CONVERT]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK-NOT: destroy_value [[IMMUTABLE_AO_BOX]] escape(captureEverything) } // CHECK: sil private [ossa] [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var P }, S, @guaranteed C, @guaranteed { var P })
ec4199063e89d12a6f07d7815e6a141c
48.64
224
0.634435
false
false
false
false
gsempe/ADVOperation
refs/heads/master
Source/OperationCondition.swift
unlicense
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the fundamental logic relating to Operation conditions. */ import Foundation let OperationConditionKey = "OperationCondition" /** A protocol for defining conditions that must be satisfied in order for an operation to begin execution. */ protocol OperationCondition { /** The name of the condition. This is used in userInfo dictionaries of `.ConditionFailed` errors as the value of the `OperationConditionKey` key. */ static var name: String { get } /** Specifies whether multiple instances of the conditionalized operation may be executing simultaneously. */ static var isMutuallyExclusive: Bool { get } /** Some conditions may have the ability to satisfy the condition if another operation is executed first. Use this method to return an operation that (for example) asks for permission to perform the operation - parameter operation: The `Operation` to which the Condition has been added. - returns: An `NSOperation`, if a dependency should be automatically added. Otherwise, `nil`. - note: Only a single operation may be returned as a dependency. If you find that you need to return multiple operations, then you should be expressing that as multiple conditions. Alternatively, you could return a single `GroupOperation` that executes multiple operations internally. */ func dependencyForOperation(operation: Operation) -> NSOperation? /// Evaluate the condition, to see if it has been satisfied or not. func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) } /** An enum to indicate whether an `OperationCondition` was satisfied, or if it failed with an error. */ enum OperationConditionResult { case Satisfied case Failed(NSError) var error: NSError? { if case .Failed(let error) = self { return error } return nil } } // MARK: Evaluate Conditions struct OperationConditionEvaluator { static func evaluate(conditions: [OperationCondition], operation: Operation, completion: [NSError] -> Void) { // Check conditions. let conditionGroup = dispatch_group_create() var results = [OperationConditionResult?](count: conditions.count, repeatedValue: nil) // Ask each condition to evaluate and store its result in the "results" array. for (index, condition) in conditions.enumerate() { dispatch_group_enter(conditionGroup) condition.evaluateForOperation(operation) { result in results[index] = result dispatch_group_leave(conditionGroup) } } // After all the conditions have evaluated, this block will execute. dispatch_group_notify(conditionGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { // Aggregate the errors that occurred, in order. var failures = results.flatMap { $0?.error } /* If any of the conditions caused this operation to be cancelled, check for that. */ if operation.cancelled { failures.append(NSError(code: .ConditionFailed)) } completion(failures) } } }
ab59a7097362a68221fc0694f53a0be1
34.979798
113
0.653004
false
false
false
false
CodaFi/swift
refs/heads/main
test/Interpreter/SDK/objc_dynamic_lookup.swift
apache-2.0
41
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation // Dynamic subscripting of NSArray, dynamic method dispatch // CHECK: Optional("3") var array : AnyObject = [1, 2, 3, 4, 5] as NSArray print((array[2] as AnyObject).description) // Dynamic subscripting on an array using an object (fails) // CHECK: NSArray subscript with an object fails var optVal1 = array["Hello" as NSString] if optVal1 != nil { print(((optVal1!)! as AnyObject).description) } else { print("NSArray subscript with an object fails") } // Dynamic subscripting of NSDictionary, dynamic method dispatch // CHECK: Optional("2") var nsdict : NSDictionary = ["Hello" : 1, "World" : 2] var dict : AnyObject = nsdict print(((dict["World" as NSString]!)! as AnyObject).description) // Dynamic subscripting on a dictionary using an index (fails) // CHECK: NSDictionary subscript with an index fails var optVal2 = dict[1] if optVal2 != nil { print((optVal2! as AnyObject).description) } else { print("NSDictionary subscript with an index fails") }
7694005c178de62b4252677a75799f27
30.285714
64
0.717808
false
false
false
false
seanoshea/computer-science-in-swift
refs/heads/master
computer-science-in-swift/LinkedList.swift
mit
1
// Copyright (c) 2015-2016 Sean O'Shea. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation class LinkedListNode { var data:Int = 0 var next:LinkedListNode? } class LinkedList: NSObject { var head:LinkedListNode? var length:Int = 0 func add(_ data:Int) { let node = LinkedListNode() node.data = data var current:LinkedListNode if self.head == nil { self.head = node } else { current = self.head! while current.next != nil { current = current.next! } current.next = node } self.length = self.length + 1 } func item(_ index:Int) -> Int? { if index > -1 && index < self.length { var current:LinkedListNode = self.head! var i = 0 while i < index { current = current.next! i = i + 1 } return current.data } return nil } func remove(_ index:Int) -> Int? { if index > -1 && index < self.length { var current:LinkedListNode = self.head! var previous:LinkedListNode = LinkedListNode() var i = 0 if index == 0 { self.head = current.next } else { while i < index { previous = current current = current.next! i = i + 1 } previous.next = current.next } self.length = self.length - 1 return current.data } else { return nil } } func size() -> Int { return self.length } func toArray() -> [Int] { var result = [Int]() for i in 0..<self.length { result.append(self.item(i)!) } return result } func clear() { for i in 0..<self.length { _ = self.remove(i) } self.head = nil self.length = 0 } }
90453a5756823796042dc1760543f1ff
29.221154
80
0.557747
false
false
false
false
DanielFulton/ImageLibraryTests
refs/heads/master
Pods/ImageLoader/ImageLoader/Loader.swift
mit
1
// // Loader.swift // ImageLoader // // Created by Hirohisa Kawasaki on 5/2/16. // Copyright © 2016 Hirohisa Kawasaki. All rights reserved. // import UIKit import Foundation /** Responsible for sending a request and receiving the response and calling blocks for the request. */ public class Loader { unowned let delegate: Manager let task: NSURLSessionDataTask var receivedData = NSMutableData() var blocks: [Block] = [] init (task: NSURLSessionDataTask, delegate: Manager) { self.task = task self.delegate = delegate resume() } var state: NSURLSessionTaskState { return task.state } public func completionHandler(completionHandler: CompletionHandler) -> Self { let identifier = (blocks.last?.identifier ?? 0) + 1 return self.completionHandler(identifier, completionHandler: completionHandler) } public func completionHandler(identifier: Int, completionHandler: CompletionHandler) -> Self { let block = Block(identifier: identifier, completionHandler: completionHandler) return appendBlock(block) } func appendBlock(block: Block) -> Self { blocks.append(block) return self } // MARK: task public func suspend() { task.suspend() } public func resume() { task.resume() } public func cancel() { task.cancel() } func remove(identifier: Int) { // needs to queue with sync blocks = blocks.filter{ $0.identifier != identifier } } func receive(data: NSData) { receivedData.appendData(data) } func complete(error: NSError?, completionHandler: () -> Void) { if let URL = task.originalRequest?.URL { if let error = error { failure(URL, error: error, completionHandler: completionHandler) return } dispatch_async(delegate.decompressingQueue) { [weak self] in guard let wSelf = self else { return } wSelf.success(URL, data: wSelf.receivedData, completionHandler: completionHandler) } } } private func success(URL: NSURL, data: NSData, completionHandler: () -> Void) { let image = UIImage.decode(data) _toCache(URL, data: data) for block in blocks { block.completionHandler(URL, image, nil, .None) } blocks = [] completionHandler() } private func failure(URL: NSURL, error: NSError, completionHandler: () -> Void) { for block in blocks { block.completionHandler(URL, nil, error, .None) } blocks = [] completionHandler() } private func _toCache(URL: NSURL, data: NSData?) { if let data = data { delegate.cache[URL] = data } } }
74a6474d9c29250623abf7ee9155685b
24.866071
98
0.597376
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/291-chain-statements.swift
apache-2.0
4
import sys; main { // Check that declaration of y and z is visible in main block scope int x = 1 => int y = 1 => int z = 1; trace(x, y, z); }
9184475c908f0b0a62cf76ffccd29603
16
71
0.517647
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
BeeFun/Pods/SwiftDate/Sources/SwiftDate/Supports/TimeStructures.swift
gpl-3.0
7
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation // MARK: - Weekday /// This define the weekdays for some functions. public enum WeekDay: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday /// Returns the name of the day given a specific locale. /// For example, for the `Friday` enum value, the en_AU locale would return "Friday" and fr_FR would return "samedi" /// /// - Parameter locale: locale of the output, omit to use the `defaultRegion`'s locale. /// - Returns: display name public func name(style: SymbolFormatStyle = .`default`, locale: LocaleConvertible = SwiftDate.defaultRegion.locale) -> String { let region = Region(calendar: SwiftDate.defaultRegion.calendar, zone: SwiftDate.defaultRegion.timeZone, locale: locale) let formatter = DateFormatter.sharedFormatter(forRegion: region, format: nil) let idx = (self.rawValue - 1) switch style { case .default: return formatter.weekdaySymbols[idx] case .defaultStandalone: return formatter.standaloneWeekdaySymbols[idx] case .short: return formatter.shortWeekdaySymbols[idx] case .standaloneShort: return formatter.shortStandaloneWeekdaySymbols[idx] case .veryShort: return formatter.veryShortWeekdaySymbols[idx] case .standaloneVeryShort: return formatter.veryShortStandaloneWeekdaySymbols[idx] } } /// Adds a number of days to the current weekday and returns the new weekday. /// /// - Parameter months: number of months to add /// - Returns: new month. public func add(days: Int) -> WeekDay { let normalized = days % 7 return WeekDay(rawValue: ((self.rawValue + normalized + 7 - 1) % 7) + 1)! } /// Subtracts a number of days from the current weekday and returns the new weekday. /// /// - Parameter months: number of days to subtract. May be negative, in which case it will be added /// - Returns: new weekday. public func subtract(days: Int) -> WeekDay { return add(days: -(days % 7)) } } // MARK: - Year public struct Year: CustomStringConvertible, Equatable { let year: Int public var description: String { return "\(self.year)" } /// Constructs a `Year` from the passed value. /// /// - Parameter year: year value. Can be negative. public init(_ year: Int) { self.year = year } /// Returns whether this year is a leap year /// /// - Returns: A boolean indicating whether this year is a leap year public func isLeap() -> Bool { return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0) } /// Returns the number of days in this year /// /// - Returns: The number of days in this year public func numberOfDays() -> Int { return self.isLeap() ? 366 : 365 } } // MARK: - Month /// Defines months in a year public enum Month: Int, CustomStringConvertible, Equatable { case january = 0, february, march, april, may, june, july, august, september, october, november, december public var description: String { return self.name() } /// Returns the name of the month given a specific locale. /// For example, for the `January` enum value, the en_AU locale would return "January" and fr_FR would return "janvier" /// /// - Parameter locale: locale of the output, omit to use the `defaultRegion`'s locale. /// - Returns: display name public func name(style: SymbolFormatStyle = .`default`, locale: LocaleConvertible = SwiftDate.defaultRegion.locale) -> String { let region = Region(calendar: SwiftDate.defaultRegion.calendar, zone: SwiftDate.defaultRegion.timeZone, locale: locale) let formatter = DateFormatter.sharedFormatter(forRegion: region, format: nil) switch style { case .default: return formatter.monthSymbols[self.rawValue] case .defaultStandalone: return formatter.standaloneMonthSymbols[self.rawValue] case .short: return formatter.shortMonthSymbols[self.rawValue] case .standaloneShort: return formatter.shortStandaloneMonthSymbols[self.rawValue] case .veryShort: return formatter.veryShortMonthSymbols[self.rawValue] case .standaloneVeryShort: return formatter.veryShortStandaloneMonthSymbols[self.rawValue] } } /// Adds a number of months to the current month and returns the new month. /// /// - Parameter months: number of months to add /// - Returns: new month. public func add(months: Int) -> Month { let normalized = months % 12 return Month(rawValue: (self.rawValue + normalized + 12) % 12)! } /// Subtracts a number of months from the current month and returns the new month. /// /// - Parameter months: number of months to subtract. May be negative, in which case it will be added /// - Returns: new month. public func subtract(months: Int) -> Month { return add(months: -(months % 12)) } /// Returns the number of days in a this month for a given year /// /// - Parameter year: reference year. /// - Returns: The number of days in this month. public func numberOfDays(year: Int) -> Int { switch self { case .february: return Year(year).isLeap() ? 29 : 28 case .april, .june, .september, .november: return 30 default: return 31 } } }
1314e65d4daeaf3c347bb163fb10dea9
34.184211
128
0.710172
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Braket/Braket_Paginator.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Braket { /// Searches for devices using the specified filters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func searchDevicesPaginator<Result>( _ input: SearchDevicesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, SearchDevicesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: searchDevices, tokenKey: \SearchDevicesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func searchDevicesPaginator( _ input: SearchDevicesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (SearchDevicesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: searchDevices, tokenKey: \SearchDevicesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Searches for tasks that match the specified filter values. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func searchQuantumTasksPaginator<Result>( _ input: SearchQuantumTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, SearchQuantumTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: searchQuantumTasks, tokenKey: \SearchQuantumTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func searchQuantumTasksPaginator( _ input: SearchQuantumTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (SearchQuantumTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: searchQuantumTasks, tokenKey: \SearchQuantumTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension Braket.SearchDevicesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Braket.SearchDevicesRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension Braket.SearchQuantumTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Braket.SearchQuantumTasksRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } }
cb294b8dfe1861ee4983f84565346f39
39.972028
168
0.63219
false
false
false
false
RobinFalko/Ubergang
refs/heads/master
Examples/TweenApp/Pods/Ubergang/Ubergang/Ease/Back.swift
apache-2.0
1
// // Back.swift // Ubergang // // Created by Robin Frielingsdorf on 07/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation open class Back: Ease { /** Back ease in. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeIn(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t let s = 1.70158 t/=d let postFix = t return c*(postFix)*t*((s+1)*t - s) + b } /** Back ease out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeOut(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t let s = 1.70158 t=t/d-1 let f = (s+1)*t + s return c*(t*t*f + 1) + b } /** Back ease in out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeInOut(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t var s = 1.70158 t/=d/2 if (t < 1) { s*=(1.525); return c/2*(t*t*(((s)+1)*t - s)) + b } t-=2 let postFix = t s*=(1.525) let f = (s+1)*t + s return c/2*(postFix*t*f + 2) + b } }
f307a8f2656619ecdd70a641ab666d8f
25.348485
85
0.52674
false
false
false
false
JGiola/swift
refs/heads/main
benchmark/single-source/StringWalk.swift
apache-2.0
10
//===--- StringWalk.swift -------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is manually generated from .gyb template and should not // be directly modified. Instead, make changes to StringWalk.swift.gyb and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// // // Test String iteration performance over a variety of workloads, languages, // and symbols. // import TestsUtils // // Helper functionality // @inline(never) func count_unicodeScalars(_ s: String.UnicodeScalarView) { var count = 0 for _ in s { count += 1 } blackHole(count) } @inline(never) func count_characters(_ s: String) { var count = 0 for _ in s { count += 1 } blackHole(count) } @inline(never) func count_unicodeScalars_rev( _ s: ReversedCollection<String.UnicodeScalarView> ) { var count = 0 for _ in s { count += 1 } blackHole(count) } @inline(never) func count_characters_rev( _ s: ReversedCollection<String> ) { var count = 0 for _ in s { count += 1 } blackHole(count) } // // Workloads // let ascii = "siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig" let emoji = "👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿" let utf16 = emoji + "the quick brown fox" + String(emoji.reversed()) let japanese = "今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。" let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。" let korean = "이번 업데이트에서는 강력하면서도 직관적인 Apple 플랫폼용 프로그래밍 언어인 Swift를 완벽히 개선하였습니다." let russian = "в чащах юга жил-был цитрус? да, но фальшивый экземпляр" let punctuated = "\u{201c}Hello\u{2010}world\u{2026}\u{201d}" let punctuatedJapanese = "\u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d}" // A workload that's mostly Latin characters, with occasional emoji // interspersed. Common for tweets. let tweet = "Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭" // // Benchmarks // // Pre-commit benchmark: simple scalar walk @inline(never) public func run_StringWalk(_ n: Int) { return run_StringWalk_ascii_unicodeScalars(n) } // Extended String benchmarks: let baseMultiplier = 250 let unicodeScalarsMultiplier = baseMultiplier let charactersMultiplier = baseMultiplier / 5 // An extended benchmark suite exercising finer-granularity behavior of our // Strings. public let benchmarks = [ BenchmarkInfo( name: "StringWalk", runFunction: run_StringWalk, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_ascii_unicodeScalars", runFunction: run_StringWalk_ascii_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_ascii_characters", runFunction: run_StringWalk_ascii_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_ascii_unicodeScalars", runFunction: run_CharIteration_ascii_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_ascii_unicodeScalars", runFunction: run_CharIndexing_ascii_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_ascii_unicodeScalars_Backwards", runFunction: run_StringWalk_ascii_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_ascii_characters_Backwards", runFunction: run_StringWalk_ascii_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_ascii_unicodeScalars_Backwards", runFunction: run_CharIteration_ascii_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_ascii_unicodeScalars_Backwards", runFunction: run_CharIndexing_ascii_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_utf16_unicodeScalars", runFunction: run_StringWalk_utf16_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_utf16_characters", runFunction: run_StringWalk_utf16_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_utf16_unicodeScalars", runFunction: run_CharIteration_utf16_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_utf16_unicodeScalars", runFunction: run_CharIndexing_utf16_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_utf16_unicodeScalars_Backwards", runFunction: run_StringWalk_utf16_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_utf16_characters_Backwards", runFunction: run_StringWalk_utf16_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_utf16_unicodeScalars_Backwards", runFunction: run_CharIteration_utf16_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_utf16_unicodeScalars_Backwards", runFunction: run_CharIndexing_utf16_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_tweet_unicodeScalars", runFunction: run_StringWalk_tweet_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_tweet_characters", runFunction: run_StringWalk_tweet_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_tweet_unicodeScalars", runFunction: run_CharIteration_tweet_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_tweet_unicodeScalars", runFunction: run_CharIndexing_tweet_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_tweet_unicodeScalars_Backwards", runFunction: run_StringWalk_tweet_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_tweet_characters_Backwards", runFunction: run_StringWalk_tweet_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_tweet_unicodeScalars_Backwards", runFunction: run_CharIteration_tweet_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_tweet_unicodeScalars_Backwards", runFunction: run_CharIndexing_tweet_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_japanese_unicodeScalars", runFunction: run_StringWalk_japanese_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_japanese_characters", runFunction: run_StringWalk_japanese_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_japanese_unicodeScalars", runFunction: run_CharIteration_japanese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_japanese_unicodeScalars", runFunction: run_CharIndexing_japanese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_japanese_unicodeScalars_Backwards", runFunction: run_StringWalk_japanese_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_japanese_characters_Backwards", runFunction: run_StringWalk_japanese_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_japanese_unicodeScalars_Backwards", runFunction: run_CharIteration_japanese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_japanese_unicodeScalars_Backwards", runFunction: run_CharIndexing_japanese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_chinese_unicodeScalars", runFunction: run_StringWalk_chinese_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_chinese_characters", runFunction: run_StringWalk_chinese_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_chinese_unicodeScalars", runFunction: run_CharIteration_chinese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_chinese_unicodeScalars", runFunction: run_CharIndexing_chinese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_chinese_unicodeScalars_Backwards", runFunction: run_StringWalk_chinese_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_chinese_characters_Backwards", runFunction: run_StringWalk_chinese_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_chinese_unicodeScalars_Backwards", runFunction: run_CharIteration_chinese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_chinese_unicodeScalars_Backwards", runFunction: run_CharIndexing_chinese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_korean_unicodeScalars", runFunction: run_StringWalk_korean_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_korean_characters", runFunction: run_StringWalk_korean_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_korean_unicodeScalars", runFunction: run_CharIteration_korean_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_korean_unicodeScalars", runFunction: run_CharIndexing_korean_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_korean_unicodeScalars_Backwards", runFunction: run_StringWalk_korean_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_korean_characters_Backwards", runFunction: run_StringWalk_korean_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_korean_unicodeScalars_Backwards", runFunction: run_CharIteration_korean_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_korean_unicodeScalars_Backwards", runFunction: run_CharIndexing_korean_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_russian_unicodeScalars", runFunction: run_StringWalk_russian_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_russian_characters", runFunction: run_StringWalk_russian_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_russian_unicodeScalars", runFunction: run_CharIteration_russian_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_russian_unicodeScalars", runFunction: run_CharIndexing_russian_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_russian_unicodeScalars_Backwards", runFunction: run_StringWalk_russian_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_russian_characters_Backwards", runFunction: run_StringWalk_russian_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_russian_unicodeScalars_Backwards", runFunction: run_CharIteration_russian_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_russian_unicodeScalars_Backwards", runFunction: run_CharIndexing_russian_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuated_unicodeScalars", runFunction: run_StringWalk_punctuated_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuated_characters", runFunction: run_StringWalk_punctuated_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_punctuated_unicodeScalars", runFunction: run_CharIteration_punctuated_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_punctuated_unicodeScalars", runFunction: run_CharIndexing_punctuated_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuated_unicodeScalars_Backwards", runFunction: run_StringWalk_punctuated_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuated_characters_Backwards", runFunction: run_StringWalk_punctuated_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_punctuated_unicodeScalars_Backwards", runFunction: run_CharIteration_punctuated_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_punctuated_unicodeScalars_Backwards", runFunction: run_CharIndexing_punctuated_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuatedJapanese_unicodeScalars", runFunction: run_StringWalk_punctuatedJapanese_unicodeScalars, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuatedJapanese_characters", runFunction: run_StringWalk_punctuatedJapanese_characters, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_punctuatedJapanese_unicodeScalars", runFunction: run_CharIteration_punctuatedJapanese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_punctuatedJapanese_unicodeScalars", runFunction: run_CharIndexing_punctuatedJapanese_unicodeScalars, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuatedJapanese_unicodeScalars_Backwards", runFunction: run_StringWalk_punctuatedJapanese_unicodeScalars_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "StringWalk_punctuatedJapanese_characters_Backwards", runFunction: run_StringWalk_punctuatedJapanese_characters_Backwards, tags: [.api, .String, .skip], legacyFactor: 40), BenchmarkInfo( name: "CharIteration_punctuatedJapanese_unicodeScalars_Backwards", runFunction: run_CharIteration_punctuatedJapanese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), BenchmarkInfo( name: "CharIndexing_punctuatedJapanese_unicodeScalars_Backwards", runFunction: run_CharIndexing_punctuatedJapanese_unicodeScalars_Backwards, tags: [.validation, .api, .String], legacyFactor: 40), ] @inline(never) public func run_StringWalk_ascii_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(ascii.unicodeScalars) } } @inline(never) public func run_StringWalk_ascii_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(ascii.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_ascii_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(ascii) } } @inline(never) public func run_StringWalk_ascii_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(ascii.reversed()) } } let asciiCharacters = Array(ascii) @inline(never) public func run_CharIteration_ascii_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in asciiCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_ascii_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in asciiCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_ascii_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in asciiCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_ascii_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in asciiCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_utf16_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(utf16.unicodeScalars) } } @inline(never) public func run_StringWalk_utf16_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(utf16.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_utf16_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(utf16) } } @inline(never) public func run_StringWalk_utf16_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(utf16.reversed()) } } let utf16Characters = Array(utf16) @inline(never) public func run_CharIteration_utf16_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in utf16Characters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_utf16_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in utf16Characters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_utf16_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in utf16Characters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_utf16_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in utf16Characters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_tweet_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(tweet.unicodeScalars) } } @inline(never) public func run_StringWalk_tweet_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(tweet.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_tweet_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(tweet) } } @inline(never) public func run_StringWalk_tweet_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(tweet.reversed()) } } let tweetCharacters = Array(tweet) @inline(never) public func run_CharIteration_tweet_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in tweetCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_tweet_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in tweetCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_tweet_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in tweetCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_tweet_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in tweetCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_japanese_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(japanese.unicodeScalars) } } @inline(never) public func run_StringWalk_japanese_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(japanese.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_japanese_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(japanese) } } @inline(never) public func run_StringWalk_japanese_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(japanese.reversed()) } } let japaneseCharacters = Array(japanese) @inline(never) public func run_CharIteration_japanese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in japaneseCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_japanese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in japaneseCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_japanese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in japaneseCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_japanese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in japaneseCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_chinese_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(chinese.unicodeScalars) } } @inline(never) public func run_StringWalk_chinese_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(chinese.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_chinese_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(chinese) } } @inline(never) public func run_StringWalk_chinese_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(chinese.reversed()) } } let chineseCharacters = Array(chinese) @inline(never) public func run_CharIteration_chinese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in chineseCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_chinese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in chineseCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_chinese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in chineseCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_chinese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in chineseCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_korean_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(korean.unicodeScalars) } } @inline(never) public func run_StringWalk_korean_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(korean.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_korean_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(korean) } } @inline(never) public func run_StringWalk_korean_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(korean.reversed()) } } let koreanCharacters = Array(korean) @inline(never) public func run_CharIteration_korean_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in koreanCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_korean_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in koreanCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_korean_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in koreanCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_korean_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in koreanCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_russian_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(russian.unicodeScalars) } } @inline(never) public func run_StringWalk_russian_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(russian.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_russian_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(russian) } } @inline(never) public func run_StringWalk_russian_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(russian.reversed()) } } let russianCharacters = Array(russian) @inline(never) public func run_CharIteration_russian_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in russianCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_russian_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in russianCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_russian_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in russianCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_russian_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in russianCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_punctuated_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(punctuated.unicodeScalars) } } @inline(never) public func run_StringWalk_punctuated_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(punctuated.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_punctuated_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(punctuated) } } @inline(never) public func run_StringWalk_punctuated_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(punctuated.reversed()) } } let punctuatedCharacters = Array(punctuated) @inline(never) public func run_CharIteration_punctuated_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_punctuated_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_punctuated_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_punctuated_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_StringWalk_punctuatedJapanese_unicodeScalars(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars(punctuatedJapanese.unicodeScalars) } } @inline(never) public func run_StringWalk_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) { for _ in 1...unicodeScalarsMultiplier*n { count_unicodeScalars_rev(punctuatedJapanese.unicodeScalars.reversed()) } } @inline(never) public func run_StringWalk_punctuatedJapanese_characters(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters(punctuatedJapanese) } } @inline(never) public func run_StringWalk_punctuatedJapanese_characters_Backwards(_ n: Int) { for _ in 1...charactersMultiplier*n { count_characters_rev(punctuatedJapanese.reversed()) } } let punctuatedJapaneseCharacters = Array(punctuatedJapanese) @inline(never) public func run_CharIteration_punctuatedJapanese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedJapaneseCharacters { for u in c.unicodeScalars { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIteration_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedJapaneseCharacters { for u in c.unicodeScalars.reversed() { count |= Int(u.value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_punctuatedJapanese_unicodeScalars(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedJapaneseCharacters { let s = c.unicodeScalars for i in s.indices { count |= Int(s[i].value) } } } blackHole(count) } @inline(never) public func run_CharIndexing_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) { var count = 0 for _ in 1...unicodeScalarsMultiplier*n { for c in punctuatedJapaneseCharacters { let s = c.unicodeScalars for i in s.indices.reversed() { count |= Int(s[i].value) } } } blackHole(count) } // Local Variables: // eval: (read-only-mode 1) // End:
251b6104203d5c478a780a2658769073
24.246198
143
0.683522
false
false
false
false
HKMOpen/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Auth/AuthPhoneViewController.swift
mit
19
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class AuthPhoneViewController: AuthViewController, UITextFieldDelegate { // MARK: - // MARK: Private vars private var grayBackground: UIView! private var titleLabel: UILabel! private var countryButton: UIButton! private var phoneBackgroundView: UIImageView! private var countryCodeLabel: UILabel! private var phoneTextField: ABPhoneField! private var hintLabel: UILabel! private var navigationBarSeparator: UIView! // MARK: - // MARK: Public vars var currentIso: String = "" { didSet { phoneTextField.currentIso = currentIso let countryCode: String = ABPhoneField.callingCodeByCountryCode()[currentIso] as! String countryCodeLabel.text = "+\(countryCode)" countryButton.setTitle(ABPhoneField.countryNameByCountryCode()[currentIso] as? String, forState: UIControlState.Normal) } } // MARK: - // MARK: Constructors override init() { super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func loadView() { super.loadView() view.backgroundColor = UIColor.whiteColor() grayBackground = UIView() grayBackground.backgroundColor = UIColor.RGB(0xf2f2f2) view.addSubview(grayBackground) titleLabel = UILabel() titleLabel.backgroundColor = UIColor.clearColor() titleLabel.textColor = UIColor.blackColor() titleLabel.font = isIPad ? UIFont(name: "HelveticaNeue-Thin", size: 50.0) : UIFont(name: "HelveticaNeue-Light", size: 30.0) titleLabel.text = NSLocalizedString("AuthPhoneTitle", comment: "Title") grayBackground.addSubview(titleLabel) let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton") let countryImageHighlighted: UIImage! = UIImage(named: "ModernAuthCountryButtonHighlighted") countryButton = UIButton() countryButton.setBackgroundImage(countryImage.stretchableImageWithLeftCapWidth(Int(countryImage.size.width / 2), topCapHeight: 0), forState: UIControlState.Normal) countryButton.setBackgroundImage(countryImageHighlighted.stretchableImageWithLeftCapWidth(Int(countryImageHighlighted.size.width / 2), topCapHeight: 0), forState: UIControlState.Highlighted) countryButton.titleLabel?.font = UIFont.systemFontOfSize(20.0) countryButton.titleLabel?.textAlignment = NSTextAlignment.Left countryButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left countryButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) countryButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 14, bottom: 9, right: 14) countryButton.addTarget(self, action: Selector("showCountriesList"), forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(countryButton) let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground") phoneBackgroundView = UIImageView(image: phoneImage.stretchableImageWithLeftCapWidth(Int(phoneImage.size.width / 2), topCapHeight: 0)) view.addSubview(phoneBackgroundView) countryCodeLabel = UILabel() countryCodeLabel.font = UIFont.systemFontOfSize(20.0) countryCodeLabel.backgroundColor = UIColor.clearColor() countryCodeLabel.textAlignment = NSTextAlignment.Center phoneBackgroundView.addSubview(countryCodeLabel) phoneTextField = ABPhoneField() phoneTextField.font = UIFont.systemFontOfSize(20.0) phoneTextField.backgroundColor = UIColor.whiteColor() phoneTextField.placeholder = NSLocalizedString("AuthPhoneNumberHint", comment: "Hint") phoneTextField.keyboardType = UIKeyboardType.NumberPad; phoneTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center phoneTextField.delegate = self view.addSubview(phoneTextField) navigationBarSeparator = UIView() navigationBarSeparator.backgroundColor = UIColor.RGB(0xc8c7cc) view.addSubview(navigationBarSeparator) hintLabel = UILabel() hintLabel.font = UIFont.systemFontOfSize(17.0) hintLabel.textColor = UIColor.RGB(0x999999) hintLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping hintLabel.backgroundColor = UIColor.whiteColor() hintLabel.textAlignment = NSTextAlignment.Center hintLabel.contentMode = UIViewContentMode.Center hintLabel.numberOfLines = 0 hintLabel.text = NSLocalizedString("AuthPhoneHint", comment: "Hint") view.addSubview(hintLabel) var nextBarButton = UIBarButtonItem(title: NSLocalizedString("NavigationNext", comment: "Next Title"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("nextButtonPressed")) // TODO: Localize navigationItem.rightBarButtonItem = nextBarButton currentIso = phoneTextField.currentIso } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let screenSize = UIScreen.mainScreen().bounds.size let isWidescreen = screenSize.width > 320 || screenSize.height > 480 let isPortraint = screenSize.width < screenSize.height let bgSize = isIPad ? (isPortraint ? 304.0: 140) : (isWidescreen ? 131.0 : 90.0) grayBackground.frame = CGRect(x: 0.0, y: 0.0, width: screenSize.width, height: CGFloat(bgSize)) let padding = isIPad ? (isPortraint ? 48 : 20) : (20) titleLabel.sizeToFit() titleLabel.frame = CGRect(x: (screenSize.width - titleLabel.frame.size.width) / 2.0, y: grayBackground.frame.height - titleLabel.frame.size.height - CGFloat(padding), width: titleLabel.frame.size.width, height: titleLabel.frame.size.height) navigationBarSeparator.frame = CGRect(x: 0, y: grayBackground.bounds.size.height, width: screenSize.width, height: retinaPixel) let fieldWidth : CGFloat = isIPad ? (520) : (screenSize.width) let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton") countryButton.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: grayBackground.frame.origin.y + grayBackground.bounds.size.height, width: fieldWidth, height: countryImage.size.height) let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground") phoneBackgroundView.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: countryButton.frame.origin.y + 57, width: fieldWidth, height: phoneImage.size.height) let countryCodeLabelTopSpacing: CGFloat = 3.0 countryCodeLabel.frame = CGRect(x: 14, y: countryCodeLabelTopSpacing, width: 68, height: phoneBackgroundView.frame.size.height - countryCodeLabelTopSpacing) phoneTextField.frame = CGRect(x: (screenSize.width - fieldWidth) / 2 + 96.0, y: phoneBackgroundView.frame.origin.y + 1, width: fieldWidth - 96.0 - 10.0, height: phoneBackgroundView.frame.size.height - 2) let hintPadding : CGFloat = isIPad ? (isPortraint ? 460.0: 274.0) : (isWidescreen ? 274.0 : 214.0) let hintLabelSize = hintLabel.sizeThatFits(CGSize(width: 278.0, height: CGFloat.max)) hintLabel.frame = CGRect(x: (screenSize.width - hintLabelSize.width) / 2.0, y: hintPadding, width: hintLabelSize.width, height: hintLabelSize.height); } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) phoneTextField.becomeFirstResponder() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { Actor.trackAuthPhoneTypeWithValue(textField.text) return true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MainAppTheme.navigation.applyAuthStatusBar() Actor.trackAuthPhoneOpen() } // MARK: - // MARK: Methods func nextButtonPressed() { let action = "Request code" Actor.trackCodeRequest() let numberLength = count(phoneTextField.phoneNumber) as Int let numberRequiredLength: Int = (ABPhoneField.phoneMinLengthByCountryCode()[currentIso] as! String).toInt()! if (numberLength < numberRequiredLength) { var msg = NSLocalizedString("AuthPhoneTooShort", comment: "Too short error"); var alertView = UIAlertView(title: nil, message: msg, delegate: self, cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok")) alertView.show() Actor.trackActionError(action, withTag: "LOCAL_EMPTY_PHONE", withMessage: msg) } else { execute(Actor.requestStartPhoneAuthCommandWithEmail(jlong((phoneTextField.phoneNumber as NSString).longLongValue)), successBlock: { (val) -> () in Actor.trackActionSuccess(action) self.navigateToSms() }, failureBlock: { (val) -> () in var message = "Unknown error" var tag = "UNKNOWN" var canTryAgain = false if let exception = val as? ACRpcException { tag = exception.getTag() if (tag == "PHONE_NUMBER_INVALID") { message = NSLocalizedString("ErrorPhoneIncorrect", comment: "PHONE_NUMBER_INVALID error") } else { message = exception.getLocalizedMessage() } canTryAgain = exception.isCanTryAgain() } else if let exception = val as? JavaLangException { message = exception.getLocalizedMessage() canTryAgain = true } Actor.trackActionError(action, withTag: tag, withMessage: message) var alertView = UIAlertView(title: nil, message: message, delegate: self, cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok")) alertView.show() }) } } // MARK: - // MARK: Navigation func showCountriesList() { var countriesController = AuthCountriesViewController() countriesController.delegate = self countriesController.currentIso = currentIso var navigationController = AANavigationController(rootViewController: countriesController) presentViewController(navigationController, animated: true, completion: nil) } func navigateToSms() { var smsController = AuthSmsViewController() smsController.phoneNumber = "+\(phoneTextField.formattedPhoneNumber)" navigateNext(smsController, removeCurrent: false) } } // MARK: - // MARK: AAAuthCountriesController Delegate extension AuthPhoneViewController: AuthCountriesViewControllerDelegate { func countriesController(countriesController: AuthCountriesViewController, didChangeCurrentIso currentIso: String) { self.currentIso = currentIso } }
d64411632dfdd0c4a99d9ea4e94a5700
45.170635
248
0.655321
false
false
false
false
danthorpe/TaylorSource
refs/heads/development
Tests/Helpers.swift
mit
2
// // Created by Daniel Thorpe on 19/04/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import UIKit import YapDatabase import ValueCoding import YapDatabaseExtensions import TaylorSource class StubbedTableView: UITableView { override func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell(style: .Default, reuseIdentifier: id) } override func dequeueReusableHeaderFooterViewWithIdentifier(identifier: String) -> UITableViewHeaderFooterView? { return UITableViewHeaderFooterView(reuseIdentifier: identifier) } } class StubbedCollectionView: UICollectionView { override func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return UICollectionViewCell() } override func dequeueReusableSupplementaryViewOfKind(elementKind: String, withReuseIdentifier identifier: String, forIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return UICollectionReusableView() } } extension NSIndexPath { static var first: NSIndexPath { return NSIndexPath(forItem: 0, inSection: 0) } } // MARK: - Fake Models struct Person { enum Gender: Int { case Unknown = 1, Female, Male } let age: Int let gender: Gender let name: String } class PersonCoder: NSObject, NSCoding, CodingType { let value: Person required init(_ v: Person) { value = v } required init?(coder aDecoder: NSCoder) { if let gender = Person.Gender(rawValue: aDecoder.decodeIntegerForKey("gender")) { let age = aDecoder.decodeIntegerForKey("age") let name = aDecoder.decodeObjectForKey("name") as! String value = Person(age: age, gender: gender, name: name) } else { fatalError("Person.Gender not encoded correctly") } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.age, forKey: "age") aCoder.encodeInteger(value.gender.rawValue, forKey: "gender") aCoder.encodeObject(value.name, forKey: "name") } } extension Person: ValueCoding { typealias Coder = PersonCoder } extension Person.Gender: CustomStringConvertible { var description: String { switch self { case .Unknown: return "Unknown" case .Female: return "Female" case .Male: return "Male" } } } extension Person: Identifiable { var identifier: Identifier { return "\(name) - \(gender) - \(age)" } } extension Person: Persistable { static var collection: String { return "People" } } extension Person: CustomStringConvertible { var description: String { return "\(name), \(gender) \(age)" } } func generateRandomPeople(count: Int) -> [Person] { let possibleNames: [(Person.Gender, String)] = [ (.Male, "Tony"), (.Male, "Thor"), (.Male, "Bruce"), (.Male, "Steve"), (.Female, "Natasha"), (.Male, "Clint"), (.Unknown, "Ultron"), (.Male, "Nick"), (.Male, "James"), (.Male, "Pietro"), (.Female, "Wanda"), (.Unknown, "Jarvis"), (.Female, "Maria"), (.Male, "Sam"), (.Female, "Peggy") ] func createRandomPerson(_: Int) -> Person { let index = Int(arc4random_uniform(UInt32(possibleNames.endIndex))) let rando = possibleNames[index] let age = 25 + Int(arc4random_uniform(20)) return Person(age: age, gender: rando.0, name: rando.1) } return Array(0..<count).map(createRandomPerson) } func people(name: String, byGroup createGroup: (Person) -> String) -> YapDB.Fetch { let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in if collection == Person.collection { if let person = Person.decode(object) { return createGroup(person) } } return .None }) let sorting: YapDB.View.Sorting = .ByObject({ (_, group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in if let person1 = Person.decode(object1), let person2 = Person.decode(object2) { let comparison = person1.name.caseInsensitiveCompare(person2.name) switch comparison { case .OrderedSame: return person1.age < person2.age ? .OrderedAscending : .OrderedDescending default: return comparison } } return .OrderedSame }) let view = YapDB.View(name: name, grouping: grouping, sorting: sorting, collections: [Person.collection]) return .View(view) } func people(name: String, byGroup createGroup: (Person) -> String) -> YapDB.FetchConfiguration { return YapDB.FetchConfiguration(fetch: people(name, byGroup: createGroup)) } func people(name: String, byGroup createGroup: (Person) -> String) -> Configuration<Person> { return Configuration(fetch: people(name, byGroup: createGroup), itemMapper: Person.decode) }
8c38e0079c66ac5ad009ec8954dbf0e2
28.08427
184
0.637242
false
false
false
false
Jnosh/swift
refs/heads/master
benchmark/single-source/DictTest.swift
apache-2.0
11
//===--- DictTest.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 // //===----------------------------------------------------------------------===// import TestsUtils @inline(never) public func run_Dictionary(scale: Int) { let Input = [ // Text from http://en.wikipedia.org/wiki/Hash_table "hash", "table", "in", "computing", "a", "hash", "table", "also", "hash", "map", "is", "a", "data", "structure", "used", "to", "implement", "an", "associative", "array", "a", "structure", "that", "can", "map", "keys", "to", "values", "a", "hash", "table", "uses", "a", "hash", "function", "to", "compute", "an", "index", "into", "an", "array", "of", "buckets", "or", "slots", "from", "which", "the", "correct", "value", "can", "be", "found", "ideally", "the", "hash", "function", "will", "assign", "each", "key", "to", "a", "unique", "bucket", "but", "this", "situation", "is", "rarely", "achievable", "in", "practice", "usually", "some", "keys", "will", "hash", "to", "the", "same", "bucket", "instead", "most", "hash", "table", "designs", "assume", "that", "hash", "collisions", "different", "keys", "that", "are", "assigned", "by", "the", "hash", "function", "to", "the", "same", "bucket", "will", "occur", "and", "must", "be", "accommodated", "in", "some", "way", "in", "a", "well", "dimensioned", "hash", "table", "the", "average", "cost", "number", "of", "instructions", "for", "each", "lookup", "is", "independent", "of", "the", "number", "of", "elements", "stored", "in", "the", "table", "many", "hash", "table", "designs", "also", "allow", "arbitrary", "insertions", "and", "deletions", "of", "key", "value", "pairs", "at", "amortized", "constant", "average", "cost", "per", "operation", "in", "many", "situations", "hash", "tables", "turn", "out", "to", "be", "more", "efficient", "than", "search", "trees", "or", "any", "other", "table", "lookup", "structure", "for", "this", "reason", "they", "are", "widely", "used", "in", "many", "kinds", "of", "computer", "software", "particularly", "for", "associative", "arrays", "database", "indexing", "caches", "and", "sets", "hashing", "the", "idea", "of", "hashing", "is", "to", "distribute", "the", "entries", "key", "value", "pairs", "across", "an", "array", "of", "buckets", "given", "a", "key", "the", "algorithm", "computes", "an", "index", "that", "suggests", "where", "the", "entry", "can", "be", "found", "index", "f", "key", "array", "size", "often", "this", "is", "done", "in", "two", "steps", "hash", "hashfunc", "key", "index", "hash", "array", "size", "in", "this", "method", "the", "hash", "is", "independent", "of", "the", "array", "size", "and", "it", "is", "then", "reduced", "to", "an", "index", "a", "number", "between", "and", "array", "size", "using", "the", "modulus", "operator", "in", "the", "case", "that", "the", "array", "size", "is", "a", "power", "of", "two", "the", "remainder", "operation", "is", "reduced", "to", "masking", "which", "improves", "speed", "but", "can", "increase", "problems", "with", "a", "poor", "hash", "function", "choosing", "a", "good", "hash", "function", "a", "good", "hash", "function", "and", "implementation", "algorithm", "are", "essential", "for", "good", "hash", "table", "performance", "but", "may", "be", "difficult", "to", "achieve", "a", "basic", "requirement", "is", "that", "the", "function", "should", "provide", "a", "uniform", "distribution", "of", "hash", "values", "a", "non", "uniform", "distribution", "increases", "the", "number", "of", "collisions", "and", "the", "cost", "of", "resolving", "them", "uniformity", "is", "sometimes", "difficult", "to", "ensure", "by", "design", "but", "may", "be", "evaluated", "empirically", "using", "statistical", "tests", "e", "g", "a", "pearson", "s", "chi", "squared", "test", "for", "discrete", "uniform", "distributions", "the", "distribution", "needs", "to", "be", "uniform", "only", "for", "table", "sizes", "that", "occur", "in", "the", "application", "in", "particular", "if", "one", "uses", "dynamic", "resizing", "with", "exact", "doubling", "and", "halving", "of", "the", "table", "size", "s", "then", "the", "hash", "function", "needs", "to", "be", "uniform", "only", "when", "s", "is", "a", "power", "of", "two", "on", "the", "other", "hand", "some", "hashing", "algorithms", "provide", "uniform", "hashes", "only", "when", "s", "is", "a", "prime", "number", "for", "open", "addressing", "schemes", "the", "hash", "function", "should", "also", "avoid", "clustering", "the", "mapping", "of", "two", "or", "more", "keys", "to", "consecutive", "slots", "such", "clustering", "may", "cause", "the", "lookup", "cost", "to", "skyrocket", "even", "if", "the", "load", "factor", "is", "low", "and", "collisions", "are", "infrequent", "the", "popular", "multiplicative", "hash", "3", "is", "claimed", "to", "have", "particularly", "poor", "clustering", "behavior", "cryptographic", "hash", "functions", "are", "believed", "to", "provide", "good", "hash", "functions", "for", "any", "table", "size", "s", "either", "by", "modulo", "reduction", "or", "by", "bit", "masking", "they", "may", "also", "be", "appropriate", "if", "there", "is", "a", "risk", "of", "malicious", "users", "trying", "to", "sabotage", "a", "network", "service", "by", "submitting", "requests", "designed", "to", "generate", "a", "large", "number", "of", "collisions", "in", "the", "server", "s", "hash", "tables", "however", "the", "risk", "of", "sabotage", "can", "also", "be", "avoided", "by", "cheaper", "methods", "such", "as", "applying", "a", "secret", "salt", "to", "the", "data", "or", "using", "a", "universal", "hash", "function", "perfect", "hash", "function", "if", "all", "keys", "are", "known", "ahead", "of", "time", "a", "perfect", "hash", "function", "can", "be", "used", "to", "create", "a", "perfect", "hash", "table", "that", "has", "no", "collisions", "if", "minimal", "perfect", "hashing", "is", "used", "every", "location", "in", "the", "hash", "table", "can", "be", "used", "as", "well", "perfect", "hashing", "allows", "for", "constant", "time", "lookups", "in", "the", "worst", "case", "this", "is", "in", "contrast", "to", "most", "chaining", "and", "open", "addressing", "methods", "where", "the", "time", "for", "lookup", "is", "low", "on", "average", "but", "may", "be", "very", "large", "proportional", "to", "the", "number", "of", "entries", "for", "some", "sets", "of", "keys" ] var Dict: Dictionary<String, Bool> = [:] let N = 5*scale // Check performance of filling the dictionary: for _ in 1...N { Dict = [:] for word in Input { Dict[word] = true } } CheckResults(Dict.count == 270) // Check performance of searching in the dictionary: // Fill the dictionary with words from the first half of the text Dict = [:] for i in 0 ..< Input.count/2 { let word = Input[i] Dict[word] = true } // Count number of words from the first half in the entire text var count = 0 for _ in 1...N { for word in Input { if Dict[word] != nil { count += 1 } } } CheckResults(count == N*541) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } var hashValue: Int { return value.hashValue } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_DictionaryOfObjects(scale: Int) { let Input = [ // Text from http://en.wikipedia.org/wiki/Hash_table "hash", "table", "in", "computing", "a", "hash", "table", "also", "hash", "map", "is", "a", "data", "structure", "used", "to", "implement", "an", "associative", "array", "a", "structure", "that", "can", "map", "keys", "to", "values", "a", "hash", "table", "uses", "a", "hash", "function", "to", "compute", "an", "index", "into", "an", "array", "of", "buckets", "or", "slots", "from", "which", "the", "correct", "value", "can", "be", "found", "ideally", "the", "hash", "function", "will", "assign", "each", "key", "to", "a", "unique", "bucket", "but", "this", "situation", "is", "rarely", "achievable", "in", "practice", "usually", "some", "keys", "will", "hash", "to", "the", "same", "bucket", "instead", "most", "hash", "table", "designs", "assume", "that", "hash", "collisions", "different", "keys", "that", "are", "assigned", "by", "the", "hash", "function", "to", "the", "same", "bucket", "will", "occur", "and", "must", "be", "accommodated", "in", "some", "way", "in", "a", "well", "dimensioned", "hash", "table", "the", "average", "cost", "number", "of", "instructions", "for", "each", "lookup", "is", "independent", "of", "the", "number", "of", "elements", "stored", "in", "the", "table", "many", "hash", "table", "designs", "also", "allow", "arbitrary", "insertions", "and", "deletions", "of", "key", "value", "pairs", "at", "amortized", "constant", "average", "cost", "per", "operation", "in", "many", "situations", "hash", "tables", "turn", "out", "to", "be", "more", "efficient", "than", "search", "trees", "or", "any", "other", "table", "lookup", "structure", "for", "this", "reason", "they", "are", "widely", "used", "in", "many", "kinds", "of", "computer", "software", "particularly", "for", "associative", "arrays", "database", "indexing", "caches", "and", "sets", "hashing", "the", "idea", "of", "hashing", "is", "to", "distribute", "the", "entries", "key", "value", "pairs", "across", "an", "array", "of", "buckets", "given", "a", "key", "the", "algorithm", "computes", "an", "index", "that", "suggests", "where", "the", "entry", "can", "be", "found", "index", "f", "key", "array", "size", "often", "this", "is", "done", "in", "two", "steps", "hash", "hashfunc", "key", "index", "hash", "array", "size", "in", "this", "method", "the", "hash", "is", "independent", "of", "the", "array", "size", "and", "it", "is", "then", "reduced", "to", "an", "index", "a", "number", "between", "and", "array", "size", "using", "the", "modulus", "operator", "in", "the", "case", "that", "the", "array", "size", "is", "a", "power", "of", "two", "the", "remainder", "operation", "is", "reduced", "to", "masking", "which", "improves", "speed", "but", "can", "increase", "problems", "with", "a", "poor", "hash", "function", "choosing", "a", "good", "hash", "function", "a", "good", "hash", "function", "and", "implementation", "algorithm", "are", "essential", "for", "good", "hash", "table", "performance", "but", "may", "be", "difficult", "to", "achieve", "a", "basic", "requirement", "is", "that", "the", "function", "should", "provide", "a", "uniform", "distribution", "of", "hash", "values", "a", "non", "uniform", "distribution", "increases", "the", "number", "of", "collisions", "and", "the", "cost", "of", "resolving", "them", "uniformity", "is", "sometimes", "difficult", "to", "ensure", "by", "design", "but", "may", "be", "evaluated", "empirically", "using", "statistical", "tests", "e", "g", "a", "pearson", "s", "chi", "squared", "test", "for", "discrete", "uniform", "distributions", "the", "distribution", "needs", "to", "be", "uniform", "only", "for", "table", "sizes", "that", "occur", "in", "the", "application", "in", "particular", "if", "one", "uses", "dynamic", "resizing", "with", "exact", "doubling", "and", "halving", "of", "the", "table", "size", "s", "then", "the", "hash", "function", "needs", "to", "be", "uniform", "only", "when", "s", "is", "a", "power", "of", "two", "on", "the", "other", "hand", "some", "hashing", "algorithms", "provide", "uniform", "hashes", "only", "when", "s", "is", "a", "prime", "number", "for", "open", "addressing", "schemes", "the", "hash", "function", "should", "also", "avoid", "clustering", "the", "mapping", "of", "two", "or", "more", "keys", "to", "consecutive", "slots", "such", "clustering", "may", "cause", "the", "lookup", "cost", "to", "skyrocket", "even", "if", "the", "load", "factor", "is", "low", "and", "collisions", "are", "infrequent", "the", "popular", "multiplicative", "hash", "3", "is", "claimed", "to", "have", "particularly", "poor", "clustering", "behavior", "cryptographic", "hash", "functions", "are", "believed", "to", "provide", "good", "hash", "functions", "for", "any", "table", "size", "s", "either", "by", "modulo", "reduction", "or", "by", "bit", "masking", "they", "may", "also", "be", "appropriate", "if", "there", "is", "a", "risk", "of", "malicious", "users", "trying", "to", "sabotage", "a", "network", "service", "by", "submitting", "requests", "designed", "to", "generate", "a", "large", "number", "of", "collisions", "in", "the", "server", "s", "hash", "tables", "however", "the", "risk", "of", "sabotage", "can", "also", "be", "avoided", "by", "cheaper", "methods", "such", "as", "applying", "a", "secret", "salt", "to", "the", "data", "or", "using", "a", "universal", "hash", "function", "perfect", "hash", "function", "if", "all", "keys", "are", "known", "ahead", "of", "time", "a", "perfect", "hash", "function", "can", "be", "used", "to", "create", "a", "perfect", "hash", "table", "that", "has", "no", "collisions", "if", "minimal", "perfect", "hashing", "is", "used", "every", "location", "in", "the", "hash", "table", "can", "be", "used", "as", "well", "perfect", "hashing", "allows", "for", "constant", "time", "lookups", "in", "the", "worst", "case", "this", "is", "in", "contrast", "to", "most", "chaining", "and", "open", "addressing", "methods", "where", "the", "time", "for", "lookup", "is", "low", "on", "average", "but", "may", "be", "very", "large", "proportional", "to", "the", "number", "of", "entries", "for", "some", "sets", "of", "keys" ] var Dict: Dictionary<Box<String>, Box<Bool>> = [:] let N = 5*scale // Check performance of filling the dictionary: for _ in 1...N { Dict = [:] for word in Input { Dict[Box(word)] = Box(true) } } CheckResults(Dict.count == 270) // Check performance of searching in the dictionary: // Fill the dictionary with words from the first half of the text Dict = [:] for i in 0 ..< Input.count/2 { let word = Input[i] Dict[Box(word)] = Box(true) } // Count number of words from the first half in the entire text var count = 0 for _ in 1...N { for word in Input { if Dict[Box(word)] != nil { count += 1 } } } CheckResults(count == N*541) }
3234d0a8f816bd1fd738630549fe7025
52.37884
80
0.509207
false
false
false
false
iAugux/iBBS-Swift
refs/heads/master
iBBS/IBBSFavoriteContainerViewController.swift
mit
1
// // IBBSFavoriteContainerViewController.swift // iBBS // // Created by Augus on 5/5/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit import SwiftyJSON let postNewArticleInFavoriteVCSegueId = "favoriteControllerPresentEditingVC" class IBBSFavoriteContainerViewController: IBBSBaseViewController { override func viewDidLoad() { super.viewDidLoad() automaticPullingDownToRefresh() configureTableView() sendRequest() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) /** important: if present NavigationController's property of interactivePopGestureRecognizer is enable, we must set it to disable, otherwise if we call UIScreenEdgePanGestureRecognizer on present ViewController it will crash. */ // navigationController?.interactivePopGestureRecognizer?.delegate = nil navigationController?.interactivePopGestureRecognizer?.enabled = false } private func sendRequest() { let key = IBBSLoginKey() guard key.isValid else { IBBSContext.loginIfNeeded(alertMessage: PLEASE_LOGIN, completion: nil) return } APIClient.defaultClient.getFavoriteTopics(key.uid, token: key.token, success: { (json) -> Void in DEBUGPrint(json) if json == nil { IBBSToast.make(NO_DATA, delay: 0, interval: TIME_OF_TOAST_OF_NO_MORE_DATA) self.tableView.reloadData() return } if json.type == Type.Array { self.datasource = json.arrayValue self.tableView.reloadData() } }, failure: { (error) -> Void in DEBUGLog(error) IBBSToast.make(SERVER_ERROR, delay: 0, interval: TIME_OF_TOAST_OF_SERVER_ERROR) }) } private func configureTableView() { tableView.registerNib(UINib(nibName: String(IBBSTableViewCell), bundle: nil ), forCellReuseIdentifier: String(IBBSTableViewCell)) tableView.tableFooterView = UIView(frame: CGRectZero) tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func cornerActionButtonDidTap() { performPostNewArticleSegue(segueIdentifier: postNewArticleInFavoriteVCSegueId) } } extension IBBSFavoriteContainerViewController { // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasource?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(String(IBBSTableViewCell)) as? IBBSTableViewCell { let json = datasource[indexPath.row] cell.loadDataToCell(json) return cell } return UITableViewCell() } // MARK: - table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let json = datasource[indexPath.row] let vc = IBBSDetailViewController() vc.json = json vc.navigationController?.navigationBar.hidden = true navigationController?.pushViewController(vc, animated: true) } } extension IBBSFavoriteContainerViewController { override func automaticContentOffset() { gearRefreshControl.beginRefreshing() tableView.setContentOffset(CGPointMake(0, -125.0), animated: true) executeAfterDelay(0.5) { self.gearRefreshControl.endRefreshing() } } // MARK: - refresh override func refreshData() { super.refreshData() sendRequest() // be sure to stop refreshing while there is an error with network or something else let refreshInSeconds = 1.3 let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(refreshInSeconds * Double(NSEC_PER_SEC))); dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in self.page = 1 self.gearRefreshControl?.endRefreshing() } } }
1e957d5e51e84bd1cbd544c4623a4a6b
31.384615
137
0.629454
false
false
false
false
JosephNK/SwiftyIamport
refs/heads/master
SwiftyIamportDemo/Controller/WKHtml5InicisViewController.swift
mit
1
// // WKHtml5InicisViewController.swift // SwiftyIamportDemo // // Created by JosephNK on 29/11/2018. // Copyright © 2018 JosephNK. All rights reserved. // import UIKit import SwiftyIamport import WebKit class WKHtml5InicisViewController: UIViewController { lazy var wkWebView: WKWebView = { var view = WKWebView() view.backgroundColor = UIColor.clear view.navigationDelegate = self return view }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(wkWebView) self.wkWebView.frame = self.view.bounds // 결제 환경 설정 IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme storeIdentifier: "imp68124833") // iamport 에서 부여받은 가맹점 식별코드 IAMPortPay.sharedInstance .setPGType(.html5_inicis) // PG사 타입 .setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용) .setPayMethod(.card) // 결제 형식 .setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정 .setRedirectUrl(nil) // m_redirect_url 주소 // 결제 정보 데이타 let parameters: IAMPortParameters = [ "merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))), "name": "결제테스트", "amount": "1004", "buyer_email": "[email protected]", "buyer_name": "구매자", "buyer_tel": "010-1234-5678", "buyer_addr": "서울특별시 강남구 삼성동", "buyer_postcode": "123-456", "custom_data": ["A1": 123, "B1": "Hello"] //"custom_data": "24" ] IAMPortPay.sharedInstance.setParameters(parameters).commit() // 결제 웹페이지(Local) 파일 호출 if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() { let request = URLRequest(url: url) self.wkWebView.load(request) } } } extension WKHtml5InicisViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let request = navigationAction.request IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in // Background Thread 처리 var resultData: [String: Any]? if let httpResponse = response as? HTTPURLResponse { let statusCode = httpResponse.statusCode switch statusCode { case 200: resultData = [ "isSuccess": "OK" ] break default: break } } return resultData }) { (pasingData) in // Main Thread 처리 } let result = IAMPortPay.sharedInstance.requestAction(for: request) decisionHandler(result ? .allow : .cancel) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과 IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in if error != nil { switch error! { case .custom(let reason): print("error: \(reason)") break } }else { print("OK") } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("didFail") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("didFailProvisionalNavigation \(error.localizedDescription)") } }
1b0f5cca3df18975753ad7e25dd6dd2d
34.008621
157
0.544447
false
false
false
false
slepcat/mint-lisp
refs/heads/master
mint-lisp/mintlisp_env.swift
apache-2.0
1
// // mintlisp_env.swift // mint-lisp // // Created by NemuNeko on 2015/08/03. // Copyright (c) 2015年 Taizo A. All rights reserved. // import Foundation class Env { var hash_table = [String: SExpr]() var ext_env: Env? init() { ext_env = nil } /* debug print deinit { if hash_table.count > 10 { print("deinit env, with \(hash_table.count) elements") } } */ func lookup(_ key : String) -> SExpr { if let value = hash_table[key] { return value } else { if let eenv = ext_env { return eenv.lookup(key) } else { print("Unbouded symbol", terminator: "\n") return MNull() } } } // todo: variable length of arguments func extended_env(_ symbols: [SExpr], values: [SExpr]) -> Env? { let _env = Env() _env.ext_env = self if symbols.count == values.count { for i in 0..<symbols.count { if let symbol = symbols[i] as? MSymbol { _env.define_variable(symbol.key, val: values[i]) } else { print("Unproper parameter values", terminator: "\n") return nil } } return _env } else if symbols.count == 1 { if let _ = symbols.last as? MNull { return _env } } print("Err. Number of Symbol and Value is unmatch.", terminator: "\n") return nil } func clone() -> Env { let cloned_env = Env() cloned_env.ext_env = self.ext_env?.clone() cloned_env.hash_table = self.hash_table return cloned_env } func define_variable(_ key: String, val: SExpr) -> Bool { if hash_table[key] == nil { hash_table[key] = val return true } else { return false } } func set_variable(_ key: String, val: SExpr) -> Bool { if hash_table[key] == nil { return false } else { hash_table[key] = val return true } } func define_variable_force(_ key: String, val: SExpr) -> Bool { hash_table[key] = val return true } } func global_environment() -> [String : SExpr] { var primitives = [String : SExpr]() ///// basic operators ///// primitives["+"] = Plus() primitives["-"] = Minus() primitives["*"] = Multiply() primitives["/"] = Divide() primitives["="] = isEqual() primitives[">"] = GreaterThan() primitives["<"] = SmallerThan() primitives[">="] = EqualOrGreaterThan() primitives["<="] = EqualOrSmallerThan() primitives["mod"] = Mod() primitives["and"] = And() primitives["or"] = Or() primitives["not"] = Not() primitives["pow"] = Power() primitives["floor"] = Floor() primitives["ceil"] = Ceil() primitives["round"] = Round() primitives["cos"] = Cos() primitives["sin"] = Sin() primitives["tan"] = Tan() primitives["asin"] = ArcSin() primitives["acos"] = ArcCos() primitives["atan"] = ArcTan() primitives["atan2"] = ArcTan2() primitives["sinh"] = Sinh() primitives["cosh"] = Cosh() primitives["tanh"] = Tanh() primitives["abs"] = Abs() primitives["sqrt"] = Sqrt() primitives["exp"] = Exp() primitives["log"] = Log() primitives["log10"] = Log10() primitives["max"] = Max() primitives["min"] = Min() primitives["random"] = Random() primitives["time"] = Time() primitives["pi"] = MDouble(_value: M_1_PI) ///// conscell management ///// primitives["cons"] = Cons() primitives["join"] = Join() primitives["car"] = Car() primitives["cdr"] = Cdr() primitives["caar"] = Caar() primitives["cadr"] = Cadr() primitives["cdar"] = Cdar() primitives["cddr"] = Cddr() primitives["caaar"] = Caaar() primitives["caadr"] = Caadr() primitives["caddr"] = Caddr() primitives["cdddr"] = Cdddr() primitives["cdaar"] = Cdaar() primitives["cddar"] = Cddar() primitives["cdadr"] = Cdadr() primitives["cadar"] = Cadar() primitives["null"] = MNull() ///// array managemetn ///// primitives["array"] = NewArray() primitives["at-index"] = ArrayAtIndex() primitives["append"] = AppendArray() primitives["joint"] = JointArray() primitives["remove-at-index"] = RemoveAtIndex() primitives["remove-last"] = RemoveLast() primitives["remove-all"] = RemoveAll() primitives["count"] = CountArray() //primitives["list"] = isEqual() //primitives["apply"] = isEqual() //primitives["map"] = isEqual() ///// Type Casting ///// primitives["cast-double"] = CastDouble() ///// 3D data objects ///// primitives["vec"] = Vec() primitives["vec.x"] = Vec_x() primitives["vec.y"] = Vec_y() primitives["vec.z"] = Vec_z() primitives["vex"] = Vex() primitives["vex.pos"] = Vex_Pos() primitives["vex.normal"] = Vex_Normal() primitives["vex.color"] = Vex_Color() primitives["color"] = Color() primitives["color.r"] = Color_r() primitives["color.g"] = Color_g() primitives["color.b"] = Color_b() primitives["color.a"] = Color_a() primitives["plane"] = Pln() primitives["plane.normal"] = Pln_normal() primitives["ln"] = Ln() primitives["ln.pos"] = Ln_Pos() primitives["ln.dir"] = Ln_Dir() primitives["ln-seg"] = LnSeg() primitives["poly"] = Poly() primitives["poly.vex-at-index"] = Poly_VexAtIndex() primitives["poly.vex-count"] = Poly_VexCount() ///// 3d primitives ///// primitives["cube"] = Cube() primitives["sphere"] = Sphere() primitives["cylinder"] = Cylinder() ///// 3d Transform ///// primitives["set-color"] = SetColor() primitives["union"] = Union() primitives["subtract"] = Subtract() primitives["intersect"] = Intersect() primitives["rotate"] = Rotate() primitives["rotate-axis"] = RotateAxis() primitives["move"] = Translate() primitives["scale"] = Scale() ///// 2d data objects ////// primitives["shape"] = Shp() ///// IO ///// primitives["print"] = Print() //primitives["display"] = Display() primitives["quit"] = Quit() return primitives }
150d197af219182ceaed114caba83d65
26.329167
78
0.52325
false
false
false
false
PandaCoderSchool/Job4Students
refs/heads/master
Jobs4Students/JobDetailsViewController.swift
gpl-2.0
1
// // JobDetailsViewController.swift // Jobs4Students // // Created by Dan Tong on 9/21/15. // Copyright © 2015 iOS Swift Course. All rights reserved. // import UIKit import MapKit class JobDetailsViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! @IBOutlet weak var jobDescription: UITextView! var selectedJob: PFObject? var localSearchRequest:MKLocalSearchRequest! var localSearch:MKLocalSearch! var localSearchResponse:MKLocalSearchResponse! var pointAnnotation:MKPointAnnotation! var pinAnnotationView:MKPinAnnotationView! override func viewDidLoad() { super.viewDidLoad() // Update Map localSearchRequest = MKLocalSearchRequest() localSearchRequest.naturalLanguageQuery = selectedJob!["contactAddress"] as? String localSearch = MKLocalSearch(request: localSearchRequest) localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in if localSearchResponse == nil{ let alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again") alert.show() return } //3 self.pointAnnotation = MKPointAnnotation() self.pointAnnotation.title = self.selectedJob!["contactAddress"] as? String self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude: localSearchResponse!.boundingRegion.center.longitude) self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil) self.map.centerCoordinate = self.pointAnnotation.coordinate self.map.addAnnotation(self.pinAnnotationView.annotation!) let latitude: CLLocationDegrees = localSearchResponse!.boundingRegion.center.latitude let longitue: CLLocationDegrees = localSearchResponse!.boundingRegion.center.longitude let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitue) let latDelta: CLLocationDegrees = 0.01 let lonDelta: CLLocationDegrees = 0.01 let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span) self.map.setRegion(region, animated: true) } // Update Job info self.title = selectedJob!["jobTitle"] as? String jobDescription.text = selectedJob!["jobDetails"] as! String } @IBAction func onShareJob(sender: UIBarButtonItem) { let textToShare = selectedJob!["jobDescription"] as! String // "Swift is awesome! Check out this website about it!" let contactAddress = self.selectedJob!["contactAddress"] as! String // if let myWebsite = NSURL(string: "http://www.codingexplorer.com/") // { let objectsToShare = [textToShare, contactAddress] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) self.presentViewController(activityVC, animated: true, completion: nil) // } } @IBAction func onApplyJob(sender: UIBarButtonItem) { } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
f80208a95eddc91fa6e7e9ba476fe184
34.84466
194
0.726436
false
false
false
false
KyoheiG3/ProtobufExample
refs/heads/master
ProtobufClient/ProtobufClient/ViewController.swift
mit
1
// // ViewController.swift // ProtobufClient // // Created by Kyohei Ito on 2016/11/19. // Copyright © 2016年 Kyohei Ito. All rights reserved. // import UIKit import RxSwift import RxCocoa import SwiftProtobuf import Protobuf private let stabJSON = "{\"id\":\"20\",\"name\":\"Swift\",\"books\":[{\"id\":\"10\",\"title\":\"Welcome to Swift\",\"author\":\"Apple Inc.\"}],\"keys\":{\"route\":\"66\"}}" class TableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var acceptLabel: UILabel! @IBOutlet weak var pathLabel: UILabel! @IBOutlet weak var dataLabel: UILabel! @IBOutlet weak var byteLabel: UILabel! fileprivate let requests = [ RequestInfo(api: .go, type: .json, path: "/"), RequestInfo(api: .go, type: .protobuf, path: "/"), RequestInfo(api: .go, type: .protobuf, path: "/stab"), RequestInfo(api: .swift, type: .json, path: "/"), RequestInfo(api: .swift, type: .protobuf, path: "/"), RequestInfo(api: .swift, type: .json, path: "/protobuf"), RequestInfo(api: .swift, type: .protobuf, path: "/json"), RequestInfo(api: .swift, type: .protobuf, path: "/stab"), ] fileprivate let disposeBag = DisposeBag() func data<T>(request: URLRequest) -> Observable<T> { guard request.url?.path != "/stab" else { self.typeLabel.text = "-" self.byteLabel.text = "-" self.typeLabel.text = "-" // return stab data. return .just(try! MyLibrary(json: stabJSON) as! T) } return URLSession.shared.rx.response(request: request) .observeOn(MainScheduler.instance) .map { [unowned self] (response, data) -> T in if 200 ..< 300 ~= response.statusCode { let contentType = response.allHeaderFields["Content-Type"] as? String let accept = request.allHTTPHeaderFields?["Accept"] self.byteLabel.text = "\(data)" self.typeLabel.text = contentType // This examples return serialized json string if json string needed. also return deserialized protobuf object if protobuf needed. if let type = contentType, type == "application/protobuf" { let library = try MyLibrary(protobuf: data) if accept == "application/json" { return try library.serializeJSON() as! T } else { return library as! T } } else { let json = String(bytes: data, encoding: .utf8) if accept == "application/protobuf" { return try MyLibrary(json: json!) as! T } else { return json as! T } } } else { throw RxCocoaURLError.httpRequestFailed(response: response, data: data) } } .do(onError: { [unowned self] _ in self.byteLabel.text = "-" self.typeLabel.text = "-" }) .catchError { error in .just(error as! T) } } func getRequest(url: String) -> URLRequest { let url = URL(string: url)! pathLabel.text = ":\(url.port!)\(url.path)" var request = URLRequest(url: url) request.httpMethod = "GET" return request } override func viewDidLoad() { super.viewDidLoad() tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return requests.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let info = requests[indexPath.row] cell.textLabel?.text = "\(info.api.port)\(info.path)" cell.detailTextLabel?.text = info.type.description return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let info = requests[indexPath.row] acceptLabel.text = info.type.description var request = getRequest(url: info.url) request.setValue(info.type.description, forHTTPHeaderField: "Accept") data(request: request) .single() .map { (data: CustomDebugStringConvertible) in data.debugDescription } .bindTo(dataLabel.rx.text) .addDisposableTo(disposeBag) } }
0f8c9487ce1da58d7c3844fc08ee7276
36.328947
172
0.547585
false
false
false
false
yunzixun/V2ex-Swift
refs/heads/master
Common/V2EXColor.swift
mit
1
// // V2EXColor.swift // V2ex-Swift // // Created by huangfeng on 1/11/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import KVOController func colorWith255RGB(_ r:CGFloat , g:CGFloat, b:CGFloat) ->UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 255) } func colorWith255RGBA(_ r:CGFloat , g:CGFloat, b:CGFloat,a:CGFloat) ->UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a/255) } func createImageWithColor(_ color:UIColor) -> UIImage{ return createImageWithColor(color, size: CGSize(width: 1, height: 1)) } func createImageWithColor(_ color:UIColor,size:CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); context?.setFillColor(color.cgColor); context?.fill(rect); let theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage!; } //使用协议 方便以后切换颜色配置文件、或者做主题配色之类乱七八糟产品经理最爱的功能 protocol V2EXColorProtocol{ var v2_backgroundColor: UIColor { get } var v2_navigationBarTintColor: UIColor { get } var v2_TopicListTitleColor : UIColor { get } var v2_TopicListUserNameColor : UIColor { get } var v2_TopicListDateColor : UIColor { get } var v2_LinkColor : UIColor { get } var v2_TextViewBackgroundColor: UIColor { get } var v2_CellWhiteBackgroundColor : UIColor { get } var v2_NodeBackgroundColor : UIColor { get } var v2_SeparatorColor : UIColor { get } var v2_LeftNodeBackgroundColor : UIColor { get } var v2_LeftNodeBackgroundHighLightedColor : UIColor { get } var v2_LeftNodeTintColor: UIColor { get } /// 小红点背景颜色 var v2_NoticePointColor : UIColor { get } var v2_ButtonBackgroundColor : UIColor { get } } class V2EXDefaultColor: NSObject,V2EXColorProtocol { static let sharedInstance = V2EXDefaultColor() fileprivate override init(){ super.init() } var v2_backgroundColor : UIColor{ get{ return colorWith255RGB(242, g: 243, b: 245); } } var v2_navigationBarTintColor : UIColor{ get{ return colorWith255RGB(102, g: 102, b: 102); } } var v2_TopicListTitleColor : UIColor{ get{ return colorWith255RGB(15, g: 15, b: 15); } } var v2_TopicListUserNameColor : UIColor{ get{ return colorWith255RGB(53, g: 53, b: 53); } } var v2_TopicListDateColor : UIColor{ get{ return colorWith255RGB(173, g: 173, b: 173); } } var v2_LinkColor : UIColor { get { return colorWith255RGB(119, g: 128, b: 135) } } var v2_TextViewBackgroundColor :UIColor { get { return colorWith255RGB(255, g: 255, b: 255) } } var v2_CellWhiteBackgroundColor :UIColor { get { return colorWith255RGB(255, g: 255, b: 255) } } var v2_NodeBackgroundColor : UIColor { get { return colorWith255RGB(242, g: 242, b: 242) } } var v2_SeparatorColor : UIColor { get { return colorWith255RGB(190, g: 190, b: 190) } } var v2_LeftNodeBackgroundColor : UIColor { get { return colorWith255RGBA(255, g: 255, b: 255, a: 76) } } var v2_LeftNodeBackgroundHighLightedColor : UIColor { get { return colorWith255RGBA(255, g: 255, b: 255, a: 56) } } var v2_LeftNodeTintColor : UIColor { get { return colorWith255RGBA(0, g: 0, b: 0, a: 140) } } var v2_NoticePointColor : UIColor { get { return colorWith255RGB(207, g: 70, b: 71) } } var v2_ButtonBackgroundColor : UIColor { get { return colorWith255RGB(85, g: 172, b: 238) } } } /// Dark Colors class V2EXDarkColor: NSObject,V2EXColorProtocol { static let sharedInstance = V2EXDarkColor() fileprivate override init(){ super.init() } var v2_backgroundColor : UIColor{ get{ return colorWith255RGB(32, g: 31, b: 35); } } var v2_navigationBarTintColor : UIColor{ get{ return colorWith255RGB(165, g: 165, b: 165); } } var v2_TopicListTitleColor : UIColor{ get{ return colorWith255RGB(145, g: 145, b: 145); } } var v2_TopicListUserNameColor : UIColor{ get{ return colorWith255RGB(125, g: 125, b: 125); } } var v2_TopicListDateColor : UIColor{ get{ return colorWith255RGB(100, g: 100, b: 100); } } var v2_LinkColor : UIColor { get { return colorWith255RGB(119, g: 128, b: 135) } } var v2_TextViewBackgroundColor :UIColor { get { return colorWith255RGB(35, g: 34, b: 38) } } var v2_CellWhiteBackgroundColor :UIColor { get { return colorWith255RGB(35, g: 34, b: 38) } } var v2_NodeBackgroundColor : UIColor { get { return colorWith255RGB(40, g: 40, b: 40) } } var v2_SeparatorColor : UIColor { get { return colorWith255RGB(46, g: 45, b: 49) } } var v2_LeftNodeBackgroundColor : UIColor { get { return colorWith255RGBA(255, g: 255, b: 255, a: 76) } } var v2_LeftNodeBackgroundHighLightedColor : UIColor { get { return colorWith255RGBA(255, g: 255, b: 255, a: 56) } } var v2_LeftNodeTintColor : UIColor { get { return colorWith255RGBA(0, g: 0, b: 0, a: 140) } } var v2_NoticePointColor : UIColor { get { return colorWith255RGB(207, g: 70, b: 71) } } var v2_ButtonBackgroundColor : UIColor { get { return colorWith255RGB(207, g: 70, b: 71) } } } class V2EXColor :NSObject { fileprivate static let STYLE_KEY = "styleKey" static let V2EXColorStyleDefault = "Default" static let V2EXColorStyleDark = "Dark" fileprivate static var _colors:V2EXColorProtocol? static var colors :V2EXColorProtocol { get{ if let c = V2EXColor._colors { return c } else{ if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault{ return V2EXDefaultColor.sharedInstance } else{ return V2EXDarkColor.sharedInstance } } } set{ V2EXColor._colors = newValue } } @objc dynamic var style:String static let sharedInstance = V2EXColor() fileprivate override init(){ if let style = V2EXSettings.sharedInstance[V2EXColor.STYLE_KEY] { self.style = style } else{ self.style = V2EXColor.V2EXColorStyleDefault } super.init() } func setStyleAndSave(_ style:String){ if self.style == style { return } if style == V2EXColor.V2EXColorStyleDefault { V2EXColor.colors = V2EXDefaultColor.sharedInstance } else{ V2EXColor.colors = V2EXDarkColor.sharedInstance } self.style = style V2EXSettings.sharedInstance[V2EXColor.STYLE_KEY] = style } } //MARK: - 主题更改时,自动执行 extension NSObject { fileprivate struct AssociatedKeys { static var thmemChanged = "thmemChanged" } /// 当前主题更改时、第一次设置时 自动调用的闭包 public typealias ThemeChangedClosure = @convention(block) (_ style:String) -> Void /// 自动调用的闭包 /// 设置时,会设置一个KVO监听,当V2Style.style更改时、第一次赋值时 会自动调用这个闭包 var themeChangedHandler:ThemeChangedClosure? { get { let closureObject: AnyObject? = objc_getAssociatedObject(self, &AssociatedKeys.thmemChanged) as AnyObject? guard closureObject != nil else{ return nil } let closure = unsafeBitCast(closureObject, to: ThemeChangedClosure.self) return closure } set{ guard let value = newValue else{ return } let dealObject: AnyObject = unsafeBitCast(value, to: AnyObject.self) objc_setAssociatedObject(self, &AssociatedKeys.thmemChanged,dealObject,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) //设置KVO监听 self.kvoController.observe(V2EXColor.sharedInstance, keyPath: "style", options: [.initial,.new] , block: {[weak self] (nav, color, change) -> Void in self?.themeChangedHandler?(V2EXColor.sharedInstance.style) } ) } } }
c1dbcc82010de1eb391f57943e48f295
25.619186
161
0.569619
false
false
false
false
OpenKitten/MongoKitten
refs/heads/master/6.0
Sources/MongoKitten/CollectionHelpers/Collection+Update.swift
mit
2
import NIO import MongoCore extension MongoCollection { public func updateOne( where query: Document, to document: Document ) -> EventLoopFuture<UpdateReply> { return pool.next(for: .basic).flatMap { connection in let request = UpdateCommand.UpdateRequest(where: query, to: document) let command = UpdateCommand(updates: [request], inCollection: self.name) return connection.executeCodable( command, namespace: self.database.commandNamespace, in: self.transaction, sessionId: self.sessionId ?? connection.implicitSessionId ) }.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop) } public func updateEncoded<E: Encodable>( where query: Document, to model: E ) -> EventLoopFuture<UpdateReply> { do { let document = try BSONEncoder().encode(model) return updateOne(where: query, to: document) } catch { return eventLoop.makeFailedFuture(error) } } public func updateOne<Query: MongoKittenQuery>( where query: Query, to document: Document ) -> EventLoopFuture<UpdateReply> { return updateOne( where: query.makeDocument(), to: document ) } public func updateEncoded<Query: MongoKittenQuery, E: Encodable>( where query: Query, to model: E ) -> EventLoopFuture<UpdateReply> { return updateEncoded( where: query.makeDocument(), to: model ) } public func updateMany( where query: Document, to document: Document ) -> EventLoopFuture<UpdateReply> { return pool.next(for: .basic).flatMap { connection in var request = UpdateCommand.UpdateRequest(where: query, to: document) request.multi = true let command = UpdateCommand(updates: [request], inCollection: self.name) return connection.executeCodable( command, namespace: self.database.commandNamespace, in: self.transaction, sessionId: self.sessionId ?? connection.implicitSessionId ) }.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop) } public func updateManyEncoded<E: Encodable>( where query: Document, to model: E ) -> EventLoopFuture<UpdateReply> { do { let document = try BSONEncoder().encode(model) return updateMany(where: query, to: document) } catch { return eventLoop.makeFailedFuture(error) } } public func updateMany<Query: MongoKittenQuery>( where query: Query, to document: Document ) -> EventLoopFuture<UpdateReply> { return updateMany( where: query.makeDocument(), to: document ) } public func updateManyEncoded<Query: MongoKittenQuery, E: Encodable>( where query: Query, to model: E ) -> EventLoopFuture<UpdateReply> { return updateManyEncoded( where: query.makeDocument(), to: model ) } public func updateMany( where query: Document, setting: Document?, unsetting: Document? ) -> EventLoopFuture<UpdateReply> { return pool.next(for: .basic).flatMap { connection in var request = UpdateCommand.UpdateRequest(where: query, setting: setting, unsetting: unsetting) request.multi = true let command = UpdateCommand(updates: [request], inCollection: self.name) return connection.executeCodable( command, namespace: self.database.commandNamespace, in: self.transaction, sessionId: self.sessionId ?? connection.implicitSessionId ) }.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop) } public func upsert(_ document: Document, where query: Document) -> EventLoopFuture<UpdateReply> { return pool.next(for: .basic).flatMap { connection in var request = UpdateCommand.UpdateRequest(where: query, to: document) request.multi = false request.upsert = true let command = UpdateCommand(updates: [request], inCollection: self.name) return connection.executeCodable( command, namespace: self.database.commandNamespace, in: self.transaction, sessionId: self.sessionId ?? connection.implicitSessionId ) }.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop) } public func upsertEncoded<E: Encodable>(_ model: E, where query: Document) -> EventLoopFuture<UpdateReply> { do { let document = try BSONEncoder().encode(model) return upsert(document, where: query) } catch { return eventLoop.makeFailedFuture(error) } } public func upsert<Query: MongoKittenQuery>(_ document: Document, where query: Query) -> EventLoopFuture<UpdateReply> { return upsert(document, where: query.makeDocument()) } public func upsertEncoded<Query: MongoKittenQuery, E: Encodable>(_ model: E, where query: Query) -> EventLoopFuture<UpdateReply> { return upsertEncoded(model, where: query.makeDocument()) } }
80708f2e799000bbc25545cf0e3543ac
34.322785
134
0.597205
false
false
false
false
zhaobin19918183/zhaobinCode
refs/heads/master
MyGame/MyGame/GameScene.swift
gpl-3.0
1
// // GameScene.swift // MyGame // // Created by Zhao.bin on 2016/12/21. // Copyright © 2016年 Zhao.bin. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { private var label : SKLabelNode? private var spinnyNode : SKShapeNode? override func didMove(to view: SKView) { // Get label node from scene and store it for use later self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode if let label = self.label { label.alpha = 0.0 label.run(SKAction.fadeIn(withDuration: 2.0)) } // Create shape node to use during mouse interaction let w = (self.size.width + self.size.height) * 0.05 self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3) if let spinnyNode = self.spinnyNode { spinnyNode.lineWidth = 2.5 spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1))) spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 0.5), SKAction.removeFromParent()])) } } func touchDown(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.green self.addChild(n) } } func touchMoved(toPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.blue self.addChild(n) } } func touchUp(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.red self.addChild(n) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let label = self.label { label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut") } for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } }
092ec39583decacd7b47c678ac1188ab
31.820225
107
0.57138
false
false
false
false
niw/meowatch
refs/heads/master
Meowatch WatchKit Extension/Meowatch.swift
mit
1
// // Meowatch.swift // Meowatch // // Created by Yoshimasa Niwa on 5/8/15. // Copyright (c) 2015 Yoshimasa Niwa. All rights reserved. // import Accounts import ImageIO import Twitter import UIKit import WatchKit extension UIImage { class func animatedImageWithData(data: NSData) -> UIImage? { if let source = CGImageSourceCreateWithData(data, nil) { let count = CGImageSourceGetCount(source); if count <= 1 { return UIImage(data: data) } else { var images: [UIImage] = [] var duration = 0.0 for index in 0..<count { if let cgImage = CGImageSourceCreateImageAtIndex(source, index, nil) { if let frameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? NSDictionary, gifProperties = frameProperties[kCGImagePropertyGIFDictionary as NSString] as? NSDictionary { if let unclampedDelayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as NSString] as? NSNumber { duration += unclampedDelayTime.doubleValue } else if let delayTime = gifProperties[kCGImagePropertyGIFDelayTime as NSString] as? NSNumber { duration += delayTime.doubleValue } } let image = UIImage(CGImage: cgImage, scale: WKInterfaceDevice.currentDevice().screenScale, orientation: UIImageOrientation.Up) images.append(image) } } return UIImage.animatedImageWithImages(images, duration: duration); } } else { return nil } } func optimizedAnimatedImage(fitSize: CGSize, maxFrame: Int) -> UIImage? { if let images = self.images { if CGSizeEqualToSize(self.size, fitSize) || CGSizeEqualToSize(fitSize, CGSizeZero) { return self; } let widthFactor = fitSize.width / self.size.width let heightFactor = fitSize.height / self.size.height let scaleFactor = min(widthFactor, heightFactor) let scaledSize = CGSizeMake(self.size.width * scaleFactor, self.size.height * scaleFactor) let increment: Int if (maxFrame > 0) { increment = images.count / maxFrame } else { increment = 0 } var scaledImages: [UIImage] = [] UIGraphicsBeginImageContextWithOptions(scaledSize, false, WKInterfaceDevice.currentDevice().screenScale) for var index = 0; index < images.count; index += increment { let image = images[index] image.drawInRect(CGRectMake(0.0, 0.0, scaledSize.width, scaledSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() if let data = UIImageJPEGRepresentation(newImage, 0.5), jpegImage = UIImage(data: data) { scaledImages.append(jpegImage) } } UIGraphicsEndImageContext(); return UIImage.animatedImageWithImages(scaledImages, duration:self.duration); } else { return self; } } } struct ArchivedAnimatedImage { let data: NSData let count: Int let duration: NSTimeInterval init(image: UIImage) { self.data = NSKeyedArchiver.archivedDataWithRootObject(image) if let count = image.images?.count { self.count = count } else { self.count = 1 } self.duration = image.duration } } struct AnimatedImageFetchResult { let originalData: NSData let archivedAniamtedImage: ArchivedAnimatedImage // Bluetooth 4.0 LE's data rate is, by measureing in stable environment, // about 420 Kbps and could be worser. private let bytesPerSeconds = 840 * 1024 / 8; func estimatedLoadingTime() -> Double { return Double(self.archivedAniamtedImage.data.length) / Double(self.bytesPerSeconds); } func formattedLodingSize() -> String { let kiloBytes = self.archivedAniamtedImage.data.length / 1024; let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle if let formattedString = formatter.stringFromNumber(NSNumber(integer: kiloBytes)) { return formattedString } else { return "\(kiloBytes)" } } } func fetchAnimatedImage(completion: (AnimatedImageFetchResult?) -> Void) { // FIXME: Find a feasible way to get cats from the internet. let theCatApiEndpoint = "http://thecatapi.com/api/images/get?format=src&type=gif" dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), { if let url = NSURL(string: theCatApiEndpoint), data = NSData(contentsOfURL: url), image = UIImage.animatedImageWithData(data)?.optimizedAnimatedImage(CGSizeMake(120.0, 120.0), maxFrame: 6) { let archivedAnimatedImage = ArchivedAnimatedImage(image: image) let fetchResult = AnimatedImageFetchResult(originalData: data, archivedAniamtedImage: archivedAnimatedImage) dispatch_async(dispatch_get_main_queue(), { completion(fetchResult) }) } else { dispatch_async(dispatch_get_main_queue(), { completion(nil) }) } }) } struct ProgressBarHelper { private let numberOfFrames = 40 private let cachedImageName = "ProgressBar" weak var progressBarImage: WKInterfaceImage? { didSet { self.progressBarImage?.setImageNamed(self.cachedImageName) self.progressBarImage?.stopAnimating() } } init() { if let image = progressBarAnimatedImage(self.numberOfFrames) { WKInterfaceDevice.currentDevice().addCachedImage(image, name: self.cachedImageName) } } // See https://developer.apple.com/watch/human-interface-guidelines/specifications/ private let progressBarColor = UIColor(red: 255.0/255.0, green: 230.0/255.0, blue: 32.0/255.0, alpha: 1.0) private func progressBarImageAtProgress(progress: Double) -> UIImage? { let progress = min(1.0, max(0.0, progress)) let barSize = CGSizeMake(WKInterfaceDevice.currentDevice().screenBounds.width - 12.0, 2.0) UIGraphicsBeginImageContextWithOptions(barSize, false, WKInterfaceDevice.currentDevice().screenScale) UIGraphicsGetCurrentContext() self.progressBarColor.setFill() UIBezierPath(roundedRect: CGRectMake(0.0, 0.0, ceil(barSize.width * CGFloat(progress)), barSize.height), cornerRadius: 1.0).fill() let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image } private func progressBarAnimatedImage(numberOfFrames: Int) -> UIImage? { var images: [UIImage] = [] for index in 0..<numberOfFrames { if let image = progressBarImageAtProgress(Double(index) / Double(numberOfFrames - 1)) { images.append(image) } else { return nil } } return UIImage.animatedImageWithImages(images, duration: 10.0) } func reset() { self.progressBarImage?.startAnimatingWithImagesInRange(NSMakeRange(0, 1), duration: 0.0, repeatCount: 1) } func startInDuration(duration: NSTimeInterval) { self.progressBarImage?.startAnimatingWithImagesInRange(NSMakeRange(0, self.numberOfFrames), duration: duration, repeatCount: 1) } } class RequestTag { } struct SocialAccount { let type: String private func serviceType() -> String? { switch self.type { case ACAccountTypeIdentifierTwitter: return SLServiceTypeTwitter case ACAccountTypeIdentifierFacebook: return SLServiceTypeFacebook case ACAccountTypeIdentifierSinaWeibo: return SLServiceTypeSinaWeibo case ACAccountTypeIdentifierTencentWeibo: return SLServiceTypeTencentWeibo default: return nil } } func check(completion: ([ACAccount]?) -> Void) { if let serviceType = self.serviceType() { if SLComposeViewController.isAvailableForServiceType(serviceType) { let accountStore = ACAccountStore(); if let accountType = accountStore.accountTypeWithAccountTypeIdentifier(self.type), accounts = accountStore.accountsWithAccountType(accountType) as? [ACAccount] { if (accounts.count == 0) { // Not Authorized. completion(nil) } else { // Authorized. completion(accounts) } } else { completion([]) } } else { // No accounts. completion([]) } } } func request(completion: ([ACAccount]?) -> Void) { let accountStore = ACAccountStore(); if let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) { accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: { (granted, error) in if granted { if let accounts = accountStore.accountsWithAccountType(accountType) as? [ACAccount] { completion(accounts) } else { completion([]) } } else { completion(nil) } }) } } } class AnimatedImageFetchInterfaceController: WKInterfaceController { @IBOutlet weak var loadingGroup: WKInterfaceGroup? @IBOutlet weak var loadingLabel: WKInterfaceLabel? @IBOutlet weak var contentImage: WKInterfaceImage? private var progressBarHelper = ProgressBarHelper() @IBOutlet weak var progressBarImage: WKInterfaceImage? { get { return self.progressBarHelper.progressBarImage } set { self.progressBarHelper.progressBarImage = newValue } } private var currenrRequestTag: RequestTag? private var lastFetchResult: AnimatedImageFetchResult? func fetch() { self.loadingGroup?.setHidden(false) self.contentImage?.setHidden(true) self.progressBarHelper.reset() self.loadingLabel?.setText("Loading...") self.clearAllMenuItems() let requestTag = RequestTag() self.currenrRequestTag = requestTag fetchAnimatedImage { [weak self] fetchResultOpt in if let strongSelf = self { if let currentRequstTag = strongSelf.currenrRequestTag, fetchResult = fetchResultOpt { if currentRequstTag === requestTag { strongSelf.loadingLabel?.setText("\(fetchResult.formattedLodingSize()) KB in \(Int(fetchResult.estimatedLoadingTime())) s") strongSelf.progressBarHelper.startInDuration(fetchResult.estimatedLoadingTime()) dispatch_async(dispatch_get_main_queue(), { [weak self] in if let strongSelf = self, currentRequstTag = strongSelf.currenrRequestTag { if (currentRequstTag === requestTag) { strongSelf.lastFetchResult = fetchResult; strongSelf.loadingGroup?.setHidden(true) strongSelf.contentImage?.setHidden(false) strongSelf.contentImage?.setImageData(fetchResult.archivedAniamtedImage.data) strongSelf.contentImage?.startAnimatingWithImagesInRange(NSMakeRange(0, fetchResult.archivedAniamtedImage.count), duration: fetchResult.archivedAniamtedImage.duration, repeatCount: 0) strongSelf.addMenuItemWithItemIcon(WKMenuItemIcon.Share, title: "Share", action: "didTapShare:"); } } }) } } else { strongSelf.loadingLabel?.setText("Failed.") } } } } private func requestTwitterAccount(completion: (ACAccount) -> Void) { // FIXME: support account selection let socialAccount = SocialAccount(type: ACAccountTypeIdentifierTwitter) socialAccount.check { (accountsOpt) -> Void in if let accounts = accountsOpt { if let account = accounts.first { completion(account) } else { self.presentControllerWithName("ModalAlert", context: ModalAlertInterfaceController.Context(text: "No Twitter accounts.")) } } else { self.presentControllerWithName("ModalAlert", context: ModalAlertInterfaceController.Context(text: "Meowatch needs access to your Twitter accounts. Tap Authorize to request access on the iPhone screen.", buttonTitle: "Authorize", didTapButton: { [weak self] in self?.dismissController() socialAccount.request({ (accounts) -> Void in if let account = accounts?.first { completion(account) } }) })) } } } private func share() { let uploadWithMediaAPIEndpoint = "https://upload.twitter.com/1/statuses/update_with_media.json" let status = "🐱 #Meowatch" if let lastFetchResult = self.lastFetchResult { requestTwitterAccount({ (account) in let url = NSURL(string: uploadWithMediaAPIEndpoint) let parameters = ["status": status] let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.POST, URL: url, parameters: parameters) request.account = account request.addMultipartData(lastFetchResult.originalData, withName: "media", type: "image/gif", filename: "cat.gif") request.performRequestWithHandler({ (data, response, error) in }) }) } } @IBAction func didTapShare(sender: AnyObject) { share(); } } class MainInterfaceController: AnimatedImageFetchInterfaceController { override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) fetch() } @IBAction func shuffle() { fetch(); } } class ModalAlertInterfaceController: WKInterfaceController { class Context { let attributedText: NSAttributedString? let text: String? let buttonTitle: String? let didTapButton: (() -> Void)? init(text: String) { self.attributedText = nil self.text = text self.buttonTitle = nil self.didTapButton = nil } init(text: String, buttonTitle: String, didTapButton: () -> Void) { self.attributedText = nil self.text = text self.buttonTitle = buttonTitle self.didTapButton = didTapButton } init(attributedText: NSAttributedString?, buttonTitle: String, didTapButton: () -> Void) { self.attributedText = attributedText self.text = nil self.buttonTitle = buttonTitle self.didTapButton = didTapButton } } @IBOutlet weak var label: WKInterfaceLabel? @IBOutlet weak var button: WKInterfaceButton? private var context: Context? override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) if let modalAlertContext = context as? Context { self.context = modalAlertContext if let attributedText = modalAlertContext.attributedText { label?.setAttributedText(attributedText) } else if let text = modalAlertContext.text { label?.setText(text) } if let buttonTitle = modalAlertContext.buttonTitle { button?.setTitle(buttonTitle) } else { button?.setHidden(true) } } } @IBAction func didTapButton(sender: AnyObject?) { self.context?.didTapButton?() } }
0fabc11aa96103b9eb63e8ad79fe1e63
37.415525
275
0.59622
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/CollectionViewPagingLayout/Lib/Scale/ScaleTransformView.swift
mit
1
// // ScaleTransformView.swift // CollectionViewPagingLayout // // Created by Amir on 15/02/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit /// A protocol for adding scale transformation to `TransformableView` public protocol ScaleTransformView: TransformableView { /// Options for controlling scale effect, see `ScaleTransformViewOptions.swift` var scaleOptions: ScaleTransformViewOptions { get } /// The view to apply scale effect on var scalableView: UIView { get } /// The view to apply blur effect on var scaleBlurViewHost: UIView { get } /// the main function for applying transforms func applyScaleTransform(progress: CGFloat) } public extension ScaleTransformView { /// The default value is the super view of `scalableView` var scaleBlurViewHost: UIView { scalableView.superview ?? scalableView } } public extension ScaleTransformView where Self: UICollectionViewCell { /// Default `scalableView` for `UICollectionViewCell` is the first subview of /// `contentView` or the content view itself if there is no subview var scalableView: UIView { contentView.subviews.first ?? contentView } } public extension ScaleTransformView { // MARK: Properties var scaleOptions: ScaleTransformViewOptions { .init() } // MARK: TransformableView func transform(progress: CGFloat) { applyScaleTransform(progress: progress) } // MARK: Public functions func applyScaleTransform(progress: CGFloat) { applyStyle(progress: progress) applyScaleAndTranslation(progress: progress) applyCATransform3D(progress: progress) if #available(iOS 10, *) { applyBlurEffect(progress: progress) } } // MARK: Private functions private func applyStyle(progress: CGFloat) { guard scaleOptions.shadowEnabled else { return } let layer = scalableView.layer layer.shadowColor = scaleOptions.shadowColor.cgColor let offset = CGSize( width: max(scaleOptions.shadowOffsetMin.width, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.width), height: max(scaleOptions.shadowOffsetMin.height, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.height) ) layer.shadowOffset = offset layer.shadowRadius = max(scaleOptions.shadowRadiusMin, (1 - abs(progress)) * scaleOptions.shadowRadiusMax) layer.shadowOpacity = max(scaleOptions.shadowOpacityMin, (1 - abs(Float(progress))) * scaleOptions.shadowOpacityMax) } private func applyScaleAndTranslation(progress: CGFloat) { var transform = CGAffineTransform.identity var xAdjustment: CGFloat = 0 var yAdjustment: CGFloat = 0 let scaleProgress = scaleOptions.scaleCurve.computeFromLinear(progress: abs(progress)) var scale = 1 - scaleProgress * scaleOptions.scaleRatio scale = max(scale, scaleOptions.minScale) scale = min(scale, scaleOptions.maxScale) if scaleOptions.keepHorizontalSpacingEqual { xAdjustment = ((1 - scale) * scalableView.bounds.width) / 2 if progress > 0 { xAdjustment *= -1 } } if scaleOptions.keepVerticalSpacingEqual { yAdjustment = ((1 - scale) * scalableView.bounds.height) / 2 } let translateProgress = scaleOptions.translationCurve.computeFromLinear(progress: abs(progress)) var translateX = scalableView.bounds.width * scaleOptions.translationRatio.x * (translateProgress * (progress < 0 ? -1 : 1)) - xAdjustment var translateY = scalableView.bounds.height * scaleOptions.translationRatio.y * abs(translateProgress) - yAdjustment if let min = scaleOptions.minTranslationRatio { translateX = max(translateX, scalableView.bounds.width * min.x) translateY = max(translateY, scalableView.bounds.height * min.y) } if let max = scaleOptions.maxTranslationRatio { translateX = min(translateX, scalableView.bounds.width * max.x) translateY = min(translateY, scalableView.bounds.height * max.y) } transform = transform .translatedBy(x: translateX, y: translateY) .scaledBy(x: scale, y: scale) scalableView.transform = transform } private func applyCATransform3D(progress: CGFloat) { var transform = CATransform3DMakeAffineTransform(scalableView.transform) if let options = self.scaleOptions.rotation3d { var angle = options.angle * progress angle = max(angle, options.minAngle) angle = min(angle, options.maxAngle) transform.m34 = options.m34 transform = CATransform3DRotate(transform, angle, options.x, options.y, options.z) scalableView.layer.isDoubleSided = options.isDoubleSided } if let options = self.scaleOptions.translation3d { var x = options.translateRatios.0 * progress * scalableView.bounds.width var y = options.translateRatios.1 * abs(progress) * scalableView.bounds.height var z = options.translateRatios.2 * abs(progress) * scalableView.bounds.width x = max(x, options.minTranslateRatios.0 * scalableView.bounds.width) x = min(x, options.maxTranslateRatios.0 * scalableView.bounds.width) y = max(y, options.minTranslateRatios.1 * scalableView.bounds.height) y = min(y, options.maxTranslateRatios.1 * scalableView.bounds.height) z = max(z, options.minTranslateRatios.2 * scalableView.bounds.width) z = min(z, options.maxTranslateRatios.2 * scalableView.bounds.width) transform = CATransform3DTranslate(transform, x, y, z) } scalableView.layer.transform = transform } private func applyBlurEffect(progress: CGFloat) { guard scaleOptions.blurEffectRadiusRatio > 0, scaleOptions.blurEffectEnabled else { scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView })?.removeFromSuperview() return } let blurView: BlurEffectView if let view = scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView }) as? BlurEffectView { blurView = view } else { blurView = BlurEffectView(effect: UIBlurEffect(style: scaleOptions.blurEffectStyle)) scaleBlurViewHost.fill(with: blurView) } blurView.setBlurRadius(radius: abs(progress) * scaleOptions.blurEffectRadiusRatio) blurView.transform = CGAffineTransform.identity.translatedBy(x: scalableView.transform.tx, y: scalableView.transform.ty) } }
9fb6642d072b0d421b834840ec196d86
38.571429
146
0.65935
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/View Controllers/UIViewController+Safari.swift
mit
1
// // UIViewController+Safari.swift // Freetime // // Created by Ryan Nystrom on 7/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SafariServices extension UIViewController { func presentSafari(url: URL) { guard let safariViewController = try? SFSafariViewController.configured(with: url) else { return } present(safariViewController, animated: trueUnlessReduceMotionEnabled) } func presentProfile(login: String) { present(CreateProfileViewController(login: login), animated: trueUnlessReduceMotionEnabled) } func presentCommit(owner: String, repo: String, hash: String) { guard let url = URL(string: "https://github.com/\(owner)/\(repo)/commit/\(hash)") else { return } presentSafari(url: url) } func presentLabels(owner: String, repo: String, label: String) { guard let url = URL(string: "https://github.com/\(owner)/\(repo)/labels/\(label)") else { return } presentSafari(url: url) } func presentMilestone(owner: String, repo: String, milestone: Int) { guard let url = URL(string: "https://github.com/\(owner)/\(repo)/milestone/\(milestone)") else { return } presentSafari(url: url) } } extension SFSafariViewController { static func configured(with url: URL) throws -> SFSafariViewController { let http = "http" let schemedURL: URL // handles http and https if url.scheme?.hasPrefix(http) == true { schemedURL = url } else { guard let u = URL(string: http + "://" + url.absoluteString) else { throw URL.Error.failedToCreateURL } schemedURL = u } let safariViewController = SFSafariViewController(url: schemedURL) safariViewController.preferredControlTintColor = Styles.Colors.Blue.medium.color return safariViewController } } extension URL { enum Error: Swift.Error { case failedToCreateURL } }
4c738e86a37afa0210a3ac1e44af5e67
28.904762
113
0.696391
false
false
false
false
apple/swift
refs/heads/main
test/attr/attr_override.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift -swift-version 5 @override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}} func virtualAttributeCanNotBeUsedInSource() {} class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}} // expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}} override @inline(never) func f1() {} } class DuplicateOverrideBase { func f1() {} class func cf1() {} class func cf2() {} class func cf3() {} class func cf4() {} } class DuplicateOverrideDerived : DuplicateOverrideBase { override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } class A { func f0() { } func f1() { } // expected-note{{overridden declaration is here}} var v1: Int { return 5 } var v2: Int { return 5 } // expected-note{{overridden declaration is here}} internal var v21: Int { return 5 } // expected-note{{overridden declaration is here}} var v4: String { return "hello" }// expected-note{{attempt to override property here}} var v5: A { return self } var v6: A { return self } var v7: A { // expected-note{{attempt to override property here}} get { return self } set { } } var v8: Int = 0 // expected-note {{attempt to override property here}} var v9: Int { return 5 } // expected-note{{attempt to override property here}} var v10: Int { return 5 } // expected-note{{attempt to override property here}} subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return "hello" } set { } } subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return "hello" } set { } } class subscript (i: String) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden class subscript 'subscript(_:)' here}} get { return "hello" } set { } } class subscript (typeInSuperclass a: [Int]) -> String { get { return "hello" } set { } } subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return self } } subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript(_:)' here}} get { return self } set { } } func overriddenInExtension() {} // expected-note {{overr}} } class B : A { override func f0() { } func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }} override func f2() { } // expected-error{{method does not override any method from its superclass}} override var v1: Int { return 5 } var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }} internal var v21: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}{{12-12=override }} override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}} override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}} // Covariance override var v5: B { return self } override var v6: B { get { return self } set { } } override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}} get { return self } set { } } // Stored properties override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}} override var v9: Int // expected-error{{cannot override with a stored property 'v9'}} lazy override var v10: Int = 5 // expected-error{{cannot override with a stored property 'v10'}} override subscript (i: Int) -> String { get { return "hello" } set { } } subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }} get { return "hello" } set { } } override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}} get { return "hello" } set { } } override class subscript (i: Int) -> String { // expected-error{{subscript does not override any subscript from its superclass}} get { return "hello" } set { } } static subscript (i: String) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{10-10=override }} get { return "hello" } set { } } static subscript (i: Double) -> String { get { return "hello" } set { } } override class subscript (typeInSuperclass a: [Int]) -> String { get { return "hello" } set { } } override subscript (typeInSuperclass a: [Int]) -> String { // expected-error{{subscript does not override any subscript from its superclass}} get { return "hello" } set { } } // Covariant override subscript (i: Int8) -> B { get { return self } } override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}} get { return self } set { } } override init() { } override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}} override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}} } extension B { override func overriddenInExtension() {} // expected-error{{overr}} } struct S { override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}} } extension S { override func ef() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}} } enum E { override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}} } protocol P { override func f() // expected-error{{method does not override any method from its parent protocol}} override var g: Int { get } // expected-error{{property does not override any property from its parent protocol}} override subscript(h: Int) -> Bool { get } // expected-error{{subscript does not override any subscript from its parent protocol}} override init(i: Int) // expected-error{{initializer does not override a designated initializer from its parent protocol}} } override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}} // Invalid 'override' on declarations inside closures. var rdar16654075a = { override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}} } var rdar16654075b = { class A { override func foo() {} // expected-error{{method does not override any method from its superclass}} } } var rdar16654075c = { () -> () in override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}} () } var rdar16654075d = { () -> () in class A { override func foo() {} // expected-error {{method does not override any method from its superclass}} } A().foo() } var rdar16654075e = { () -> () in class A { func foo() {} } class B : A { override func foo() {} } A().foo() } class C { init(string: String) { } // expected-note{{overridden declaration is here}} required init(double: Double) { } // expected-note 3{{overridden required initializer is here}} convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}} } class D1 : C { override init(string: String) { super.init(string: string) } required init(double: Double) { } convenience init() { self.init(string: "hello") } } class D2 : C { init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }} // FIXME: Would like to remove the space after 'override' as well. required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}} override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}} } class D3 : C { override init(string: String) { super.init(string: string) } override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}} } class D4 : C { // "required override" only when we're overriding a non-required // designated initializer with a required initializer. required override init(string: String) { super.init(string: string) } required init(double: Double) { } } class D5 : C { // "required override" only when we're overriding a non-required // designated initializer with a required initializer. required convenience override init(string: String) { self.init(double: 5.0) } required init(double: Double) { } } class D6 : C { init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }} } // rdar://problem/18232867 class C_empty_tuple { init() { } } class D_empty_tuple : C_empty_tuple { override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}} } class C_with_let { let x = 42 // expected-note {{attempt to override property here}} } class D_with_let : C_with_let { override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}} } // <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available class C21311590 { override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}} } class B21311590 : C21311590 {} _ = C21311590() _ = B21311590() class MismatchOptionalBase { func param(_: Int?) {} func paramIUO(_: Int!) {} func result() -> Int { return 0 } func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 } func functionParam(x: ((Int) -> Int)?) {} func tupleParam(x: (Int, Int)?) {} func compositionParam(x: (P1 & P2)?) {} func nameAndTypeMismatch(label: Int?) {} func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}} func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}} var prop: Int = 0 // expected-note {{attempt to override property here}} var optProp: Int? // expected-note {{attempt to override property here}} var getProp: Int { return 0 } // expected-note {{attempt to override property here}} var getOptProp: Int? { return nil } init(param: Int?) {} init() {} // expected-note {{non-failable initializer 'init()' overridden here}} subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}} get { return () } set {} } subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}} get { return 0 } set {} } subscript(get a: Int?) -> Void { return () } subscript(get b: Void) -> Int { return 0 } subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}} return () } subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}} return () } } protocol P1 {} protocol P2 {} class MismatchOptional : MismatchOptionalBase { override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}} override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{32-32=?}} override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}} override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil } // expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}} // expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{47-47=?}} // expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{55-56=}} override func functionParam(x: @escaping (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{56-56=)?}} override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}} override func compositionParam(x: P1 & P2) {} // expected-error {{cannot override instance method parameter of type '(any P1 & P2)?' with non-optional type 'any P1 & P2'}} {{37-37=(}} {{44-44=)?}} override func nameAndTypeMismatch(_: Int) {} // expected-error@-1 {{argument labels for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }} // expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}} override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}} override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}} override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}} get { return nil } set {} } override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}} get { return 0 } set {} } override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}} override var getOptProp: Int { return 0 } // okay override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}} override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}} override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}} get { return () } set {} } override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}} get { return nil } set {} } override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}} return () } override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}} return nil } override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}} return () } override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}} return () } } class MismatchOptional2 : MismatchOptionalBase { override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}} // None of these are overrides because we didn't say 'override'. Since they're // not exact matches, they shouldn't result in errors. func param(_: Int) {} func ambiguousOverride(a: Int, b: Int) {} // This is covariant, so we still assume it's meant to override. func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} } class MismatchOptional3 : MismatchOptionalBase { override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}} } // Make sure we remap the method's innermost generic parameters // to the correct depth class GenericBase<T> { func doStuff<U>(t: T, u: U) {} init<U>(t: T, u: U) {} } class ConcreteSub : GenericBase<Int> { override func doStuff<U>(t: Int, u: U) {} override init<U>(t: Int, u: U) {} } class ConcreteBase { init<U>(t: Int, u: U) {} func doStuff<U>(t: Int, u: U) {} } class GenericSub<T> : ConcreteBase { override init<U>(t: Int, u: U) {} override func doStuff<U>(t: Int, u: U) {} } // Issue with generic parameter index class MoreGenericSub1<T, TT> : GenericBase<T> { override func doStuff<U>(t: T, u: U) {} } class MoreGenericSub2<TT, T> : GenericBase<T> { override func doStuff<U>(t: T, u: U) {} } // Issue with insufficient canonicalization when // comparing types protocol SI {} protocol CI {} protocol Sequence { associatedtype I : SI // expected-note{{declared here}} } protocol Collection : Sequence { associatedtype I : CI // expected-warning{{redeclaration of associated type 'I'}} } class Index<F, T> { func map(_ f: F) -> T {} } class CollectionIndex<C : Collection> : Index<C, C.I> { override func map(_ f: C) -> C.I {} } // https://github.com/apple/swift/issues/46789 // Overrides with different generic signatures protocol Protocol1 {} protocol Protocol2 {} // Base class is generic, derived class is concrete. class Base1<T> { func foo<T: Protocol1>(arg: T) {} } class Derived1: Base1<Protocol2> { override func foo<T>(arg: T) {} // Ok? } // Base class is concrete, derived class is generic. class Base2 { func foo() {} } class Derived2<T>: Base2 { override func foo<T>(arg: T) {} // expected-error {{method does not override any method from its superclass}} } // Base class generic w/ method generic, derived class generic w/ method not // generic. class Base3<T> { func foo<T>(arg: T) {} } class Derived3<T>: Base3<T> { override func foo() {} // expected-error {{method does not override any method from its superclass}} } // Base class generic w/ method generic, derived class generic w/ method generic // but different requirement. class Base4<T> { func foo<T>(arg: T) {} } class Derived4<T>: Base4<T> { override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}} } // Base class not generic w/ method generic, derived class not generic w/ method // generic but different requirement. class Base5 { func foo<T>(arg: T) {} } class Derived5: Base5 { override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}} } // Base class not generic w/ method generic, derived class not generic w/ method // generic but removed requirement. class Base6 { func foo<T: Protocol2>(arg: T) {} } class Derived6: Base6 { override func foo<T>(arg: T) {} // Ok? } // Base class not generic w/ method generic, derived class generic w/ method // generic but different requirement. class Base7 { func foo<T: Protocol2>(arg: T) {} } class Derived7<T>: Base7 { override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}} } // Override with orthogonal requirement on contextual generic parameter. class Base8<T> { func foo1() where T: Protocol1 {} func foo2() where T: Protocol1 {} } class Derived8<T>: Base8<T> { override func foo1() where T: Protocol2 {} // expected-error {{method does not override any method from its superclass}} override func foo2() {} // OK } // Subclass with new conformance requirement on inherited generic parameter. class Base9<T> { func foo() where T: Protocol1 {} } class Derived9<T: Protocol2, U>: Base9<T> { // Because the generic signature of foo() is the same either way, // it may seem confusing that placing an additional constraint on the // generic parameter declaration directly has a different effect on // overridability in contrast to placing the constraint on foo(). // The former (unlike the latter) is accepted because the constraint // in question only affects the ability to initialize an instance of the // subclass — not the visibility of the override itself relative to an // existing instance. override func foo() where T: Protocol1 {} // OK } // Override with less strict requirement via contextual where clauses. class Base10<T> { func foo() where T == Int {} } class Derived10<T>: Base10<T> { override func foo() where T: FixedWidthInteger {} // OK } // Override with equivalent constraint on a different, non-inherited generic // parameter. class Base11<T> { func foo() where T: Protocol1 {} } class Derived11<T, U>: Base11<T> { override func foo() where U: Protocol1 {} // expected-error {{method does not override any method from its superclass}} } // Generic superclass / non-generic subclass. class Base12<T> { // The fact that the return type matches the substitution // for T must hold across overrides. func foo() -> T where T: FixedWidthInteger { fatalError() } // expected-note {{potential overridden instance method 'foo()' here}} } class Derived12_1: Base12<Int> { override func foo() -> Int { return .zero } // OK } class Derived12_2: Base12<Bool> { override func foo() -> Int { return .zero } // expected-error {{method does not override any method from its superclass}} } // Misc // protocol P_Key {} protocol P_Container { associatedtype Key: P_Key } class Base13<Key: P_Key> { func foo(forKey key: Key) throws {} } class Derived13<C: P_Container> : Base13<C.Key> { typealias Key = C.Key override func foo(forKey key: Key) throws {} // Okay, no generic signature mismatch } // https://github.com/apple/swift/issues/52598 class Base1_52598 { func a<T>(_ val: T) -> String { return "not equatable" } func a<T: Equatable>(_ val: T) -> String { return "equatable" } } class Derived1_52598: Base1_52598 { override func a<T>(_ val: T) -> String { return super.a(val) } // okay override func a<T: Equatable>(_ val: T) -> String { return super.a(val) } // okay } protocol P_52598 { associatedtype Bar } struct S_52598: P_52598 { typealias Bar = Int } class Base2_52598 { init<F: P_52598>(_ arg: F) where F.Bar == Int {} } class Derived2_52598: Base2_52598 { init(_ arg1: Int) { super.init(S_52598()) } // okay, doesn't crash } // https://github.com/apple/swift/issues/54147 public protocol P_54147 {} public protocol Q_54147: P_54147 { associatedtype A } public class Base_54147<F, A> {} public class Derived_54147<F, A> : Base_54147<Base_54147<F, A>, A>, Q_54147 {} public extension Base_54147 where F: Q_54147 { static func foo(_: F.A) {} } extension Derived_54147 where F: P_54147 { public static func foo(_: A) {} } // Make sure we don't crash on generic requirement mismatch protocol P3 {} protocol P4 { associatedtype T } class Base { func method<T: P3>(_: T) {} func method<T: P4>(_: T) where T.T : P3 {} } class Derived: Base { override func method<T: P3>(_: T) {} }
acc6e43a874eb90d3c90e16b5f6b98ad
33.644444
212
0.670702
false
false
false
false
beallej/krlx-app
refs/heads/master
KRLX/KRLX/ShowHeader.swift
mit
1
// // ShowHeader.swift // KRLX // // This class define each show's properties (including title, DJ, start, end time and date of show) // Created by Josie Bealle, Phuong Dinh, Maraki Ketema, Naomi Yamamoto on 5/20/15. // Copyright (c) 2015 KRLXpert. All rights reserved. // import Foundation class ShowHeader { var title : String var start : String var end : String var DJ : String var date: String init (titleString: String, startString: String, endString: String, DJString: String, dateString:String){ self.title = titleString self.start = startString self.end = endString self.DJ = DJString self.date = dateString // initialize to nil if dateString != "" { self.date = self.formatDate(dateString) } } func getTitle() -> String{ return self.title } func getDJ() -> String{ return self.DJ } func getStartTime() -> String{ return self.start } func getEndTime() -> String{ return self.end } func getDate() -> String{ return self.date } //Returns date as "Mon, Dec 21",for example func formatDate(dateString : String) -> String{ //converts string to nsdate var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.timeZone = NSTimeZone(abbreviation: "America/Chicago") let showDate = dateFormatter.dateFromString(dateString) //converts nsdate to preferred format, then back to a string var prettyDateFormatter = NSDateFormatter() //DayOfWeek-MonthAsString-DayNumber prettyDateFormatter.dateFormat = "EEEE-LLLL-dd" prettyDateFormatter.timeZone = NSTimeZone(abbreviation: "America/Chicago") let prettyDateString = prettyDateFormatter.stringFromDate(showDate!) var dateStringArray = prettyDateString.componentsSeparatedByString("-") let day = dateStringArray[0] let month = dateStringArray[1] //Shorten December-> Dec, Monday -> Mon, for example dateStringArray[0] = day.substringWithRange(Range<String.Index>(start: day.startIndex, end: advance(day.startIndex, 3))) dateStringArray[1] = month.substringWithRange(Range<String.Index>(start: month.startIndex, end: advance(month.startIndex, 3))) // Day of week , Month Day let finalDateString = dateStringArray[0]+", "+dateStringArray[1]+" "+dateStringArray[2] return finalDateString } }
8433d94c748db2c73b4e2ab5336069e1
31.047619
134
0.61627
false
true
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/AlchemyDataNewsV1/Models/DocumentUrl.swift
apache-2.0
3
/** * Copyright IBM Corporation 2016 * * 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 RestKit /** **DocumentUrl** Information about the Document. May include url, author, title, etc. */ public struct DocumentUrl: JSONDecodable { /** title of the document */ public let title: String? /** url where the document is located */ public let url: String? /** the author of the document */ public let author: String? /** see **Entity** */ public let entities: [Entity]? /** see **SAORelation** */ public let relations: [SAORelation]? /** see **Taxonomy** */ public let taxonomy: [Taxonomy]? /** see **Sentiment** */ public let sentiment: [Sentiment]? /** see **Keyword** */ public let keywords: [Keyword]? /** see **Concept** */ public let concepts: [Concept]? /** see **EnrichedTitle** */ public let enrichedTitle: EnrichedTitle? /** an image within the document */ public let image: String? /** see **ImageKeyword** */ public let imageKeywords: [ImageKeyword]? /** see **Feed** */ public let feeds: [Feed]? /** a cleaned version of the raw title */ public let cleanedTitle: String? /** see **PublicationDate** */ public let publicationDate: PublicationDate? /** a snipit of the document's text. This is largely for reference, the document's enture text is taken into account when running analysis */ public let text: String? /// used internally to initialize a DocumentUrl object public init(json: JSON) throws { title = try? json.getString(at: "title") url = try? json.getString(at: "url") author = try? json.getString(at: "author") entities = try? json.decodedArray(at: "entities", type: Entity.self) relations = try? json.decodedArray(at: "relations", type: SAORelation.self) taxonomy = try? json.decodedArray(at: "taxonomy", type: Taxonomy.self) sentiment = try? json.decodedArray(at: "sentiment", type: Sentiment.self) keywords = try? json.decodedArray(at: "keywords", type: Keyword.self) concepts = try? json.decodedArray(at: "concept", type: Concept.self) enrichedTitle = try? json.decode(at: "enrichedTitle", type: EnrichedTitle.self) image = try? json.getString(at: "image") imageKeywords = try? json.decodedArray(at: "imageKeywords", type: ImageKeyword.self) feeds = try? json.decodedArray(at: "feeds", type: Feed.self) cleanedTitle = try? json.getString(at: "cleanedTitle") publicationDate = try? json.decode(at: "publicationDate", type: PublicationDate.self) text = try? json.getString(at: "text") } }
fda077cdf0f09b40ddbda14158e9f526
32.575758
98
0.641998
false
false
false
false
WalterCreazyBear/Swifter30
refs/heads/master
TwitterBird/TwitterBird/AppDelegate.swift
mit
1
// // AppDelegate.swift // TwitterBird // // Created by Bear on 2017/6/29. // Copyright © 2017年 Bear. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CAAnimationDelegate { var window: UIWindow? var mask: CALayer? var imageView: UIImageView? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) if let window = window { // add background imageView imageView = UIImageView(frame: window.frame) imageView!.image = UIImage(named: "twitterScreen") window.addSubview(imageView!) // set up mask mask = CALayer() mask?.contents = UIImage(named: "twitterBird")?.cgImage mask?.position = window.center mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 80) imageView!.layer.mask = mask animateMask() // make window visible window.rootViewController = UIViewController() window.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1) window.makeKeyAndVisible() } // hide the status bar UIApplication.shared.isStatusBarHidden = true return true } func animateMask() { // init key frame animation let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 1 keyFrameAnimation.beginTime = CACurrentMediaTime() + 1 // animate zoom in and then zoom out let initalBounds = NSValue(cgRect: mask!.bounds) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 80, height: 64)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 2000, height: 2000)) keyFrameAnimation.values = [initalBounds, secondBounds, finalBounds] // set up time interals keyFrameAnimation.keyTimes = [0, 0.3, 1] // add animation to current view keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] mask!.add(keyFrameAnimation, forKey: "bounds") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { imageView?.layer.mask = nil } }
0b37552b56c8bf09e3a7a3aa54d3e7cc
34.808219
170
0.625478
false
false
false
false
sessionm/ios-smp-example
refs/heads/master
Referrals/ReferralDetailViewController.swift
mit
1
// // ReferralDetailViewController.swift // SMPExample // // Copyright © 2018 SessionM. All rights reserved. // import SessionMReferralsKit import UIKit class ReferralDetailViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate { @IBOutlet private var idTop: NSLayoutConstraint! @IBOutlet private var idLabel: UILabel! @IBOutlet private var referralID: UILabel! @IBOutlet private var statusLabel: UILabel! @IBOutlet private var status: UILabel! @IBOutlet private var pendingTimeLabel: UILabel! @IBOutlet private var pendingTime: UILabel! @IBOutlet private var referee: UITextField! @IBOutlet private var email: UITextField! @IBOutlet private var phoneNumber: UITextField! @IBOutlet private var source: UITextField! @IBOutlet private var origin: UITextField! @IBOutlet private var clientData: UITextView! @IBOutlet private var submit: UIButton! private var baseY: CGFloat = 0.0 private var latestY: CGFloat = 0.0 var isAddingReferral = false var referral: SMReferral? @IBAction private func submit(_ sender: UIButton) { guard let emailText = email.text, emailText.count > 0 else { let emailMissing = UIAlertController(title: "Email Missing", message: "Email is required", preferredStyle: .alert) emailMissing.addAction(UIAlertAction(title: "Dismiss", style: .default)) self.present(emailMissing, animated: true) return } let referralRequest = SMReferralRequest(email: emailText, name: referee.text, phoneNumber: phoneNumber.text, origin: origin.text, source: source.text, clientData: clientData.text) let referralsRequest = SMReferralsRequest(requests: [referralRequest], referrer: "Me") SMReferralsManager.instance().sendReferrals(referralsRequest, completionHandler: {(referrals: [SMReferral]?, referralErrors: [SMReferralError]?, error: SMError?) in let referralAlert = UIAlertController(title: nil, message: nil, preferredStyle: .alert) var alertHandler: ((UIAlertAction?) -> Void)? if let errors = referralErrors { referralAlert.title = "Error" if let firstError = errors.first { referralAlert.message = "\(firstError.referral.email)\n\(firstError.error.message)" } else { referralAlert.message = "Error encountered when submitting referral" } } else { referralAlert.title = "Success" referralAlert.message = "Refferal sent to \(emailText)" alertHandler = { (action: UIAlertAction?) in self.navigationController!.popViewController(animated: true) } } referralAlert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: alertHandler)) self.present(referralAlert, animated: true) }) } override func viewDidLoad() { super.viewDidLoad() clientData.delegate = self referee.delegate = self email.delegate = self phoneNumber.delegate = self source.delegate = self origin.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing(_:))) self.view.addGestureRecognizer(tap) baseY = idTop.constant } @objc private func endEditing(_: UITapGestureRecognizer) { self.view.endEditing(true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.updateFieldVisibility() if !isAddingReferral, let r = referral { referralID.text = r.referralID status.text = SMReferral.string(from: r.status) pendingTime.text = r.pendingTime referee.text = r.referee email.text = r.email phoneNumber.text = r.phoneNumber source.text = r.source origin.text = r.origin clientData.text = "\(String(describing: r.clientData))" } } private func updateFieldVisibility() { if isAddingReferral { idTop.constant = baseY - (idLabel.frame.size.height + statusLabel.frame.size.height + pendingTimeLabel.frame.size.height) submit.isHidden = false idLabel.isHidden = true referralID.isHidden = true statusLabel.isHidden = true status.isHidden = true pendingTimeLabel.isHidden = true pendingTime.isHidden = true referee.borderStyle = .roundedRect email.borderStyle = .roundedRect phoneNumber.borderStyle = .roundedRect source.borderStyle = .roundedRect origin.borderStyle = .roundedRect referee.isEnabled = true email.isEnabled = true phoneNumber.isEnabled = true source.isEnabled = true origin.isEnabled = true } else { idTop.constant = baseY submit.isHidden = true idLabel.isHidden = false referralID.isHidden = false statusLabel.isHidden = false status.isHidden = false pendingTimeLabel.isHidden = false pendingTime.isHidden = false referee.borderStyle = .none email.borderStyle = .none phoneNumber.borderStyle = .none source.borderStyle = .none origin.borderStyle = .none referee.isEnabled = false email.isEnabled = false phoneNumber.isEnabled = false source.isEnabled = false origin.isEnabled = false } } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { latestY = textView.frame.origin.y return isAddingReferral } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { latestY = textField.frame.origin.y return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @objc private func keyboardWillShow(_ notification: Notification) { idTop.constant = 80.0 - latestY } @objc private func keyboardWillHide(_ notification: Notification) { idTop.constant = baseY - (idLabel.frame.size.height + statusLabel.frame.size.height + pendingTimeLabel.frame.size.height) } }
928c7bd053f9634ebb2b15b2c7bb6860
37.754286
187
0.639487
false
false
false
false
klaus01/Centipede
refs/heads/master
Centipede/PassKit/CE_PKPaymentAuthorizationViewController.swift
mit
1
// // CE_PKPaymentAuthorizationViewController.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import PassKit extension PKPaymentAuthorizationViewController { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: PKPaymentAuthorizationViewController_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? PKPaymentAuthorizationViewController_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: PKPaymentAuthorizationViewController_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is PKPaymentAuthorizationViewController_Delegate { return obj as! PKPaymentAuthorizationViewController_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal override func getDelegateInstance() -> PKPaymentAuthorizationViewController_Delegate { return PKPaymentAuthorizationViewController_Delegate() } @discardableResult public func ce_paymentAuthorizationViewController_didAuthorizePayment(handle: @escaping (PKPaymentAuthorizationViewController, PKPayment, @escaping (PKPaymentAuthorizationStatus) -> Void) -> Void) -> Self { ce._paymentAuthorizationViewController_didAuthorizePayment = handle rebindingDelegate() return self } @discardableResult public func ce_paymentAuthorizationViewControllerDidFinish(handle: @escaping (PKPaymentAuthorizationViewController) -> Void) -> Self { ce._paymentAuthorizationViewControllerDidFinish = handle rebindingDelegate() return self } @discardableResult public func ce_paymentAuthorizationViewController_didSelect(handle: @escaping (PKPaymentAuthorizationViewController, PKShippingMethod, @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) -> Void) -> Self { ce._paymentAuthorizationViewController_didSelect = handle rebindingDelegate() return self } } internal class PKPaymentAuthorizationViewController_Delegate: UIViewController_Delegate, PKPaymentAuthorizationViewControllerDelegate { var _paymentAuthorizationViewController_didAuthorizePayment: ((PKPaymentAuthorizationViewController, PKPayment, @escaping (PKPaymentAuthorizationStatus) -> Void) -> Void)? var _paymentAuthorizationViewControllerDidFinish: ((PKPaymentAuthorizationViewController) -> Void)? var _paymentAuthorizationViewController_didSelect: ((PKPaymentAuthorizationViewController, PKShippingMethod, @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(paymentAuthorizationViewController(_:didAuthorizePayment:completion:)) : _paymentAuthorizationViewController_didAuthorizePayment, #selector(paymentAuthorizationViewControllerDidFinish(_:)) : _paymentAuthorizationViewControllerDidFinish, #selector(paymentAuthorizationViewController(_:didSelect:completion:)) : _paymentAuthorizationViewController_didSelect, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) { _paymentAuthorizationViewController_didAuthorizePayment!(controller, payment, completion) } @objc func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) { _paymentAuthorizationViewControllerDidFinish!(controller) } @objc func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, completion: @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) { _paymentAuthorizationViewController_didSelect!(controller, shippingMethod, completion) } }
b038013803d5f70d2e293562f6c473b8
47.052632
233
0.737349
false
false
false
false
touchopia/HackingWithSwift
refs/heads/master
project6a/Project2/ViewController.swift
unlicense
1
// // ViewController.swift // Project2 // // Created by TwoStraws on 13/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import GameplayKit import UIKit class ViewController: UIViewController { @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! var countries = [String]() var correctAnswer = 0 var score = 0 override func viewDidLoad() { super.viewDidLoad() button1.layer.borderWidth = 1 button2.layer.borderWidth = 1 button3.layer.borderWidth = 1 button1.layer.borderColor = UIColor.lightGray.cgColor button2.layer.borderColor = UIColor.lightGray.cgColor button3.layer.borderColor = UIColor.lightGray.cgColor countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"] askQuestion() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func askQuestion(action: UIAlertAction! = nil) { countries = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: countries) as! [String] button1.setImage(UIImage(named: countries[0]), for: .normal) button2.setImage(UIImage(named: countries[1]), for: .normal) button3.setImage(UIImage(named: countries[2]), for: .normal) correctAnswer = GKRandomSource.sharedRandom().nextInt(upperBound: 3) title = countries[correctAnswer].uppercased() } @IBAction func buttonTapped(_ sender: UIButton) { var title: String if sender.tag == correctAnswer { title = "Correct" score += 1 } else { title = "Wrong" score -= 1 } let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion)) present(ac, animated: true) } }
94a434417bc3c03e947e6bcb252c1221
26.318841
129
0.716711
false
false
false
false
mastahyeti/SoftU2F
refs/heads/master
SoftU2FToolTests/TestUtil.swift
mit
2
// // Util.swift // SoftU2F // // Created by Benjamin P Toews on 9/10/16. // import XCTest @testable import SoftU2F func tupleDigestEqual(_ a: SHA256.TupleDigest, _ b: SHA256.TupleDigest) -> Bool { return a.0 == b.0 && a.1 == b.1 && a.2 == b.2 && a.3 == b.3 && a.4 == b.4 && a.5 == b.5 && a.6 == b.6 && a.7 == b.7 && a.8 == b.8 && a.9 == b.9 && a.10 == b.10 && a.11 == b.11 && a.12 == b.12 && a.13 == b.13 && a.14 == b.14 && a.15 == b.15 && a.16 == b.16 && a.17 == b.17 && a.18 == b.18 && a.19 == b.19 && a.20 == b.20 && a.21 == b.21 && a.22 == b.22 && a.23 == b.23 && a.24 == b.24 && a.25 == b.25 && a.26 == b.26 && a.27 == b.27 && a.28 == b.28 && a.29 == b.29 && a.30 == b.30 && a.31 == b.31 } func randData(maxLen: Int = 4096) -> Data { let dLen = Int(arc4random()) % maxLen return randData(length: dLen) } func randData(length len: Int) -> Data { var d = Data(repeating: 0x00, count: len) d.withUnsafeMutableBytes { dPtr in arc4random_buf(dPtr, len) } return d } extension u2fh_rc { var name: String { let namePtr = u2fh_strerror_name(rawValue) return String(cString: namePtr!) } }
27432ddb9cdfb35e30de341706f0bdfa
21.681818
81
0.398798
false
false
false
false
PokeMapCommunity/PokeMap-iOS
refs/heads/master
Pods/Permission/Source/PermissionSet.swift
mit
1
// // PermissionSet.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // public class PermissionSet { /// The permissions in the set. public let permissions: Set<Permission> /// The delegate of the permission set. public var delegate: PermissionSetDelegate? /// The permission set status public var status: PermissionStatus { let statuses = permissions.map({ $0.status }) for status in statuses where status == .Denied { return .Denied } for status in statuses where status == .Disabled { return .Disabled } for status in statuses where status == .NotDetermined { return .NotDetermined } return .Authorized } /** Creates and returns a new permission set containing the specified buttons. - parameter buttons: The buttons contained by the set. - returns: A newly created set. */ public convenience init(_ buttons: PermissionButton...) { self.init(buttons: buttons) } /** Creates and returns a new permission set containing the specified buttons. - parameter buttons: The buttons contained by the set. - returns: A newly created set. */ public convenience init(_ buttons: [PermissionButton]) { self.init(buttons: buttons) } /** Creates and returns a new permission set containing the specified buttons. - parameter permissions: The permissions contained by the set. - returns: A newly created set. */ public convenience init(_ permissions: Permission...) { self.init(permissions: permissions) } /** Creates and returns a new permission set containing the specified buttons. - parameter permissions: The permissions contained by the set. - returns: A newly created set. */ public convenience init(_ permissions: [Permission]) { self.init(permissions: permissions) } private convenience init(buttons: [PermissionButton]) { let permissions = buttons.map({ $0.permission }) self.init(permissions: permissions) } private init(permissions: [Permission]) { self.permissions = Set(permissions) self.permissions.forEach { $0.permissionSets.append(self) } } internal func willRequestPermission(permission: Permission) { delegate?.permissionSet(self, willRequestPermission: permission) } internal func didRequestPermission(permission: Permission) { delegate?.permissionSet(self, didRequestPermission: permission) } } extension PermissionSet: CustomStringConvertible { /// The textual representation of self. public var description: String { return [ "\(status): [", permissions.map{ "\t\($0)" }.joinWithSeparator(",\n"), "]" ].joinWithSeparator("\n") } } public protocol PermissionSetDelegate { /** Tells the delegate that the specified permission has been requested. - parameter permissionSet: The permission set containing the requested permission. - parameter permission: The requested permission. */ func permissionSet(permissionSet: PermissionSet, didRequestPermission permission: Permission) /** Tells the delegate that the specified permission will be requested. - parameter permissionSet: The permission set containing the requested permission. - parameter permission: The requested permission. */ func permissionSet(permissionSet: PermissionSet, willRequestPermission permission: Permission) } public extension PermissionSetDelegate { /** Tells the delegate that the specified permission has been requested. - parameter permissionSet: The permission set containing the requested permission. - parameter permission: The requested permission. */ func permissionSet(permissionSet: PermissionSet, didRequestPermission permission: Permission) {} /** Tells the delegate that the specified permission will be requested. - parameter permissionSet: The permission set containing the requested permission. - parameter permission: The requested permission. */ func permissionSet(permissionSet: PermissionSet, willRequestPermission permission: Permission) {} }
409407595bc82fe537312d333268df63
33.614907
101
0.677315
false
false
false
false
bangslosan/ImagePickerSheetController
refs/heads/master
ImagePickerSheetController/Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Laurin Brandner on 26/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit import Photos import ImagePickerSheetController class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() let tapRecognizer = UITapGestureRecognizer(target: self, action: "presentImagePickerSheet:") view.addGestureRecognizer(tapRecognizer) } // MARK: Other Methods func presentImagePickerSheet(gestureRecognizer: UITapGestureRecognizer) { let authorization = PHPhotoLibrary.authorizationStatus() if authorization == .NotDetermined { PHPhotoLibrary.requestAuthorization() { status in dispatch_async(dispatch_get_main_queue()) { self.presentImagePickerSheet(gestureRecognizer) } } return } if authorization == .Authorized { let presentImagePickerController: UIImagePickerControllerSourceType -> () = { source in let controller = UIImagePickerController() controller.delegate = self var sourceType = source if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) { sourceType = .PhotoLibrary println("Fallback to camera roll as a source since the simulator doesn't support taking pictures") } controller.sourceType = sourceType self.presentViewController(controller, animated: true, completion: nil) } let controller = ImagePickerSheetController() controller.addAction(ImageAction(title: NSLocalizedString("Take Photo Or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Add comment", comment: "Action Title"), handler: { _ in presentImagePickerController(.Camera) }, secondaryHandler: { _, numberOfPhotos in println("Comment \(numberOfPhotos) photos") })) controller.addAction(ImageAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title"), $0) as String}, handler: { _ in presentImagePickerController(.PhotoLibrary) }, secondaryHandler: { _, numberOfPhotos in controller.getSelectedImagesWithCompletion() { images in println("Send \(images) photos") } })) controller.addAction(ImageAction(title: NSLocalizedString("Cancel", comment: "Action Title"), style: .Cancel, handler: { _ in println("Cancelled") })) presentViewController(controller, animated: true, completion: nil) } else { let alertView = UIAlertView(title: NSLocalizedString("An error occurred", comment: "An error occurred"), message: NSLocalizedString("ImagePickerSheet needs access to the camera roll", comment: "ImagePickerSheet needs access to the camera roll"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "OK")) alertView.show() } } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }
6c64b7a603c5f84e200c922d75afb907
43.77381
331
0.628556
false
false
false
false
Where2Go/swiftsina
refs/heads/master
GZWeibo05/Class/Extension/FFLabel.swift
apache-2.0
2
// // FFLabel.swift // FFLabel import UIKit @objc public protocol FFLabelDelegate: NSObjectProtocol { optional func labelDidSelectedLinkText(label: FFLabel, text: String) } public class FFLabel: UILabel { public var linkTextColor = UIColor.blueColor() public var selectedBackgroudColor = UIColor.lightGrayColor() public weak var labelDelegate: FFLabelDelegate? // MARK: - override properties override public var text: String? { didSet { updateTextStorage() } } override public var attributedText: NSAttributedString? { didSet { updateTextStorage() } } override public var font: UIFont! { didSet { updateTextStorage() } } override public var textColor: UIColor! { didSet { updateTextStorage() } } // MARK: - upadte text storage and redraw text private func updateTextStorage() { if attributedText == nil { return } let attrStringM = addLineBreak(attributedText!) regexLinkRanges(attrStringM) addLinkAttribute(attrStringM) textStorage.setAttributedString(attrStringM) setNeedsDisplay() } /// add link attribute private func addLinkAttribute(attrStringM: NSMutableAttributedString) { var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) attributes[NSFontAttributeName] = font! attributes[NSForegroundColorAttributeName] = textColor attrStringM.addAttributes(attributes, range: range) attributes[NSForegroundColorAttributeName] = linkTextColor for r in linkRanges { attrStringM.setAttributes(attributes, range: r) } } /// use regex check all link ranges private let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"] private func regexLinkRanges(attrString: NSAttributedString) { linkRanges.removeAll() let regexRange = NSRange(location: 0, length: attrString.string.characters.count) for pattern in patterns { let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) let results = regex.matchesInString(attrString.string, options: NSMatchingOptions(rawValue: 0), range: regexRange) for r in results { linkRanges.append(r.rangeAtIndex(0)) } } } /// add line break mode private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString { let attrStringM = NSMutableAttributedString(attributedString: attrString) var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle if paragraphStyle != nil { paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping } else { // iOS 8.0 can not get the paragraphStyle directly paragraphStyle = NSMutableParagraphStyle() paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping attributes[NSParagraphStyleAttributeName] = paragraphStyle attrStringM.setAttributes(attributes, range: range) } return attrStringM } public override func drawTextInRect(rect: CGRect) { let range = glyphsRange() let offset = glyphsOffset(range) layoutManager.drawBackgroundForGlyphRange(range, atPoint: offset) layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } private func glyphsRange() -> NSRange { return NSRange(location: 0, length: textStorage.length) } private func glyphsOffset(range: NSRange) -> CGPoint { let rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: textContainer) let height = (bounds.height - rect.height) * 0.5 return CGPoint(x: 0, y: height) } // MARK: - touch events public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) selectedRange = linkRangeAtLocation(location) modifySelectedAttribute(true) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) if let range = linkRangeAtLocation(location) { if !(range.location == selectedRange?.location && range.length == selectedRange?.length) { modifySelectedAttribute(false) selectedRange = range modifySelectedAttribute(true) } } else { modifySelectedAttribute(false) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if selectedRange != nil { let text = (textStorage.string as NSString).substringWithRange(selectedRange!) labelDelegate?.labelDidSelectedLinkText!(self, text: text) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { self.modifySelectedAttribute(false) } } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { modifySelectedAttribute(false) } private func modifySelectedAttribute(isSet: Bool) { if selectedRange == nil { return } var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil) attributes[NSForegroundColorAttributeName] = linkTextColor let range = selectedRange! if isSet { attributes[NSBackgroundColorAttributeName] = selectedBackgroudColor } else { attributes[NSBackgroundColorAttributeName] = UIColor.clearColor() selectedRange = nil } textStorage.addAttributes(attributes, range: range) setNeedsDisplay() } private func linkRangeAtLocation(location: CGPoint) -> NSRange? { if textStorage.length == 0 { return nil } let offset = glyphsOffset(glyphsRange()) let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y) let index = layoutManager.glyphIndexForPoint(point, inTextContainer: textContainer) for r in linkRanges { if index >= r.location && index <= r.location + r.length { return r } } return nil } // MARK: - init functions override public init(frame: CGRect) { super.init(frame: frame) prepareLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareLabel() } public override func layoutSubviews() { super.layoutSubviews() textContainer.size = bounds.size } private func prepareLabel() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) textContainer.lineFragmentPadding = 0 userInteractionEnabled = true } // MARK: lazy properties private lazy var linkRanges = [NSRange]() private var selectedRange: NSRange? private lazy var textStorage = NSTextStorage() private lazy var layoutManager = NSLayoutManager() private lazy var textContainer = NSTextContainer() }
0036e555cab8e71e3db6809e52c5367d
32.140496
128
0.622818
false
false
false
false
avaidyam/Parrot
refs/heads/master
Hangouts/PeopleAPI.swift
mpl-2.0
1
import Foundation import HangoutsCore import ParrotServiceExtension import class Mocha.Logger internal enum PeopleAPI { private static let baseURL = "https://people-pa.clients6.google.com/v2/people" private static let groupsURL = "https://hangoutssearch-pa.clients6.google.com/v1" private static let APIKey = "AIzaSyBokvzEPUrkgfws0OrFWkpKkVBVuhRfKpk" internal static func suggestions(on channel: Channel, completionHandler: @escaping (PeopleAPIData.SuggestionsResponse?, Error?) -> ()) { self._post(channel, PeopleAPI.baseURL + "/me/allPeople", [ "requestMask.includeField.paths": "person.email", "requestMask.includeField.paths": "person.gender", "requestMask.includeField.paths": "person.in_app_reachability", "requestMask.includeField.paths": "person.metadata", "requestMask.includeField.paths": "person.name", "requestMask.includeField.paths": "person.phone", "requestMask.includeField.paths": "person.photo", "requestMask.includeField.paths": "person.read_only_profile_info", "extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA", "extensionSet.extensionNames": "HANGOUTS_SUGGESTED_PEOPLE", "extensionSet.extensionNames": "HANGOUTS_PHONE_DATA", "key": PeopleAPI.APIKey ], nil, completionHandler) } internal static func list(on channel: Channel, completionHandler: @escaping (PeopleAPIData.ListAllResponse?, Error?) -> ()) { self._post(channel, PeopleAPI.baseURL + "/me/allPeople", [ "requestMask.includeField.paths": "person.email", "requestMask.includeField.paths": "person.gender", "requestMask.includeField.paths": "person.in_app_reachability", "requestMask.includeField.paths": "person.metadata", "requestMask.includeField.paths": "person.name", "requestMask.includeField.paths": "person.phone", "requestMask.includeField.paths": "person.photo", "requestMask.includeField.paths": "person.read_only_profile_info", "extensionSet.extensionNames": "HANGOUTS_PHONE_DATA", "fieldFilter.field": "PHONE", "key": PeopleAPI.APIKey ], nil, completionHandler) } internal static func lookup(on channel: Channel, ids: [String], completionHandler: @escaping (PeopleAPIData.GetByIdResponse?, Error?) -> ()) { guard ids.count > 0 else { return } self._post(channel, PeopleAPI.baseURL + "", [ "requestMask.includeField.paths": "person.email", "requestMask.includeField.paths": "person.gender", "requestMask.includeField.paths": "person.in_app_reachability", "requestMask.includeField.paths": "person.metadata", "requestMask.includeField.paths": "person.name", "requestMask.includeField.paths": "person.phone", "requestMask.includeField.paths": "person.photo", "requestMask.includeField.paths": "person.read_only_profile_info", "requestMask.includeField.paths": "person.organization", // extra "requestMask.includeField.paths": "person.location", // extra "requestMask.includeField.paths": "person.cover_photo", // extra "extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA", "extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_GET", "extensionSet.extensionNames": "HANGOUTS_PHONE_DATA", "includedProfileStates": "ADMIN_BLOCKED", "includedProfileStates": "DELETED", "includedProfileStates": "PRIVATE_PROFILE", "mergedPersonSourceOptions.includeAffinity": "CHAT_AUTOCOMPLETE", "coreIdParams.useRealtimeNotificationExpandedAcls": "true", "key": PeopleAPI.APIKey ], ids.map { "personId=" + $0 }.joined(separator: "&"), completionHandler) } internal static func lookup(on channel: Channel, phones: [String], completionHandler: @escaping (PeopleAPIData.LookupResponse?, Error?) -> ()) { guard phones.count > 0 else { return } self._post(channel, PeopleAPI.baseURL + "/lookup", [ "type": "PHONE", "matchType": "LENIENT", "requestMask.includeField.paths": "person.email", "requestMask.includeField.paths": "person.gender", "requestMask.includeField.paths": "person.in_app_reachability", "requestMask.includeField.paths": "person.metadata", "requestMask.includeField.paths": "person.name", "requestMask.includeField.paths": "person.phone", "requestMask.includeField.paths": "person.photo", "requestMask.includeField.paths": "person.read_only_profile_info", "extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA", "extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_LOOKUP", "extensionSet.extensionNames": "HANGOUTS_PHONE_DATA", "coreIdParams.useRealtimeNotificationExpandedAcls": "true", "quotaFilterType": "PHONE", "key": PeopleAPI.APIKey ], phones.map { "id=" + $0 }.joined(separator: "&"), completionHandler) } internal static func lookup(on channel: Channel, emails: [String], completionHandler: @escaping (PeopleAPIData.LookupResponse?, Error?) -> ()) { guard emails.count > 0 else { return } self._post(channel, PeopleAPI.baseURL + "/lookup", [ "type": "EMAIL", "matchType": "EXACT", "requestMask.includeField.paths": "person.email", "requestMask.includeField.paths": "person.gender", "requestMask.includeField.paths": "person.in_app_reachability", "requestMask.includeField.paths": "person.metadata", "requestMask.includeField.paths": "person.name", "requestMask.includeField.paths": "person.phone", "requestMask.includeField.paths": "person.photo", "requestMask.includeField.paths": "person.read_only_profile_info", "extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA", "extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_LOOKUP", "extensionSet.extensionNames": "HANGOUTS_PHONE_DATA", "coreIdParams.useRealtimeNotificationExpandedAcls": "true", "key": PeopleAPI.APIKey ], emails.map { "id=" + $0 }.joined(separator: "&"), completionHandler) } internal static func autocomplete(on channel: Channel, person: String, length: UInt = 15, completionHandler: @escaping (PeopleAPIData.AutocompleteResponse?, Error?) -> ()) { self._post(channel, PeopleAPI.baseURL + "/autocomplete", [ "query": person, "client": "HANGOUTS_WITH_DATA", "pageSize": "\(length)", "key": PeopleAPI.APIKey ], nil, completionHandler) } internal static func autocomplete(on channel: Channel, group: String, length: UInt = 15, completionHandler: @escaping (PeopleAPIData.AutocompleteGroupResponse?, Error?) -> ()) { self._post(channel, PeopleAPI.groupsURL + "/metadata:search", [ "query": group, "pageSize": "\(length)", "includeMetadata": "true", "key": PeopleAPI.APIKey, "alt": "json" ], nil, completionHandler) } // Note: DictionaryLiteral accepts duplicate keys and preserves order. // Note: `prefix` is a silly hack for multiple `id`'s which are dynamic and cannot be in a literal. private static func _post<T: Codable>(_ channel: Channel, _ api: String, _ params: DictionaryLiteral<String, String>, _ prefix: String? = nil, _ completionHandler: @escaping (T?, Error?) -> ()) { var merge = params.map { "\($0)=\($1)" }.joined(separator: "&") if let prefix2 = prefix { merge = prefix2 + "&" + merge } merge = merge.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! .replacingOccurrences(of: "+", with: "%2B") // since + is somehow allowed??? var request = URLRequest(url: URL(string: api)!) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = merge.data(using: .utf8) for (k, v) in Channel.getAuthorizationHeaders(channel.cachedSAPISID, origin: "https://hangouts.google.com", extras: ["X-HTTP-Method-Override": "GET"]) { request.setValue(v, forHTTPHeaderField: k) } channel.session.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { completionHandler(nil, error); return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { completionHandler(nil, NSError(domain: NSURLErrorDomain, code: httpStatus.statusCode, userInfo: [ "status": httpStatus, "response": data ])) } do { let res = try JSONDecoder().decode(T.self, from: data) completionHandler(res, nil) } catch(let error) { completionHandler(nil, error) } }.resume() } } internal enum PeopleAPIData { internal struct Metadata: Codable { internal var container: String? = nil internal var containerType: String? = nil internal var visibility: String? = nil internal var primary: Bool? = nil internal var writable: Bool? = nil } internal struct Address: Codable { internal var metadata: Metadata? = nil internal var formatted: String? = nil internal var type: String? = nil } internal struct Location: Codable { internal var metadata: Metadata? = nil internal var value: String? = nil } internal struct Birthday: Codable { internal var metadata: Metadata? = nil internal var dateMs: String? = nil internal var dateMsAsNumber: String? = nil } internal struct Organization: Codable { internal var metadata: Metadata? = nil internal var name: String? = nil internal var stringType: String? = nil internal var title: String? = nil } internal struct Tagline: Codable { internal var metadata: Metadata? = nil internal var value: String? = nil } internal struct Membership: Codable { internal var contactGroupId: String? = nil internal var systemContactGroupId: String? = nil } internal struct ProfileUrl: Codable { internal var url: String? = nil } internal struct Email: Codable { internal var metadata: Metadata? = nil internal var formattedType: String? = nil internal var type: String? = nil internal var value: String? = nil } internal struct Gender: Codable { internal var metadata: Metadata? = nil internal var formattedType: String? = nil internal var type: String? = nil } internal struct Name: Codable { internal var metadata: Metadata? = nil internal var displayName: String? = nil internal var displayNameLastFirst: String? = nil internal var familyName: String? = nil internal var givenName: String? = nil internal var unstructuredName: String? = nil } internal struct Photo: Codable { internal var metadata: Metadata? = nil internal var isDefault: Bool? = nil internal var isMonogram: Bool? = nil internal var monogramBackground: String? = nil internal var photoToken: String? = nil internal var url: String? = nil } internal struct CoverPhoto: Codable { internal var imageHeight: UInt? = nil internal var imageWidth: UInt? = nil internal var imageId: String? = nil internal var imageUrl: String? = nil } internal struct Phone: Codable { internal struct PhoneExtendedData: Codable { internal struct StructuredPhone: Codable { internal struct PhoneNumber: Codable { internal struct I18nData: Codable { internal var countryCode: UInt? = nil internal var internationalNumber: String? = nil internal var isValid: Bool = false internal var nationalNumber: String? = nil internal var regionCode: String? = nil internal var validationResult: String? = nil } internal var e164: String? = nil internal var i18nData: I18nData? = nil } internal var phoneNumber: PhoneNumber? = nil internal var type: String? = nil } internal var structuredPhone: StructuredPhone? = nil } internal var metadata: Metadata? = nil internal var canonicalizedForm: String? = nil internal var extendedData: PhoneExtendedData? = nil internal var formattedType: String? = nil internal var type: String? = nil internal var uri: String? = nil internal var value: String? = nil } internal struct InAppReachability: Codable { internal struct ReachabilityKey: Codable { internal var keyType: String? = nil internal var keyValue: String? = nil } internal var appType: String? = nil internal var reachabilityKey: ReachabilityKey? = nil internal var status: String? = nil } internal struct ProfileInfo: Codable { internal struct AccountEmail: Codable { internal var email: String? = nil } internal var accountEmail: AccountEmail? = nil internal var objectType: String? = nil } internal struct ExtendedData: Codable { internal struct HangoutsExtendedData: Codable { internal var hadPastHangoutState: String? = nil internal var invitationStatus: String? = nil internal var isBot: Bool? = nil internal var isDismissed: Bool? = nil internal var isFavorite: Bool? = nil internal var isPinned: Bool? = nil internal var userType: String? = nil } internal var hangoutsExtendedData: HangoutsExtendedData? = nil } internal struct Person: Codable { internal var coverPhoto: CoverPhoto? = nil internal var email: [Email]? = nil internal var extendedData: ExtendedData? = nil internal var fingerprint: String? = nil internal var gender: [Gender]? = nil internal var inAppReachability: [InAppReachability]? = nil internal var name: [Name]? = nil internal var personId: String? = nil internal var phone: [Phone]? = nil internal var photo: [Photo]? = nil internal var address: [Address]? = nil internal var location: [Location]? = nil internal var birthday: [Birthday]? = nil internal var organization: [Organization]? = nil internal var tagline: [Tagline]? = nil internal var membership: [Membership]? = nil internal var readOnlyProfileInfo: [ProfileInfo]? = nil internal var profileUrlRepeated: [ProfileUrl]? = nil } internal struct Participant: Codable { internal struct Id: Codable { internal var profileId: String? = nil } internal var displayName: String? = nil internal var email: String? = nil internal var id: Id? = nil internal var invitationStatus: String? = nil internal var profilePictureUrl: String? = nil } internal struct ConversationResult: Codable { internal struct ConversationAndSelfState: Codable { internal struct ConversationMetadata: Codable { internal struct Id: Codable { internal var id: String? = nil } internal var id: Id? = nil internal var otrStatus: String? = nil internal var participants: [Participant]? = nil internal var type: String? = nil } internal var conversationMetadata: ConversationMetadata? = nil } internal var conversationAndSelfState: ConversationAndSelfState? = nil } internal struct GetByIdResponse: Codable { internal struct Result: Codable { internal var person: Person? = nil internal var personId: String? = nil internal var status: String? = nil } internal var personResponse: [Result]? = nil } internal struct LookupResponse: Codable { internal struct Match: Codable { internal var lookupId: String? = nil internal var personId: [String]? = nil } internal var people: [String: Person]? = nil internal var matches: [Match]? = nil } internal struct ListAllResponse: Codable { internal var nextSyncToken: String? = nil internal var people: [Person]? = nil internal var totalItems: UInt? = nil internal var nextPageToken: String? = nil } internal struct SuggestionsResponse: Codable { internal var people: [Person]? = nil } internal struct AutocompleteResponse: Codable { internal struct Status: Codable { internal var personalResultsNotReady: Bool? = nil } internal struct Suggestion: Codable { internal var objectType: String? = nil internal var person: Person? = nil internal var suggestion: String? = nil } internal var status: Status? = nil internal var nextPageToken: String? = nil internal var results: [Suggestion]? = nil } internal struct AutocompleteGroupResponse: Codable { internal var results: [ConversationResult]? = nil } // Convenience for this crazy nesting. internal typealias PhoneNumber = Phone.PhoneExtendedData.StructuredPhone.PhoneNumber internal typealias I18nData = Phone.PhoneExtendedData.StructuredPhone.PhoneNumber.I18nData internal typealias HangoutsExtendedData = ExtendedData.HangoutsExtendedData internal typealias ConversationMetadata = ConversationResult.ConversationAndSelfState.ConversationMetadata } internal extension PeopleAPIData.HangoutsExtendedData { var userInterest: Bool { return (self.isFavorite ?? false || self.isPinned ?? false) } }
0cb89e6754466eca32cf88aff8df4dc0
42.522523
148
0.606707
false
false
false
false
ben-ng/swift
refs/heads/master
benchmark/single-source/StringInterpolation.swift
apache-2.0
1
//===--- StringInterpolation.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils class RefTypePrintable : CustomStringConvertible { var description: String { return "01234567890123456789012345678901234567890123456789" } } @inline(never) public func run_StringInterpolation(_ N: Int) { let reps = 100 let refResult = reps let anInt: Int64 = 0x1234567812345678 let aRefCountedObject = RefTypePrintable() for _ in 1...100*N { var result = 0 for _ in 1...reps { let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}" let utf16 = s.utf16 // FIXME: if String is not stored as UTF-16 on this platform, then the // following operation has a non-trivial cost and needs to be replaced // with an operation on the native storage type. result = result &+ Int(utf16[utf16.index(before: utf16.endIndex)]) } CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)") } }
6af071b36b5d61d6f7c3ed119222f553
33.690476
107
0.645161
false
false
false
false
stolycizmus/WowToken
refs/heads/master
WowToken/RoundedRect.swift
gpl-3.0
1
// // RoundedRect.swift // WowToken // // Created by Kadasi Mate on 2015. 11. 22.. // Copyright © 2015. Tairpake Inc. All rights reserved. // import UIKit @IBDesignable class RoundedRect: UIView { @IBInspectable var fillColor: UIColor = UIColor(colorLiteralRed: 0.035, green: 0.043, blue: 0.133, alpha: 1.0) override func draw(_ rect: CGRect) { self.backgroundColor = UIColor.clear fillColor.setFill() var path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 5)) path.addLine(to: CGPoint(x: 5, y: 0)) path.addLine(to: CGPoint(x: rect.width-5, y: 0)) path.addLine(to: CGPoint(x: rect.width, y: 5)) path.addLine(to: CGPoint(x: rect.width, y: rect.height-5)) path.addLine(to: CGPoint(x: rect.width-5, y: rect.height)) path.addLine(to: CGPoint(x: 5, y: rect.height)) path.addLine(to: CGPoint(x: 0, y: rect.height-5)) path.close() path.addClip() path.fill() path = UIBezierPath() path.lineWidth = 3 UIColor.white.setStroke() path.move(to: CGPoint(x: 0, y: 5)) path.addLine(to: CGPoint(x: 5, y: 0)) path.addLine(to: CGPoint(x: rect.width-5, y: 0)) path.addLine(to: CGPoint(x: rect.width, y: 5)) path.stroke() path = UIBezierPath() path.lineWidth = 3 UIColor(colorLiteralRed: 0.467, green: 0.467, blue: 0.467, alpha: 1.0).setStroke() path.move(to: CGPoint(x: rect.width, y: 5)) path.addLine(to: CGPoint(x: rect.width, y: rect.height-5)) path.addLine(to: CGPoint(x: rect.width-5, y: rect.height)) path.addLine(to: CGPoint(x: 5, y: rect.height)) path.addLine(to: CGPoint(x: 0, y: rect.height-5)) path.addLine(to: CGPoint(x: 0, y: 5)) path.stroke() } }
583ce960fbe0837fbe3a11601471e9f5
33.773585
114
0.583831
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Pods/PagingMenuController/Pod/Classes/MenuItemView.swift
apache-2.0
1
// // MenuItemView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit open class MenuItemView: UIView { lazy public var titleLabel: UILabel = self.initLabel() lazy public var descriptionLabel: UILabel = self.initLabel() lazy public var menuImageView: UIImageView = { $0.isUserInteractionEnabled = true $0.translatesAutoresizingMaskIntoConstraints = false return $0 }(UIImageView(frame: .zero)) public fileprivate(set) var customView: UIView? { didSet { guard let customView = customView else { return } addSubview(customView) } } public internal(set) var isSelected: Bool = false { didSet { if case .roundRect = menuOptions.focusMode { backgroundColor = UIColor.clear } else { backgroundColor = isSelected ? menuOptions.selectedBackgroundColor : menuOptions.backgroundColor } switch menuItemOptions.displayMode { case .text(let title): updateLabel(titleLabel, text: title) // adjust label width if needed let labelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) widthConstraint.constant = labelSize.width case let .multilineText(title, description): updateLabel(titleLabel, text: title) updateLabel(descriptionLabel, text: description) // adjust label width if needed widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: maxWindowSize).width descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize).width case let .image(image, selectedImage): menuImageView.image = isSelected ? (selectedImage ?? image) : image case .custom: break } } } lazy public fileprivate(set) var dividerImageView: UIImageView? = { [unowned self] in guard let image = self.menuOptions.dividerImage else { return nil } let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() fileprivate var menuOptions: MenuViewCustomizable! fileprivate var menuItemOptions: MenuItemViewCustomizable! fileprivate var widthConstraint: NSLayoutConstraint! fileprivate var descriptionWidthConstraint: NSLayoutConstraint! fileprivate var horizontalMargin: CGFloat { switch menuOptions.displayMode { case .segmentedControl: return 0.0 default: return menuItemOptions.horizontalMargin } } // MARK: - Lifecycle internal init(menuOptions: MenuViewCustomizable, menuItemOptions: MenuItemViewCustomizable, addDiveder: Bool) { super.init(frame: .zero) self.menuOptions = menuOptions self.menuItemOptions = menuItemOptions switch menuItemOptions.displayMode { case .text(let title): commonInit({ self.setupTitleLabel(title) self.layoutLabel() }) case let .multilineText(title, description): commonInit({ self.setupMultilineLabel(title, description: description) self.layoutMultiLineLabel() }) case .image(let image, _): commonInit({ self.setupImageView(image) self.layoutImageView() }) case .custom(let view): commonInit({ self.setupCustomView(view) self.layoutCustomView() }) } } fileprivate func commonInit(_ setupContentView: () -> Void) { setupView() setupContentView() setupDivider() layoutDivider() } fileprivate func initLabel() -> UILabel { let label = UILabel(frame: .zero) label.numberOfLines = 1 label.textAlignment = .center label.isUserInteractionEnabled = true label.translatesAutoresizingMaskIntoConstraints = false return label } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Constraints manager internal func updateConstraints(_ size: CGSize) { // set width manually to support ratotaion guard case .segmentedControl = menuOptions.displayMode else { return } switch menuItemOptions.displayMode { case .text: let labelSize = calculateLabelSize(titleLabel, maxWidth: size.width) widthConstraint.constant = labelSize.width case .multilineText: widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: size.width).width descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: size.width).width case .image, .custom: widthConstraint.constant = size.width / CGFloat(menuOptions.itemsOptions.count) } } // MARK: - Constructor fileprivate func setupView() { if case .roundRect = menuOptions.focusMode { backgroundColor = UIColor.clear } else { backgroundColor = menuOptions.backgroundColor } translatesAutoresizingMaskIntoConstraints = false } fileprivate func setupTitleLabel(_ text: MenuItemText) { setupLabel(titleLabel, text: text) } fileprivate func setupMultilineLabel(_ text: MenuItemText, description: MenuItemText) { setupLabel(titleLabel, text: text) setupLabel(descriptionLabel, text: description) } fileprivate func setupLabel(_ label: UILabel, text: MenuItemText) { label.text = text.text updateLabel(label, text: text) addSubview(label) } fileprivate func updateLabel(_ label: UILabel, text: MenuItemText) { label.textColor = isSelected ? text.selectedColor : text.color label.font = isSelected ? text.selectedFont : text.font } fileprivate func setupImageView(_ image: UIImage) { menuImageView.image = image addSubview(menuImageView) } fileprivate func setupCustomView(_ view: UIView) { customView = view } fileprivate func setupDivider() { guard let dividerImageView = dividerImageView else { return } addSubview(dividerImageView) } fileprivate func layoutMultiLineLabel() { // H:|[titleLabel(==labelSize.width)]| // H:|[descriptionLabel(==labelSize.width)]| // V:|-margin-[titleLabel][descriptionLabel]-margin| let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) let descriptionLabelSize = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize) let verticalMargin = max(menuOptions.height - (titleLabelSize.height + descriptionLabelSize.height), 0) / 2 widthConstraint = titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: titleLabelSize.width) descriptionWidthConstraint = descriptionLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: descriptionLabelSize.width) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor), widthConstraint, descriptionLabel.leadingAnchor.constraint(equalTo: leadingAnchor), descriptionLabel.trailingAnchor.constraint(equalTo: trailingAnchor), descriptionWidthConstraint, titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: verticalMargin + menuOptions.marginTop), titleLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: 0), descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: verticalMargin), titleLabel.heightAnchor.constraint(equalToConstant: titleLabelSize.height), ]) } fileprivate func layoutLabel() { // H:|[titleLabel](==labelSize.width)| // V:|[titleLabel]| let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) widthConstraint = titleLabel.widthAnchor.constraint(equalToConstant: titleLabelSize.width) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor), widthConstraint, titleLabel.topAnchor.constraint(equalTo: topAnchor), titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } fileprivate func layoutImageView() { guard let image = menuImageView.image else { return } let width: CGFloat switch menuOptions.displayMode { case .segmentedControl: if let windowWidth = UIApplication.shared.keyWindow?.bounds.size.width { width = windowWidth / CGFloat(menuOptions.itemsOptions.count) } else { width = UIScreen.main.bounds.width / CGFloat(menuOptions.itemsOptions.count) } default: width = image.size.width + horizontalMargin * 2 } widthConstraint = widthAnchor.constraint(equalToConstant: width) NSLayoutConstraint.activate([ menuImageView.centerXAnchor.constraint(equalTo: centerXAnchor), menuImageView.centerYAnchor.constraint(equalTo: centerYAnchor), menuImageView.widthAnchor.constraint(equalToConstant: image.size.width), menuImageView.heightAnchor.constraint(equalToConstant: image.size.height), widthConstraint ]) } fileprivate func layoutCustomView() { guard let customView = customView else { return } widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width) NSLayoutConstraint.activate([ NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width), NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: customView.frame.height), widthConstraint ]) } fileprivate func layoutDivider() { guard let dividerImageView = dividerImageView else { return } NSLayoutConstraint.activate([ dividerImageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 1.0), dividerImageView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) } } extension MenuItemView { func cleanup() { switch menuItemOptions.displayMode { case .text: titleLabel.removeFromSuperview() case .multilineText: titleLabel.removeFromSuperview() descriptionLabel.removeFromSuperview() case .image: menuImageView.removeFromSuperview() case .custom: customView?.removeFromSuperview() } dividerImageView?.removeFromSuperview() } } // MARK: Lable Size extension MenuItemView { fileprivate func labelWidth(_ widthMode: MenuItemWidthMode, estimatedSize: CGSize) -> CGFloat { switch widthMode { case .flexible: return ceil(estimatedSize.width) case .fixed(let width): return width } } fileprivate func estimatedLabelSize(_ label: UILabel) -> CGSize { guard let text = label.text else { return .zero } return NSString(string: text).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil).size } fileprivate func calculateLabelSize(_ label: UILabel, maxWidth: CGFloat) -> CGSize { guard let _ = label.text else { return .zero } let itemWidth: CGFloat switch menuOptions.displayMode { case .standard(let widthMode, _, _): itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label)) case .segmentedControl: itemWidth = maxWidth / CGFloat(menuOptions.itemsOptions.count) case .infinite(let widthMode, _): itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label)) } let itemHeight = floor(estimatedLabelSize(label).height) return CGSize(width: itemWidth + horizontalMargin * 2, height: itemHeight) } fileprivate var maxWindowSize: CGFloat { return UIApplication.shared.keyWindow?.bounds.width ?? UIScreen.main.bounds.width } }
24e673f85186533553e58e31880de47a
40.200608
245
0.650092
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
refs/heads/master
03-YFPageViewExtensionDemo(IM)/YFPageViewExtensionDemo/YFPageView/YFTitleView.swift
mit
2
// // YFTitleView.swift // YFPageViewDemo // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit protocol YFTitleViewDelegate : class { func titleView(_ titleView : YFTitleView, targetIndex : Int) } class YFTitleView: UIView { weak var delegate : YFTitleViewDelegate? fileprivate var titlesArr : [String] fileprivate var style : YFPageStyle fileprivate lazy var titleLabelsArr : [UILabel] = [UILabel]() fileprivate var currentIndex :Int = 0 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor bottomLine.frame.size.height = self.style.bottomLineHeight return bottomLine }() init(frame: CGRect,titles:[String],style:YFPageStyle) { self.titlesArr = titles self.style = style super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension YFTitleView { fileprivate func setupUI() { //1.将UIScorllView添加到view中 addSubview(scrollView) //2.将titleLabel添加到UIScorllView中 setupTitleLabels() //3.设置titleLabel的frame setupTitleLabelsFrame() // 4.设置BottomLine setupBottomLine() } private func setupBottomLine() { // 1.判断是否需要显示底部线段 guard style.isShowBottomLine else { return } // 2.将bottomLine添加到titleView中 scrollView.addSubview(bottomLine) // 3.设置frame bottomLine.frame.origin.x = titleLabelsArr.first!.frame.origin.x bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight bottomLine.frame.size.width = titleLabelsArr.first!.bounds.width } private func setupTitleLabels(){ for (i ,title) in titlesArr.enumerated() { // 1.创建Label let titleLabel = UILabel() // 2.设置label的属性 titleLabel.text = title titleLabel.font = UIFont.systemFont(ofSize: style.fontSize) titleLabel.tag = i titleLabel.textAlignment = .center titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor // 3.添加到父控件中 scrollView.addSubview(titleLabel) // 4.保存label titleLabelsArr.append(titleLabel) //给UILabel添加点击手势 let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:))) titleLabel.addGestureRecognizer(tapGes) titleLabel.isUserInteractionEnabled = true } } private func setupTitleLabelsFrame() { let count = titlesArr.count for (i, label) in titleLabelsArr.enumerated() { var w : CGFloat = 0 let h : CGFloat = bounds.height var x : CGFloat = 0 let y : CGFloat = 0 if style.isScrollEnable { // 可以滚动 w = (titlesArr[i] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil).width if i == 0 { x = style.itemMargin * 0.5 } else { let preLabel = titleLabelsArr[i - 1] x = preLabel.frame.maxX + style.itemMargin } } else { // 不能滚动 w = bounds.width / CGFloat(count) x = w * CGFloat(i) } label.frame = CGRect(x: x, y: y, width: w, height: h) } scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabelsArr.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero } } // MARK:- 监听事件 extension YFTitleView { @objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer) { //1.取出用户点击的View let targetLabel = tapGes.view as! UILabel //2.调整title adjustTitleLabel(targetIndex: targetLabel.tag) //3.通知ContentView进行调整 delegate?.titleView(self, targetIndex: currentIndex) // 4.调整BottomLine if style.isShowBottomLine { bottomLine.frame.origin.x = targetLabel.frame.origin.x bottomLine.frame.size.width = targetLabel.frame.width } } fileprivate func adjustTitleLabel(targetIndex : Int) { if targetIndex == currentIndex { return } //1.取出label let targetLabel = titleLabelsArr[targetIndex] let sourceLabel = titleLabelsArr[currentIndex] //2.切换文字的颜色 sourceLabel.textColor = style.normalColor targetLabel.textColor = style.selectColor //3.记录下值 currentIndex = targetLabel.tag //5.调整位置 -- 选中的按钮居中 if style.isScrollEnable { var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5 if offsetX < 0 { offsetX = 0 } if offsetX > scrollView.contentSize.width - scrollView.bounds.width { offsetX = scrollView.contentSize.width - scrollView.bounds.width } scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } } //MARK:-遵循YFContentViewDelegate 滑动contentView标签调整 extension YFTitleView : YFContentViewDelegate{ func contentView(_ contentView: YFContentView, targetIndex: Int) { adjustTitleLabel(targetIndex: targetIndex) } func contentView(_ contentView: YFContentView, targetIndex: Int, progress: CGFloat) { //1.取出label let sourceLabel = titleLabelsArr[currentIndex] let targetLabel = titleLabelsArr[targetIndex] //2.颜色渐变 let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor) let selectRGB = style.selectColor.getRGB() let normalRGB = style.normalColor.getRGB() sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress) targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress) // 3.渐变BottomLine if style.isShowBottomLine { let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let deltaW = targetLabel.frame.width - sourceLabel.frame.width bottomLine.frame.origin.x = sourceLabel.frame.origin.x + deltaX * progress bottomLine.frame.size.width = sourceLabel.frame.width + deltaW * progress } } } // MARK:- 对外暴露的方法 extension YFTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { //1.取出label let sourceLabel = titleLabelsArr[sourceIndex] let targetLabel = titleLabelsArr[targetIndex] //2.颜色渐变 let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor) let selectRGB = style.selectColor.getRGB() let normalRGB = style.normalColor.getRGB() sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress) targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isShowBottomLine { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } } }
f7629c2ab0a82d411d766fb6faafd7ed
31.104869
212
0.604176
false
false
false
false
davirdgs/ABC4
refs/heads/master
MN4/StartViewController.swift
gpl-3.0
1
// // StartViewController.swift // MN4 // // Created by Davi Rodrigues on 20/08/15. // Copyright (c) 2015 Pedro Rodrigues Grijó. All rights reserved. // import UIKit class StartViewController: UIViewController { let defaults = UserDefaults.standard ///Displays score @IBOutlet weak var scoreLabel: UILabel! ///Trophy image icon @IBOutlet weak var scoreIcon: UIImageView! @IBOutlet weak var tutorialButton: UIButton! @IBOutlet weak var playButton: UIButton! override func viewDidLoad() { super.viewDidLoad() //Set background image as newspaper self.view.backgroundColor = Styles.backgroundColor //tutorialButton.layer.borderColor = UIColor.blackColor().CGColor tutorialButton.layer.borderWidth = 0 //playButton.layer.borderColor = UIColor.blackColor().CGColor playButton.layer.borderWidth = 0 tutorialButton.layer.cornerRadius = tutorialButton.frame.height/4 tutorialButton.layer.masksToBounds = true playButton.layer.cornerRadius = playButton.frame.height/4 playButton.layer.masksToBounds = true //Set Trophy scoreIcon.image = scoreIcon.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate) scoreIcon.tintColor = UIColor(red: 255/255, green: 200/255, blue: 0/255, alpha: 1.0) scoreIcon.layer.shadowOffset = CGSize(width: 1, height: 1) scoreIcon.layer.shadowOpacity = 1 scoreIcon.layer.shadowRadius = 1 //Set font scoreLabel.font = Styles.getFont() playButton.titleLabel!.font = Styles.getFont() tutorialButton.titleLabel!.font = Styles.getFont() // Creates the dataBase WordDataBase.setDataBase() WordDataBaseEnglish.setDataBase() WordDataBaseSpanish.setDataBase() } override func viewWillAppear(_ animated: Bool) { let record = defaults.integer(forKey: "Record") scoreLabel.text = String(format: "%03d", record) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // Hide status bar from this view override var prefersStatusBarHidden : Bool { return true } @IBAction func tutorialButtonHandler(_ sender: AnyObject) { performSegue(withIdentifier: "toTutorialViewController", sender: self) } @IBAction func playButtonHandler(_ sender: AnyObject) { let level = Level() level.setLevel() performSegue(withIdentifier: "toGameViewController", sender: self) } @IBAction func returnToStart(_ sender: UIStoryboardSegue) { } }
afac279c0c92c9f81ea4abed08273177
29.505618
97
0.658932
false
false
false
false
jianweihehe/JWDouYuZB
refs/heads/master
JWDouYuZB/JWDouYuZB/Classes/Main/Controller/CustomNavigationController.swift
mit
1
// // CustomNavigationController.swift // JWDouYuZB // // Created by [email protected] on 2017/1/16. // Copyright © 2017年 简伟. All rights reserved. // import UIKit class CustomNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() //获取系统pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } //获取手势添加到的view中 guard let gesView = systemGes.view else { return } //获取target/action /** 利用运行时机制查看所有的属性名称 var count:UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count) for i in 0..<count { let ivar = ivars?[Int(i)] let name = ivar_getName(ivar) print(String(cString: name!)) } */ let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetsObjc = targets?.first else { return } guard let target = targetsObjc.value(forKey: "target") else { return } let action = Selector(("handleNavigationTransition:")) let panGes = UIPanGestureRecognizer(target: target, action: action) gesView.addGestureRecognizer(panGes) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } }
cc6d1174b1729a71b3b8733f364e1e4c
31.727273
90
0.648611
false
false
false
false
LeaderQiu/SwiftDictModel
refs/heads/master
HMWeibo04/HMWeibo04/Classes/Tools/SwiftDictModel.swift
mit
4
// // SwiftDictModel.swift // // // Created by 刘凡 on 15/2/17. // // import Foundation /** 字典转模型协议 提示: * 自定义类映射字典中需要包含类的命名空间 示例代码: return ["info": "\(Info.self)", "other": "\(Info.self)", "demo": "\(Info.self)"]; * 目前存在的问题: - 由于 customClassMapping 是一个静态函数,子类模型中不能重写协议函数 - 如果子类中也包含自定义对象,需要在父类的 customClassMapping 一并指定 * 不希望参与字典转模型的属性可以定义为 private 的 */ @objc public protocol DictModelProtocol { /// 自定义类映射字典 /// /// :returns: 可选映射字典 static func customClassMapping() -> [String: String]? } /// 字典转模型管理器 public class DictModelManager { private static let instance = DictModelManager() /// 全局统一访问入口 public class var sharedManager: DictModelManager { return instance } /// 字典转模型 /// /// :param: dict 数据字典 /// :param: cls 模型类 /// /// :returns: 模型对象 public func objectWithDictionary(dict: NSDictionary, cls: AnyClass) -> AnyObject? { // 1. 模型信息 let infoDict = fullModelInfo(cls) // 2. 实例化对象 let obj: AnyObject = cls.alloc() autoreleasepool { // 3. 遍历模型字典 for (k, v) in infoDict { if let value: AnyObject = dict[k] { if v.isEmpty { if !(value === NSNull()) { obj.setValue(value, forKey: k) } } else { let type = "\(value.classForCoder)" if type == "NSDictionary" { if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } else if type == "NSArray" { if let subObj: AnyObject = objectsWithArray(value as! NSArray, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } } } } } return obj } /// 创建自定义对象数组 /// /// :param: NSArray 字典数组 /// :param: cls 模型类 /// /// :returns: 模型数组 public func objectsWithArray(array: NSArray, cls: AnyClass) -> NSArray? { var list = [AnyObject]() autoreleasepool { () -> () in for value in array { let type = "\(value.classForCoder)" if type == "NSDictionary" { if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: cls) { list.append(subObj) } } else if type == "NSArray" { if let subObj: AnyObject = objectsWithArray(value as! NSArray, cls: cls) { list.append(subObj) } } } } if list.count > 0 { return list } else { return nil } } /// 模型转字典 /// /// :param: obj 模型对象 /// /// :returns: 字典信息 public func objectDictionary(obj: AnyObject) -> [String: AnyObject]? { // 1. 取出对象模型字典 let infoDict = fullModelInfo(obj.classForCoder) var result = [String: AnyObject]() // 2. 遍历字典 for (k, v) in infoDict { var value: AnyObject? = obj.valueForKey(k) if value == nil { value = NSNull() } if v.isEmpty || value === NSNull() { result[k] = value } else { let type = "\(value!.classForCoder)" var subValue: AnyObject? if type == "NSArray" { subValue = objectArray(value! as! [AnyObject]) } else { subValue = objectDictionary(value!) } if subValue == nil { subValue = NSNull() } result[k] = subValue } } if result.count > 0 { return result } else { return nil } } /// 模型数组转字典数组 /// /// :param: array 模型数组 /// /// :returns: 字典数组 public func objectArray(array: [AnyObject]) -> [AnyObject]? { var result = [AnyObject]() for value in array { let type = "\(value.classForCoder)" var subValue: AnyObject? if type == "NSArray" { subValue = objectArray(value as! [AnyObject]) } else { subValue = objectDictionary(value) } if subValue != nil { result.append(subValue!) } } if result.count > 0 { return result } else { return nil } } // MARK: - 私有函数 /// 加载完整类信息 /// /// :param: cls 模型类 /// /// :returns: 模型类完整信息 func fullModelInfo(cls: AnyClass) -> [String: String] { // 检测缓冲池 if let cache = modelCache["\(cls)"] { return cache } var currentCls: AnyClass = cls var infoDict = [String: String]() while let parent: AnyClass = currentCls.superclass() { infoDict.merge(modelInfo(currentCls)) currentCls = parent } // 写入缓冲池 modelCache["\(cls)"] = infoDict return infoDict } /// 加载类信息 /// /// :param: cls 模型类 /// /// :returns: 模型类信息 func modelInfo(cls: AnyClass) -> [String: String] { // 检测缓冲池 if let cache = modelCache["\(cls)"] { return cache } // 拷贝属性列表 var count: UInt32 = 0 let properties = class_copyPropertyList(cls, &count) // 检查类是否实现了协议 var mappingDict: [String: String]? if cls.respondsToSelector("customClassMapping") { mappingDict = cls.customClassMapping() } var infoDict = [String: String]() for i in 0..<count { let property = properties[Int(i)] // 属性名称 let cname = property_getName(property) let name = String.fromCString(cname)! let type = mappingDict?[name] ?? "" infoDict[name] = type } free(properties) // 写入缓冲池 modelCache["\(cls)"] = infoDict return infoDict } /// 模型缓冲,[类名: 模型信息字典] var modelCache = [String: [String: String]]() } extension Dictionary { /// 将字典合并到当前字典 mutating func merge<K, V>(dict: [K: V]) { for (k, v) in dict { self.updateValue(v as! Value, forKey: k as! Key) } } } func printLog<T>(message: T, file: String = __FILE__, method: String = __FUNCTION__, line: Int = __LINE__) { println("\(file.lastPathComponent)[\(line)], \(method): \(message)") }
0d25387beeed3c7e6674d444540dbe65
25.547445
128
0.445972
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Services/Implementations/Persistency/Adapters/GoalModelAdapter.swift
bsd-3-clause
1
import Foundation import CoreData class GoalModelAdapter : CoreDataModelAdapter<Goal> { //MARK: Private Properties private let dateKey = "date" private let categoryKey = "category" private let targetTimeKey = "targetTime" //MARK: Initializers override init() { super.init() sortDescriptorsForList = [ NSSortDescriptor(key: dateKey, ascending: false) ] sortDescriptorsForLast = sortDescriptorsForList } //MARK: Public Methods override func getModel(fromManagedObject managedObject: NSManagedObject) -> Goal { let date = managedObject.value(forKey: dateKey) as! Date let category = Category(rawValue: managedObject.value(forKey: categoryKey) as! String)! let targetTime = managedObject.value(forKey: targetTimeKey) as! Seconds let goal = Goal(date: date, category: category, targetTime: targetTime) return goal } override func setManagedElementProperties(fromModel model: Goal, managedObject: NSManagedObject) { managedObject.setValue(model.targetTime, forKey: targetTimeKey) managedObject.setValue(model.date, forKey: dateKey) managedObject.setValue(model.category.rawValue, forKey: categoryKey) } }
ce57be599556c6dacf7b98cbf4a0e53d
32.947368
100
0.688372
false
false
false
false
AnRanScheme/magiGlobe
refs/heads/master
Example/Pods/Moya/Sources/Moya/Endpoint.swift
apache-2.0
18
import Foundation import Alamofire /// Used for stubbing responses. public enum EndpointSampleResponse { /// The network returned a response, including status code and data. case networkResponse(Int, Data) /// The network returned response which can be fully customized. case response(HTTPURLResponse, Data) /// The network failed to send the request, or failed to retrieve a response (eg a timeout). case networkError(NSError) } /// Class for reifying a target of the `Target` enum unto a concrete `Endpoint`. open class Endpoint<Target> { public typealias SampleResponseClosure = () -> EndpointSampleResponse open let url: String open let method: Moya.Method open let sampleResponseClosure: SampleResponseClosure open let parameters: [String: Any]? open let parameterEncoding: Moya.ParameterEncoding open let httpHeaderFields: [String: String]? /// Main initializer for `Endpoint`. public init(url: String, sampleResponseClosure: @escaping SampleResponseClosure, method: Moya.Method = Moya.Method.get, parameters: [String: Any]? = nil, parameterEncoding: Moya.ParameterEncoding = URLEncoding.default, httpHeaderFields: [String: String]? = nil) { self.url = url self.sampleResponseClosure = sampleResponseClosure self.method = method self.parameters = parameters self.parameterEncoding = parameterEncoding self.httpHeaderFields = httpHeaderFields } /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with added parameters. open func adding(newParameters: [String: Any]) -> Endpoint<Target> { return adding(parameters: newParameters) } /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with added HTTP header fields. open func adding(newHTTPHeaderFields: [String: String]) -> Endpoint<Target> { return adding(httpHeaderFields: newHTTPHeaderFields) } /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with another parameter encoding. open func adding(newParameterEncoding: Moya.ParameterEncoding) -> Endpoint<Target> { return adding(parameterEncoding: newParameterEncoding) } /// Convenience method for creating a new `Endpoint`, with changes only to the properties we specify as parameters open func adding(parameters: [String: Any]? = nil, httpHeaderFields: [String: String]? = nil, parameterEncoding: Moya.ParameterEncoding? = nil) -> Endpoint<Target> { let newParameters = add(parameters: parameters) let newHTTPHeaderFields = add(httpHeaderFields: httpHeaderFields) let newParameterEncoding = parameterEncoding ?? self.parameterEncoding return Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, parameters: newParameters, parameterEncoding: newParameterEncoding, httpHeaderFields: newHTTPHeaderFields) } fileprivate func add(parameters: [String: Any]?) -> [String: Any]? { guard let unwrappedParameters = parameters, unwrappedParameters.isEmpty == false else { return self.parameters } var newParameters = self.parameters ?? [:] unwrappedParameters.forEach { key, value in newParameters[key] = value } return newParameters } fileprivate func add(httpHeaderFields headers: [String: String]?) -> [String: String]? { guard let unwrappedHeaders = headers, unwrappedHeaders.isEmpty == false else { return self.httpHeaderFields } var newHTTPHeaderFields = self.httpHeaderFields ?? [:] unwrappedHeaders.forEach { key, value in newHTTPHeaderFields[key] = value } return newHTTPHeaderFields } } /// Extension for converting an `Endpoint` into an optional `URLRequest`. extension Endpoint { /// Returns the `Endpoint` converted to a `URLRequest` if valid. Returns `nil` otherwise. public var urlRequest: URLRequest? { guard let requestURL = Foundation.URL(string: url) else { return nil } var request = URLRequest(url: requestURL) request.httpMethod = method.rawValue request.allHTTPHeaderFields = httpHeaderFields return try? parameterEncoding.encode(request, with: parameters) } } /// Required for using `Endpoint` as a key type in a `Dictionary`. extension Endpoint: Equatable, Hashable { public var hashValue: Int { return urlRequest?.hashValue ?? url.hashValue } public static func == <T>(lhs: Endpoint<T>, rhs: Endpoint<T>) -> Bool { if lhs.urlRequest != nil, rhs.urlRequest == nil { return false } if lhs.urlRequest == nil, rhs.urlRequest != nil { return false } if lhs.urlRequest == nil, rhs.urlRequest == nil { return lhs.hashValue == rhs.hashValue } return (lhs.urlRequest == rhs.urlRequest) } }
5f655a8000e5fc832fbb996f63b86e17
41.898305
202
0.692019
false
false
false
false
cnbin/LayerPlayer
refs/heads/master
LayerPlayer/CATiledLayerViewController.swift
mit
3
// // CATiledLayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 11/17/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit class CATiledLayerViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var zoomLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var viewForTiledLayer: TilingView! @IBOutlet weak var fadeDurationSlider: UISlider! @IBOutlet weak var fadeDurationSliderValueLabel: UILabel! @IBOutlet weak var tileSizeSlider: UISlider! @IBOutlet weak var tileSizeSliderValueLabel: UILabel! @IBOutlet weak var levelsOfDetailSlider: UISlider! @IBOutlet weak var levelsOfDetailSliderValueLabel: UILabel! @IBOutlet weak var detailBiasSlider: UISlider! @IBOutlet weak var detailBiasSliderValueLabel: UILabel! @IBOutlet weak var zoomScaleSlider: UISlider! @IBOutlet weak var zoomScaleSliderValueLabel: UILabel! var tiledLayer: TiledLayer { return viewForTiledLayer.layer as TiledLayer } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() scrollView.contentSize = scrollView.frame.size updateFadeDurationSliderValueLabel() updateTileSizeSliderValueLabel() updateLevelsOfDetailSliderValueLabel() updateDetailBiasSliderValueLabel() updateZoomScaleSliderValueLabel() } deinit { TiledLayer.setFadeDuration(CFTimeInterval(0.25)) } // MARK: - IBActions @IBAction func fadeDurationSliderChanged(sender: UISlider) { TiledLayer.setFadeDuration(CFTimeInterval(sender.value)) updateFadeDurationSliderValueLabel() tiledLayer.contents = nil tiledLayer.setNeedsDisplayInRect(tiledLayer.bounds) } @IBAction func tileSizeSliderChanged(sender: UISlider) { let value = Int(sender.value) tiledLayer.tileSize = CGSize(width: value, height: value) updateTileSizeSliderValueLabel() } @IBAction func levelsOfDetailSliderChanged(sender: UISlider) { tiledLayer.levelsOfDetail = UInt(sender.value) updateLevelsOfDetailSliderValueLabel() } @IBAction func levelsOfDetailSliderTouchedUp(sender: AnyObject) { showZoomLabel() } func showZoomLabel() { zoomLabel.alpha = 1.0 zoomLabel.hidden = false let label = zoomLabel UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: { label.alpha = 0 }, completion: { _ in label.hidden = true }) } @IBAction func detailBiasSliderChanged(sender: UISlider) { tiledLayer.levelsOfDetailBias = UInt(sender.value) updateDetailBiasSliderValueLabel() } @IBAction func detailBiasSliderTouchedUp(sender: AnyObject) { showZoomLabel() } @IBAction func zoomScaleSliderChanged(sender: UISlider) { scrollView.zoomScale = CGFloat(sender.value) updateZoomScaleSliderValueLabel() } // MARK: - Helpers func updateFadeDurationSliderValueLabel() { fadeDurationSliderValueLabel.text = String(format: "%.2f", adjustableFadeDuration) } func updateTileSizeSliderValueLabel() { tileSizeSliderValueLabel.text = "\(Int(tiledLayer.tileSize.width))" } func updateLevelsOfDetailSliderValueLabel() { levelsOfDetailSliderValueLabel.text = "\(tiledLayer.levelsOfDetail)" } func updateDetailBiasSliderValueLabel() { detailBiasSliderValueLabel.text = "\(tiledLayer.levelsOfDetailBias)" } func updateZoomScaleSliderValueLabel() { zoomScaleSliderValueLabel.text = "\(Int(scrollView.zoomScale))" } // MARK: UIScrollViewDelegate func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! { return viewForTiledLayer } func scrollViewDidZoom(scrollView: UIScrollView!) { zoomScaleSlider.setValue(Float(scrollView.zoomScale), animated: true) updateZoomScaleSliderValueLabel() } }
d5a40edf49d0a841fde9618a6617d897
28.607692
86
0.742531
false
false
false
false
colemancda/Pedido
refs/heads/master
Pedido Admin/Pedido Admin/PickerViewController.swift
mit
1
// // PickerViewController.swift // Pedido Admin // // Created by Alsey Coleman Miller on 12/10/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import UIKit import CoreData import CorePedido import CorePedidoClient /** View controller for editing to-many relationships between entities. It allows selection from a list of existing items. */ class PickerViewController: FetchedResultsViewController { // MARK: - Properties var relationship: (NSManagedObject, String)? { didSet { // create fetch request if relationship != nil { let (managedObject, key) = self.relationship! let relationshipDescription = managedObject.entity.relationshipsByName[key] as? NSRelationshipDescription assert(relationshipDescription != nil, "Relationship \(key) not found on \(managedObject.entity.name!) entity") assert(relationshipDescription!.toMany, "Relationship \(key) on \(managedObject.entity.name!) is not to-many") let fetchRequest = NSFetchRequest(entityName: relationshipDescription!.destinationEntity!.name!) fetchRequest.sortDescriptors = [NSSortDescriptor(key: Store.sharedStore.resourceIDAttributeName, ascending: true)] self.fetchRequest = fetchRequest } else { self.fetchRequest = nil } } } // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } // MARK: - Methods func selectManagedObject(managedObject: NSManagedObject) { let (parentManagedObject, relationshipName) = self.relationship! let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet var newRelationshipValue: NSSet? if relationshipValue?.containsObject(managedObject) ?? false { // remove... let arrayValue = (relationshipValue!.allObjects as NSArray).mutableCopy() as NSMutableArray arrayValue.removeObject(managedObject) newRelationshipValue = NSSet(array: arrayValue) } else { // add to set... var arrayValue: NSMutableArray? if relationshipValue != nil { arrayValue = (relationshipValue!.allObjects as NSArray).mutableCopy() as? NSMutableArray } else { arrayValue = NSMutableArray() } arrayValue!.addObject(managedObject) newRelationshipValue = NSSet(array: arrayValue!) } // edit managed object Store.sharedStore.editManagedObject(parentManagedObject, changes: [relationshipName: newRelationshipValue!], completionBlock: { (error) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in // show error if error != nil { self.showErrorAlert(error!.localizedDescription, retryHandler: { () -> Void in self.selectManagedObject(managedObject) }) return } }) }) } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // get model object let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject let dateCached = managedObject.valueForKey(Store.sharedStore.dateCachedAttributeName!) as? NSDate let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) // only set selection if managed object was cached if dateCached != nil { // set selection let (parentManagedObject, relationshipName) = self.relationship! let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet if relationshipValue?.containsObject(managedObject) ?? false { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } } return cell } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // remove or add to relationship... let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject self.selectManagedObject(managedObject) tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - NSFetchedResultsControllerDelegate override func controller(controller: NSFetchedResultsController, didChangeObject object: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) { switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) case .Update: if let cell = self.tableView.cellForRowAtIndexPath(indexPath) { self.configureCell(cell, atIndexPath: indexPath) // get model object let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject let dateCached = managedObject.valueForKey(Store.sharedStore.dateCachedAttributeName!) as? NSDate // only set selection if managed object was cached if dateCached != nil { // set selection let (parentManagedObject, relationshipName) = self.relationship! let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet if relationshipValue?.containsObject(managedObject) ?? false { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } } } case .Move: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) default: return } } }
9da1ab695de2a85312b9907db0e2c1b7
34.638889
154
0.541829
false
false
false
false
vantist/CWEPBU_Library
refs/heads/master
platforms/ios/Hello World/Plugins/com.gss.pdfrenderer/PDFRenderer.swift
mit
1
// // MuPDF.swift // mupdf // // Created by Zam-mbpr on 2015/3/4. // // import Foundation @objc(PDFRenderer) class PDFRenderer : CDVPlugin { var core: PDFRendererCore? let DataBin: Int = 0 let DataUrl: Int = 1 let FileUri: Int = 2 let Jpeg: Int = 0 let Png: Int = 1 let Path: Int = 0 let Buffer: Int = 1 let NumberOfPage: String = "numberOfPage" let PageWidth: String = "width" let PageHeight: String = "height" let FilePath: String = "path" let FileName: String = "name" var SystemPath: String; var fileName: String; var filePath: String; var numberOfPage: Int; var currentPage: Int; var customPath: String; override init(webView theWebView: UIWebView!) { self.core = PDFRendererCore() self.fileName = "" self.filePath = "" self.numberOfPage = 0 self.currentPage = 0 self.customPath = "" self.SystemPath = NSHomeDirectory() + "/Documents" super.init() } func open(command: CDVInvokedUrlCommand) { commandDelegate!.runInBackground({ var content: AnyObject = command.arguments[0] as AnyObject var openType = command.arguments[1] as! Int var password = command.arguments[2] as! String var cPassword = password.cStringUsingEncoding(NSUTF8StringEncoding)! var pluginResult: CDVPluginResult? self.closeFile() if let result = self.openFile(content, openType: openType) { pluginResult = result } else { if let result = self.checkPassword(password) { pluginResult = result } else { if let result = self.checkPDFReady() { pluginResult = result } else { pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: self.preparePDFInfo()) } } } self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) } func close(command: CDVInvokedUrlCommand) { commandDelegate!.runInBackground({ self.closeFile() var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) } func getPage(command: CDVInvokedUrlCommand) { commandDelegate!.runInBackground({ if !self.checkFileOpen() { var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Please open a file.") self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) return } let index = command.arguments[0] as! NSNumber var pageSize: CGSize = self.core!.getPageSize(index.intValue) var patchRect: CGRect = CGRect() pageSize.width = command.arguments[1] as! Int == -1 ? pageSize.width : command.arguments[1] as! CGFloat pageSize.height = command.arguments[2] as! Int == -1 ? pageSize.height : command.arguments[2] as! CGFloat patchRect.origin.x = command.arguments[3] as! CGFloat patchRect.origin.y = command.arguments[4] as! CGFloat patchRect.size.width = command.arguments[5] as! Int == -1 ? pageSize.width : command.arguments[5] as! CGFloat patchRect.size.height = command.arguments[6] as! Int == -1 ? pageSize.height : command.arguments[6] as! CGFloat let quality = command.arguments[7] as! CGFloat let encodingType = command.arguments[8] as! Int let destinationType = command.arguments[9] as! Int let destinationPath = command.arguments[10] as! String self.currentPage = index.integerValue var image: UIImage? = self.core!.drawPage(index.intValue, pageSize: pageSize, patchRect: patchRect) var pluginResult: CDVPluginResult? = nil var data: NSData var format:String if encodingType == self.Jpeg { data = UIImageJPEGRepresentation(image!, quality)! format = ".jpeg" } else { data = UIImagePNGRepresentation(image!)! format = ".png" } if destinationType == self.DataBin { // array buffer pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArrayBuffer: data) } else if destinationType == self.DataUrl { // base64 pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: data.base64EncodedString()) } else if destinationType == self.FileUri { // file path var path: String = self.SystemPath if (!destinationPath.isEmpty) { path = path + self.addSlashFirstAndLast(destinationPath) } else if (!self.customPath.isEmpty) { path = path + "/" + self.addSlashFirstAndLast(self.customPath) } else { path = path + self.fileName + "/" } path = path + String(self.currentPage) + format data.writeToFile(path, atomically: true) pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: path) } self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) } func getPageInfo(command: CDVInvokedUrlCommand) { commandDelegate!.runInBackground({ if !self.checkFileOpen() { var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Please open a file.") self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) return } let n = command.accessibilityElementAtIndex(0) == nil ? self.currentPage : command.arguments[0] as! Int let index: NSNumber = n >= self.numberOfPage ? self.numberOfPage - 1 : n let pageSize: CGSize = self.core!.getPageSize(index.intValue) var result:Dictionary<String, AnyObject> = Dictionary() result[self.NumberOfPage] = self.numberOfPage result[self.PageWidth] = pageSize.width result[self.PageHeight] = pageSize.height var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: result) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) } func getPDFInfo(command: CDVInvokedUrlCommand) { commandDelegate!.runInBackground({ if !self.checkFileOpen() { var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Please open a file.") self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) return } var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: self.preparePDFInfo()) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) } func changePreference(command: CDVInvokedUrlCommand) { self.customPath = command.arguments[0] as! String var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: self.preparePDFInfo()) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } private func preparePDFInfo() -> Dictionary<String, AnyObject> { var result:Dictionary<String, AnyObject> = Dictionary() result[self.NumberOfPage] = self.numberOfPage result[self.FileName] = self.fileName result[self.FilePath] = self.filePath return result } private func checkPassword(password: String) -> CDVPluginResult? { var pluginResult:CDVPluginResult? if self.core!.needsPassword() { var cPassword = password.cStringUsingEncoding(NSUTF8StringEncoding)! // if count(password.utf16) == 0 { if password.isEmpty { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "The PDF needs password.") } else if !self.core!.authenticatePassword(&cPassword) { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Password incorrect.") } } return pluginResult } private func checkPDFReady() -> CDVPluginResult? { var pluginResult:CDVPluginResult? self.numberOfPage = self.core!.countPages() if self.numberOfPage == 0 { self.closeFile() pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Can not open document.") } return pluginResult } private func openFile(content: AnyObject, openType: Int) -> CDVPluginResult? { var pluginResult:CDVPluginResult? if openType == self.Path { let path = content as! String self.fileName = self.getFileName(path) self.filePath = path // var nspath = NSHomeDirectory() + "/Documents/" + path // var cPath = nspath.cStringUsingEncoding(NSUTF8StringEncoding)! var cPath = path.cStringUsingEncoding(NSUTF8StringEncoding)! if !self.core!.openFile(&cPath) { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Can not open document.") } } else { // var buffer: NSData = content as NSData // var magic = "".cStringUsingEncoding(NSUTF8StringEncoding)! // if !self.core!.openFile(buffer, magic: &magic) { // pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Can not open document.") // } pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "iOS not support open buffer yet.") } return pluginResult } private func checkFileOpen() -> Bool { return self.core!.isFileOpen() } private func getFileName(path: String) -> String { if let slashRange = path.rangeOfString("/") { let fileName = path.substringFromIndex(slashRange.endIndex) return getFileName(fileName) } else { if let dotRange = path.rangeOfString(".") { return path.substringToIndex(dotRange.startIndex) } else { return path } } } private func closeFile() { self.core!.closeFile() self.fileName = ""; self.filePath = ""; self.numberOfPage = 0; self.currentPage = 0; } private func addSlashFirstAndLast(destinationPath: String) -> String { var path = destinationPath if path[path.startIndex] != "/" { path = "/" + path } if path[path.endIndex.advancedBy(-1)] != "/" { path = path + "/" } return path } }
30f07c45721fcd130d3e5875cce98685
41.424354
127
0.601688
false
false
false
false
ducyen/ClasHStamP
refs/heads/master
samples/CalcOrtho/swift/Main/CalcModel.swift
gpl-3.0
3
import Foundation import Main.Statemachine import Main.CalcOperand import Main.CalcView class CalcModel : System.Object { public class OPER_PARAMS { public var key: char } public class DIGIT_1_9_PARAMS { public var digit: char } public enum TestNestedEnum { case ONE case TWO case THREE } var _stm: Statemachine var _intEntry: string var _fracEntry: string var _signEntry: char var _operEntry: char var _operand1: double var _entry: string var _operand_input: CalcOperand var _testNestedEnumAttr: TestNestedEnum var _testNestedEnumProb: TestNestedEnum var _calcView: CalcView UInt32 nOnHistory; public init ( entry: string ) { _stm = Value0 _intEntry = "" _fracEntry = "" _signEntry = ' ' _operEntry = ' ' _operand1 = 0f _entry = entry _operand_input = new CalcOperand(this) _testNestedEnumAttr = TestNestedEnum.ONE _testNestedEnumProb = TestNestedEnum.ONE _calcView = new CalcView() nOnHistory = ON; } public void insertInt( char digit) { _intEntry = _intEntry + digit; _calcView.Update(entry); } // insertInt public void insertFrac( char digit) { _fracEntry = _fracEntry + digit; _calcView.Update(entry); } // insertFrac public void negate() { _signEntry = '-'; _calcView.Update(entry); } // negate public void set( char digit) { _intEntry = digit.ToString(); _fracEntry = ""; _calcView.Update(entry); } // set public void clear() { _signEntry = ' '; set( '0' ); } // clear public void setOper( char key) { _operEntry = key; _calcView.Update(entry); } // setOper public bool calculate() { bool error = false; switch (_operEntry) { case '+': _operand1 = _operand1 + curOperand; break; case '-': _operand1 = _operand1 - curOperand; break; case '*': _operand1 = _operand1 * curOperand; break; case '/': if (curOperand == 0f) { error = true; } else { _operand1 = _operand1 / curOperand; } break; } return error; } // calculate public void showResult() { string result = _operand1.ToString("0.########"); int dotPos = result.IndexOf("."); string intRslt = "0"; string fracRslt = ""; if (dotPos >= 0) { intRslt = result.Substring(0, dotPos); fracRslt = result.Substring(dotPos + 1); } else { intRslt = result.Substring(0); } _calcView.Update(intRslt + "." + fracRslt + _operEntry); } // showResult public void showError() { _calcView.Update("Err" + _operEntry); } // showError public TestNestedEnumOper(x: TestNestedEnum): TestNestedEnum { return x; } // TestNestedEnumOper public var stm: Statemachine { get { return _stm } set { _stm = newValue } } public var entry: string { get { return _entry } set { _entry = newValue } } public var curOperand: double { XXX } public var testNestedEnumProb: TestNestedEnum { get { return _testNestedEnumProb } set { _testNestedEnumProb = newValue } } const UInt32 RESULT = 1; const UInt32 BEGIN = 2; const UInt32 ERROR = 4; const UInt32 OP_ENTERED = 8; const UInt32 OPERAND_INPUT1 = 16; const UInt32 OPERAND_INPUT2 = 32; const UInt32 POWER_SAVE = 64; const UInt32 STM = UInt32.MaxValue; const UInt32 ON = ( READY | ERROR | OP_ENTERED | OPERAND_INPUT1 | OPERAND_INPUT2 ); const UInt32 READY = ( RESULT | BEGIN ); internal enum CALC_MODEL_EVENT { case AC case CE case DIGIT_0 case DIGIT_1_9 case EQUALS case OFF case OPER case POINT case PSAVE_OFF case PSAVE_ON } void EndTrans( bool isFinished ){ _stm.nCurrentState = _stm.nTargetState; _stm.bIsFinished = isFinished; _stm.bIsExternTrans = false; if( isFinished ){ return; } switch( _stm.nCurrentState ){ case ON: On_Entry(); break; case READY: Ready_Entry(); break; case RESULT: Result_Entry(); break; case BEGIN: Begin_Entry(); break; case ERROR: Error_Entry(); break; case OP_ENTERED: OpEntered_Entry(); break; case OPERAND_INPUT1: OperandInput1_Entry(); break; case OPERAND_INPUT2: OperandInput2_Entry(); break; case POWER_SAVE: PowerSave_Entry(); break; default: break; } } void BgnTrans( UInt32 sourceState, UInt32 targetState ){ _stm.nSourceState = sourceState; _stm.nTargetState = targetState; switch( _stm.nCurrentState ){ case ON: On_Exit(); break; case READY: Ready_Exit(); break; case RESULT: Result_Exit(); break; case BEGIN: Begin_Exit(); break; case ERROR: Error_Exit(); break; case OP_ENTERED: OpEntered_Exit(); break; case OPERAND_INPUT1: OperandInput1_Exit(); break; case OPERAND_INPUT2: OperandInput2_Exit(); break; case POWER_SAVE: PowerSave_Exit(); break; default: break; } } public bool RunToCompletion(){ bool bResult; do{ if( Statemachine.IsComposite( _stm.nCurrentState ) && !_stm.bIsFinished ){ bResult = Start(); }else{ bResult = Done(); } }while( bResult ); if (IsFinished() && _stm.pParentContext != null) { _stm.pParentContext.runToCompletion(); } return bResult; } public bool IsFinished() { return _stm.bIsFinished && _stm.nCurrentState == STM; } public bool IsEventHandled( bool bReset ) { _stm.bIsEventHandled &= !bReset; return _stm.bIsEventHandled; } public bool Abort() { BgnTrans( STM, STM ); EndTrans( true ); return true; } bool EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; if (IsFinished()) { return bResult; } bResult |= _operand_input.IsEventHandled( true ); switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.CE:{ _operand_input.Ce( ); } break; case CALC_MODEL_EVENT.DIGIT_0:{ _operand_input.Digit0( ); } break; case CALC_MODEL_EVENT.DIGIT_1_9:{ CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams; _operand_input.Digit19(e.digit ); } break; case CALC_MODEL_EVENT.EQUALS:{ _operand_input.Equals( ); } break; case CALC_MODEL_EVENT.OPER:{ CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams; _operand_input.Oper(e.key ); } break; case CALC_MODEL_EVENT.POINT:{ _operand_input.Point( ); } break; default: break; } switch( _stm.nCurrentState ){ case ON: bResult = On_EventProc( nEventId, pEventParams ); break; case READY: bResult = Ready_EventProc( nEventId, pEventParams ); break; case RESULT: bResult = Result_EventProc( nEventId, pEventParams ); break; case BEGIN: bResult = Begin_EventProc( nEventId, pEventParams ); break; case ERROR: bResult = Error_EventProc( nEventId, pEventParams ); break; case OP_ENTERED: bResult = OpEntered_EventProc( nEventId, pEventParams ); break; case OPERAND_INPUT1: bResult = OperandInput1_EventProc( nEventId, pEventParams ); break; case OPERAND_INPUT2: bResult = OperandInput2_EventProc( nEventId, pEventParams ); break; case POWER_SAVE: bResult = PowerSave_EventProc( nEventId, pEventParams ); break; default: break; } return bResult; } void On_Entry(){ if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){ _operand_input.Start(); _operand_input.RunToCompletion(); _stm.nLCAState = 0; } } bool On_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.AC:{ _stm.bIsExternTrans = true; BgnTrans( ON, ON ); _operEntry = ' '; EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.OFF:{ BgnTrans( ON, STM ); EndTrans( true ); bResult = true; } break; case CALC_MODEL_EVENT.PSAVE_ON:{ BgnTrans( ON, POWER_SAVE ); EndTrans( false ); bResult = true; } break; default: break; } bResult |= _operand_input.IsEventHandled( false ); return bResult; } void On_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ON ) && Statemachine.IsIn( _stm.nTargetState, ON ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; _operand_input.Abort(); } else { _stm.nLCAState = ON; } } void Ready_Entry(){ if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){ On_Entry(); _signEntry = ' '; nOnHistory = READY; _stm.nLCAState = 0; } } bool Ready_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.DIGIT_0:{ BgnTrans( READY, OPERAND_INPUT1 ); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.DIGIT_1_9:{ CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams; BgnTrans( READY, OPERAND_INPUT1 ); set(e.digit); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.POINT:{ BgnTrans( READY, OPERAND_INPUT1 ); EndTrans( false ); bResult = true; } break; default: break; } return bResult ? bResult : On_EventProc( nEventId, pEventParams ); } void Ready_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, READY ) && Statemachine.IsIn( _stm.nTargetState, READY ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; On_Exit(); } else { _stm.nLCAState = READY; } } void Result_Entry(){ if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){ Ready_Entry(); _stm.nLCAState = 0; } } bool Result_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; return bResult ? bResult : Ready_EventProc( nEventId, pEventParams ); } void Result_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, RESULT ) && Statemachine.IsIn( _stm.nTargetState, RESULT ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; Ready_Exit(); } else { _stm.nLCAState = RESULT; } } void Begin_Entry(){ if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){ Ready_Entry(); clear(); _stm.nLCAState = 0; } } bool Begin_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.OPER:{ CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams; if (e.key == '-') { BgnTrans( BEGIN, OPERAND_INPUT1 ); EndTrans( false ); bResult = true; } } break; default: break; } return bResult ? bResult : Ready_EventProc( nEventId, pEventParams ); } void Begin_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, BEGIN ) && Statemachine.IsIn( _stm.nTargetState, BEGIN ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; Ready_Exit(); } else { _stm.nLCAState = BEGIN; } } void Error_Entry(){ if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){ On_Entry(); showError(); nOnHistory = ERROR; _stm.nLCAState = 0; } } bool Error_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; return bResult ? bResult : On_EventProc( nEventId, pEventParams ); } void Error_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ERROR ) && Statemachine.IsIn( _stm.nTargetState, ERROR ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; On_Exit(); } else { _stm.nLCAState = ERROR; } } void OpEntered_Entry(){ if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){ On_Entry(); _signEntry = ' '; nOnHistory = OP_ENTERED; _stm.nLCAState = 0; } } bool OpEntered_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.DIGIT_0:{ BgnTrans( OP_ENTERED, OPERAND_INPUT2 ); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.DIGIT_1_9:{ CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams; BgnTrans( OP_ENTERED, OPERAND_INPUT2 ); set(e.digit); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.OPER:{ CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams; if (e.key == '-') { BgnTrans( OP_ENTERED, OPERAND_INPUT2 ); EndTrans( false ); bResult = true; } } break; case CALC_MODEL_EVENT.POINT:{ BgnTrans( OP_ENTERED, OPERAND_INPUT2 ); EndTrans( false ); bResult = true; } break; default: break; } return bResult ? bResult : On_EventProc( nEventId, pEventParams ); } void OpEntered_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OP_ENTERED ) && Statemachine.IsIn( _stm.nTargetState, OP_ENTERED ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; On_Exit(); } else { _stm.nLCAState = OP_ENTERED; } } void OperandInput1_Entry(){ if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){ On_Entry(); nOnHistory = OPERAND_INPUT1; _stm.nLCAState = 0; } } bool OperandInput1_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.CE:{ BgnTrans( OPERAND_INPUT1, BEGIN ); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.OPER:{ CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams; BgnTrans( OPERAND_INPUT1, OP_ENTERED ); _operand1 = curOperand; setOper( e.key ); EndTrans( false ); bResult = true; } break; default: break; } return bResult ? bResult : On_EventProc( nEventId, pEventParams ); } void OperandInput1_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT1 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT1 ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; On_Exit(); } else { _stm.nLCAState = OPERAND_INPUT1; } } void OperandInput2_Entry(){ if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){ On_Entry(); nOnHistory = OPERAND_INPUT2; _stm.nLCAState = 0; } } bool OperandInput2_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.CE:{ BgnTrans( OPERAND_INPUT2, OP_ENTERED ); clear(); EndTrans( false ); bResult = true; } break; case CALC_MODEL_EVENT.EQUALS:{ bool error = calculate(); if (error) { BgnTrans( OPERAND_INPUT2, ERROR ); EndTrans( false ); bResult = true; } else { BgnTrans( OPERAND_INPUT2, RESULT ); _operEntry = ' '; showResult(); EndTrans( false ); bResult = true; } } break; case CALC_MODEL_EVENT.OPER:{ CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams; bool error = calculate(); setOper( e.key ); if (error) { BgnTrans( OPERAND_INPUT2, ERROR ); EndTrans( false ); bResult = true; } else { BgnTrans( OPERAND_INPUT2, OP_ENTERED ); showResult(); EndTrans( false ); bResult = true; } } break; default: break; } return bResult ? bResult : On_EventProc( nEventId, pEventParams ); } void OperandInput2_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT2 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT2 ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; On_Exit(); } else { _stm.nLCAState = OPERAND_INPUT2; } } void PowerSave_Entry(){ if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){ _stm.nLCAState = 0; } } bool PowerSave_EventProc( UInt32 nEventId, Object pEventParams ){ bool bResult = false; switch( ( CALC_MODEL_EVENT )nEventId ){ case CALC_MODEL_EVENT.PSAVE_OFF:{ BgnTrans( POWER_SAVE, nOnHistory ); EndTrans( false ); bResult = true; } break; default: break; } return bResult; } void PowerSave_Exit(){ bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, POWER_SAVE ) && Statemachine.IsIn( _stm.nTargetState, POWER_SAVE ); if( !isThisLCA || _stm.bIsExternTrans ){ _stm.bIsExternTrans &= !isThisLCA; } else { _stm.nLCAState = POWER_SAVE; } } public bool Start( ){ bool bResult = false; _stm.bIsFinished = false; switch( _stm.nCurrentState ){ case STM:{ BgnTrans( STM, ON ); _calcView.DrawFrame(); EndTrans( false ); bResult = true; } break; case ON:{ BgnTrans( ON, READY ); EndTrans( false ); bResult = true; } break; case READY:{ BgnTrans( READY, BEGIN ); EndTrans( false ); bResult = true; } break; default: break; } return bResult; } public void Ac( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.AC, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Ce( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.CE, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Digit0( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_0, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Digit19( char digit ) { Object pEventParams = null; CalcModel.DIGIT_1_9_PARAMS eventParams = new CalcModel.DIGIT_1_9_PARAMS(); pEventParams = ( Object )eventParams; eventParams.digit = digit; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_1_9, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Equals( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.EQUALS, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Off( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OFF, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Oper( char key ) { Object pEventParams = null; CalcModel.OPER_PARAMS eventParams = new CalcModel.OPER_PARAMS(); pEventParams = ( Object )eventParams; eventParams.key = key; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OPER, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void Point( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.POINT, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void PsaveOff( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_OFF, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public void PsaveOn( ) { Object pEventParams = null; _stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_ON, pEventParams ); _stm.bIsEventHandled |= RunToCompletion(); } public bool Done( ){ bool bResult = false; return bResult; } } }
22e113263b62030771551efebad62eb7
31.816384
138
0.531764
false
false
false
false
jwamin/Xnpm
refs/heads/master
Xnpm/ConsoleViewController.swift
mit
1
// // ConsoleViewController.swift // Xnpm // // Created by Joss Manger on 6/29/17. // Copyright © 2017 Joss Manger. All rights reserved. // import Cocoa class ConsoleViewController: NSViewController,NSWindowDelegate { @IBOutlet weak var touchBarButton: NSButton! @IBOutlet var textView: NSTextView! var parentController:ViewController? @IBOutlet weak var indicator: NSProgressIndicator! override func viewDidLoad() { NotificationCenter.default.addObserver(self, selector: #selector(handleText), name: NSNotification.Name(rawValue: "gotOut"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleEnd), name: NSNotification.Name(rawValue: "gotEnd"), object: nil) // if #available(OSX 10.12.2, *) { // touchBarButton.image = NSImage(named: NSImageNameTouchBarRecordStopTemplate) // indicator.startAnimation(self) // } } override func viewDidAppear() { self.view.window?.delegate = self; if #available(OSX 10.12.2, *) { self.view.window?.unbind(#keyPath(touchBar)) // unbind first self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil) } } override func awakeFromNib() { //print("hello world") textView.font = NSFont(name: "Andale Mono", size: 11.0) } func handleText(notification:NSNotification){ //print(notification.object ?? "none") let dict = notification.object as! NSDictionary let str = dict.object(forKey: "str") as! String let notificationID = dict.object(forKey: "sender") as! String if let identifier = parentController?.package.packageTitle{ if(identifier==notificationID){ updateTextView(str: str) } } } func handleEnd(notification:NSNotification){ //print(notification.object ?? "none") updateTextView(str: notification.object as! String) } func updateTextView(str:String){ // Smart Scrolling let scroll = (NSMaxY(textView.visibleRect) == NSMaxY(textView.bounds)); // Append string to textview textView.textStorage?.append(NSAttributedString(string: str)) //Set Font textView.textStorage?.font = NSFont(name: "Andale Mono", size: 11.0) if (scroll){ textView.scrollRangeToVisible(NSMakeRange((textView.string?.count)!, 0)); }// Scroll to end of the textview contents } func windowShouldClose(_ sender: Any) -> Bool { self.parentController?.executeScript(sender: self) return false; } func removeObservers(){ NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotOut"), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotEnd"), object: nil) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } override func viewDidDisappear() { removeObservers() } deinit { if #available(OSX 10.12.2, *) { self.view.window?.unbind(#keyPath(touchBar)) } } }
4f069dd95e2d7af5a854039635899dce
29.882883
145
0.612894
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Common/CloudKitSync/FavoriteCardUploader.swift
mit
2
// // FavoriteCardUploader.swift // DereGuide // // Created by zzk on 2017/7/27. // Copyright © 2017 zzk. All rights reserved. // import CoreData /// use local favorite card to create remote favorite card final class FavoriteCardUploader: ElementChangeProcessor { typealias Element = FavoriteCard var remote: FavoriteCardsRemote init(remote: FavoriteCardsRemote) { self.remote = remote } var elementsInProgress = InProgressTracker<FavoriteCard>() func setup(for context: ChangeProcessorContext) { // no-op } func processChangedLocalElements(_ objects: [FavoriteCard], in context: ChangeProcessorContext) { processInsertedFavoriteCards(objects, in: context) } func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], in context: ChangeProcessorContext, completion: () -> ()) { completion() } func fetchLatestRemoteRecords(in context: ChangeProcessorContext) { // no-op } var predicateForLocallyTrackedElements: NSPredicate { return FavoriteCard.waitingForUploadPredicate } } extension FavoriteCardUploader { fileprivate func processInsertedFavoriteCards(_ insertions: [FavoriteCard], in context: ChangeProcessorContext) { remote.upload(insertions) { (remoteFavoriteCards, error) in context.perform { guard !(error?.isPermanent ?? false) else { // Since the error was permanent, delete these objects: insertions.forEach { $0.markForLocalDeletion() } self.elementsInProgress.markObjectsAsComplete(insertions) return } // currently not retry for temporarily error // set unit remote id for favoriteCard in insertions { guard let remoteFavoriteCard = remoteFavoriteCards.first(where: { favoriteCard.createdAt == $0.localCreatedAt }) else { continue } favoriteCard.creatorID = remoteFavoriteCard.creatorID favoriteCard.remoteIdentifier = remoteFavoriteCard.id } context.delayedSaveOrRollback() if Config.cloudKitDebug && insertions.count > 0 { print("favorite card uploader: upload \(insertions.count) success \(insertions.filter { $0.remoteIdentifier != nil }.count)") } self.elementsInProgress.markObjectsAsComplete(insertions) } } } }
1638afe60ed066fbe001aa4cf9e70310
34.547945
150
0.625434
false
false
false
false
17thDimension/AudioKit
refs/heads/develop
Examples/OSX/Swift/HelloWorld/HelloWorld/ViewController.swift
lgpl-3.0
5
// // ViewController.swift // HelloWorld // // Created by Nicholas Arner on 2/28/15. // Copyright (c) 2015 AudioKit. All rights reserved. // import Cocoa class ViewController: NSViewController { // STEP 1 : Set up an instance variable for the instrument let instrument = AKInstrument() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // STEP 2 : Define the instrument as a simple oscillator let oscillator = AKOscillator() instrument.connect(oscillator) instrument.connect(AKAudioOutput(audioSource: oscillator)) // STEP 3 : Add the instrument to the orchestra and start the orchestra AKOrchestra.addInstrument(instrument) AKOrchestra.start() } // STEP 4 : React to a button press on the Storyboard UI by // playing or stopping the instrument and updating the button text. @IBAction func toggleSound(sender: NSButton){ if !(sender.title == "Stop") { instrument.play() sender.title = "Stop" } else { instrument.stop() sender.title = "Play Sine Wave at 440HZ" } } }
e0c4b13d1336404aab106bd603075623
29
80
0.62381
false
false
false
false
alexcurylo/chatalyzer
refs/heads/master
Chatalyzer/Chatalyzer/source/ViewController.swift
mit
1
// // ViewController.swift // Chatalyzer // // Created by alex on 2016-04-28. // Copyright © 2016 Trollwerks Inc. All rights reserved. // import UIKit /// Takes string input from user and displays its parsed contents. class ViewController: UIViewController, UITextFieldDelegate { // MARK: - Properties @IBOutlet weak var chatView: UITextField! @IBOutlet weak var resultView: UITextView! @IBOutlet weak var stackBottom: NSLayoutConstraint! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() chatView.addTarget(self, action: #selector(onChatChange), forControlEvents: .EditingChanged) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChange), name:UIKeyboardWillChangeFrameNotification, object:nil) } // MARK: - Text input handling func onChatChange(sender: AnyObject?) { if let legalJSON = chatView.text?.chatalysis() { // Make it more readable for display let legalHTML = legalJSON.stringByReplacingOccurrencesOfString("\\/", withString: "/") resultView.text = legalHTML.stringByDecodingHTMLEntities } else { resultView.text = nil } } func textFieldShouldReturn(textField: UITextField) -> Bool { view.endEditing(true) return true } func keyboardWillChange(notification: NSNotification) { let userInfo = notification.userInfo! let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window) let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window) let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y stackBottom.constant -= originDelta view.setNeedsUpdateConstraints() UIView.animateWithDuration(animationDuration, delay:0, options:.BeginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) } }
754430e43271aa938cd6b0530f6b726b
36.169231
159
0.701159
false
false
false
false
DevAspirant/SwiftPro
refs/heads/master
PrimeCount.swift
gpl-2.0
1
/*------/ prime count /------*/ var number = 2 var isPrime = true for(var i=2;i<=number;i++){ if number % i == 0{ isPrime=false; } } print("is it Prime: " , isPrime);
01f521d3fe47740b29aae5e208e300a8
19.666667
33
0.5
false
false
false
false
Zglove/DouYu
refs/heads/master
DYTV/DYTV/Classes/Tools/Common.swift
mit
1
// // Common.swift // DYTV // // Created by people on 2016/10/28. // Copyright © 2016年 people2000. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabBarH : CGFloat = 44 let kScreenW : CGFloat = UIScreen.main.bounds.width let kScreenH : CGFloat = UIScreen.main.bounds.height
20e8bd176ff7ce5c690c0772c0bde14b
20.375
54
0.716374
false
false
false
false
scottkawai/sendgrid-swift
refs/heads/master
Tests/SendGridTests/API/V3/Mail/Send/EmailTests.swift
mit
1
@testable import SendGrid import XCTest class EmailTests: XCTestCase, EncodingTester { typealias EncodableObject = Email.Parameters let goodFrom = Address(email: "[email protected]") func generatePersonalizations(_ amount: Int) -> [Personalization] { Array(0..<amount).map { (i) -> Personalization in let recipient = Address(email: "test\(i)@example.none") return Personalization(to: [recipient]) } } func generateBaseEmail(_ subject: String? = "Hello World") -> Email { let personalization = self.generatePersonalizations(1) return Email( personalizations: personalization, from: self.goodFrom, content: [Content.plainText(body: "plain")], subject: subject ) } func testOnlyApiKeys() { do { let auth = try Authentication.credential(username: "foo", password: "bar") let session = Session(auth: auth) let goodContent = Content.emailBody(plain: "plain", html: "html") let email = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent, subject: "Test") try session.send(request: email) XCTFail("Expected an error to be thrown when using basic auth with the mail send API, but nothing was thrown.") } catch let SendGrid.Exception.Session.unsupportedAuthetication(desc) { XCTAssertEqual(desc, "credential") } catch { XCTFailUnknownError(error) } } func testNoImpersonation() { do { let auth = Authentication.apiKey("foobar") let session = Session(auth: auth, onBehalfOf: "baz") let goodContent = Content.emailBody(plain: "plain", html: "html") let email = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent, subject: "Test") try session.send(request: email) XCTFail("Expected an error to be thrown when impersonating a subuser with the mail send API, but nothing was thrown.") } catch SendGrid.Exception.Session.impersonationNotAllowed { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } func testEncoding() { let goodContent = Content.emailBody(plain: "plain", html: "html") let min = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent) let minExpectations: [String: Any] = [ "personalizations": [ [ "to": [ [ "email": "[email protected]" ] ] ] ], "from": [ "email": "[email protected]" ], "content": [ [ "type": "text/plain", "value": "plain" ], [ "type": "text/html", "value": "html" ] ] ] XCTAssertEncodedObject(min.parameters!, equals: minExpectations) let max = Email( personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent, subject: "Root Subject" ) max.parameters?.replyTo = "[email protected]" let data = Data(AttachmentTests.redDotBytes) max.parameters?.attachments = [Attachment(filename: "red.png", content: data)] max.parameters?.templateID = "1334949C-CE58-4A21-A633-47638EFA358A" max.parameters?.sections = [ ":male": "Mr. :name", ":female": "Ms. :name", ":neutral": ":name", ":event1": "New User Event on :event_date", ":event2": "Veteran User Appreciation on :event_date" ] max.parameters?.headers = [ "Foo": "Bar" ] max.parameters?.categories = ["Foo", "Bar"] max.parameters?.customArguments = [ "foo": "bar" ] max.parameters?.sendAt = Date(timeIntervalSince1970: 1505705165) max.parameters?.batchID = "foobar" max.parameters?.asm = ASM(groupID: 1234) max.parameters?.ipPoolName = "Marketing" max.parameters?.mailSettings.sandboxMode = SandboxMode() max.parameters?.trackingSettings.clickTracking = ClickTracking(section: .off) let maxExpectations: [String: Any] = [ "personalizations": [ [ "to": [ [ "email": "[email protected]" ] ] ] ], "from": [ "email": "[email protected]" ], "content": [ [ "type": "text/plain", "value": "plain" ], [ "type": "text/html", "value": "html" ] ], "subject": "Root Subject", "reply_to": [ "email": "[email protected]" ], "attachments": [ [ "content": AttachmentTests.dotBase64, "filename": "red.png", "disposition": "attachment" ] ], "template_id": "1334949C-CE58-4A21-A633-47638EFA358A", "sections": [ ":male": "Mr. :name", ":female": "Ms. :name", ":neutral": ":name", ":event1": "New User Event on :event_date", ":event2": "Veteran User Appreciation on :event_date" ], "headers": [ "Foo": "Bar" ], "categories": ["Foo", "Bar"], "custom_args": [ "foo": "bar" ], "send_at": 1505705165, "batch_id": "foobar", "asm": [ "group_id": 1234 ], "ip_pool_name": "Marketing", "mail_settings": [ "sandbox_mode": [ "enable": true ] ], "tracking_settings": [ "click_tracking": [ "enable": false ] ] ] XCTAssertEncodedObject(max.parameters!, equals: maxExpectations) } func testInitialization() { let personalization = self.generatePersonalizations(Constants.PersonalizationLimit) let goodContent = Content.emailBody(plain: "plain", html: "html") let good = Email(personalizations: personalization, from: self.goodFrom, content: goodContent) XCTAssertEqual(good.parameters!.personalizations.count, Constants.PersonalizationLimit) XCTAssertEqual(good.parameters!.personalizations[0].to[0].email, "[email protected]") XCTAssertEqual(good.parameters!.from.email, "[email protected]") XCTAssertEqual(good.parameters!.content?.count, 2) XCTAssertEqual(good.parameters!.content?[0].value, "plain") XCTAssertEqual(good.parameters!.content?[1].value, "html") XCTAssertNil(good.parameters!.subject) } func testPersonalizationValidation() { let goodContent = Content.emailBody(plain: "plain", html: "html") do { let empty = Email(personalizations: [], from: self.goodFrom, content: goodContent, subject: "Hello World") try empty.validate() XCTFail("Expected error to be thrown when initializing Email with an empty personalization array, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidNumberOfPersonalizations { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let over = self.generatePersonalizations(Constants.PersonalizationLimit + 1) let tooMany = Email(personalizations: over, from: self.goodFrom, content: goodContent, subject: "Hello World") try tooMany.validate() XCTFail("Expected error to be thrown when providing more than \(Constants.PersonalizationLimit) personalizations, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidNumberOfPersonalizations { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { // Over 1000 recipients should throw an error. let personalizations = Array(0...334).map( { (i) -> Personalization in let to = Address(email: "to\(i)@example.none") let cc = Address(email: "cc\(i)@example.none") let bcc = Address(email: "bcc\(i)@example.none") return Personalization(to: [to], cc: [cc], bcc: [bcc], subject: nil, headers: nil, substitutions: nil, customArguments: nil) } ) let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")]) try bad.validate() XCTFail("Expected an error to be thrown when an email contains more than \(Constants.RecipientLimit) total recipients, but nothing was thrown") } catch SendGrid.Exception.Mail.tooManyRecipients { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { // Under 1000 recipients should have no errors. let personalizations = Array(0...3).map( { (i) -> Personalization in let to = Address(email: "to\(i)@example.none") let cc = Address(email: "cc\(i)@example.none") let bcc = Address(email: "bcc\(i)@example.none") return Personalization(to: [to], cc: [cc], bcc: [bcc], subject: nil, headers: nil, substitutions: nil, customArguments: nil) } ) let good = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")], subject: "Hello World") try good.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let personalizations: [Personalization] = [ Personalization(recipients: "[email protected]"), Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: [Address(email: "[email protected]")], subject: "Hello", headers: nil, substitutions: nil, customArguments: nil) ] let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")]) try bad.validate() XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.") } catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) { XCTAssertEqual(duplicate, "[email protected]") } catch { XCTFailUnknownError(error) } do { let personalizations: [Personalization] = [ Personalization(recipients: "[email protected]"), Personalization(to: [Address(email: "[email protected]")], cc: [Address(email: "[email protected]")], bcc: nil, subject: "Hello", headers: nil, substitutions: nil, customArguments: nil) ] let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")]) try bad.validate() XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.") } catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) { XCTAssertEqual(duplicate, "[email protected]") } catch { XCTFailUnknownError(error) } do { let personalizations: [Personalization] = [ Personalization(recipients: "[email protected]"), Personalization(recipients: "[email protected]") ] let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")]) try bad.validate() XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.") } catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) { XCTAssertEqual(duplicate, "[email protected]") } catch { XCTFailUnknownError(error) } do { let personalizations: [Personalization] = [Personalization(recipients: "[email protected]")] let fromTest = Email(personalizations: personalizations, from: Address(email: "from"), content: [Content.plainText(body: "uh oh")], subject: "Hello World") try fromTest.validate() XCTFail("Expected error to be thrown when an email has a malformed From address, but nothing was thrown.") } catch SendGrid.Exception.Mail.malformedEmailAddress(_) { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let personalizations: [Personalization] = [Personalization(recipients: "[email protected]")] let replyToTest = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")], subject: "Hello World") replyToTest.parameters?.replyTo = "reply" try replyToTest.validate() XCTFail("Expected error to be thrown when an email has a malformed Reply To address, but nothing was thrown.") } catch SendGrid.Exception.Mail.malformedEmailAddress(_) { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } func testContentValidation() { let personalization = self.generatePersonalizations(Constants.PersonalizationLimit) let plain = Content.plainText(body: "plain") let html = Content.html(body: "html") let csv = Content(contentType: .csv, value: "foo,bar") let amp = Content(contentType: .amp, value: "AMP") let goodContent = [plain, html] do { let empty = Email(personalizations: personalization, from: self.goodFrom, content: [], subject: "Hello World") try empty.validate() XCTFail("Expected error to be thrown when initializing Email with an empty content array, but nothing was thrown.") } catch SendGrid.Exception.Mail.missingContent { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } let badContent1 = [csv] + goodContent do { let badOrder = Email(personalizations: personalization, from: self.goodFrom, content: badContent1, subject: "Hello World") try badOrder.validate() XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidContentOrder { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } let badContent2 = [plain, csv, html] do { let badOrder2 = Email(personalizations: personalization, from: self.goodFrom, content: badContent2, subject: "Hello World") try badOrder2.validate() XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidContentOrder { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } let badContent3 = [html, plain, csv] do { let badOrder3 = Email(personalizations: personalization, from: self.goodFrom, content: badContent3, subject: "Hello World") try badOrder3.validate() XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidContentOrder { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let goodOrder = Email(personalizations: personalization, from: self.goodFrom, content: [plain, html, csv], subject: "Hello World") try goodOrder.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let goodOrderAMP1 = Email(personalizations: personalization, from: self.goodFrom, content: [plain, html, amp], subject: "Hello World") try goodOrderAMP1.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let goodOrderAMP2 = Email(personalizations: personalization, from: self.goodFrom, content: [plain, amp, html], subject: "Hello World") try goodOrderAMP2.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let badOrderAMP = Email(personalizations: personalization, from: self.goodFrom, content: [amp, plain, html], subject: "Hello World") try badOrderAMP.validate() XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidContentOrder { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } /// No content with no template ID should throw an error. do { let personalization = Personalization(recipients: "[email protected]") let noContentEmail = Email(personalizations: [personalization], from: self.goodFrom, content: [], subject: "Hello world") noContentEmail.parameters?.content = nil try noContentEmail.validate() } catch SendGrid.Exception.Mail.missingContent { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } /// Empty array content with no template ID should throw an error. do { let personalization = Personalization(recipients: "[email protected]") let emptyContentEmail = Email(personalizations: [personalization], from: self.goodFrom, content: [], subject: "Hello world") try emptyContentEmail.validate() } catch SendGrid.Exception.Mail.missingContent { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } /// No content with a template ID throws no error. do { let personalization = Personalization(recipients: "[email protected]") let emptyTemplatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world") XCTAssertNoThrow(try emptyTemplatedEmail.validate()) } /// Empty array content with a template ID throws no error. do { let personalization = Personalization(recipients: "[email protected]") let emptyTemplatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world") emptyTemplatedEmail.parameters?.content = [] XCTAssertNoThrow(try emptyTemplatedEmail.validate()) } /// Content with a template ID throws no error. do { let personalization = Personalization(recipients: "[email protected]") let templatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world") templatedEmail.parameters?.content = Content.emailBody(plain: "foobar", html: "<p>foobar</p>") XCTAssertNoThrow(try templatedEmail.validate()) } } func testSubjectValidation() { do { let missing = self.generateBaseEmail(nil) try missing.validate() XCTFail("Expected an error to be thrown when a subject is missing, but nothing was thrown.") } catch SendGrid.Exception.Mail.missingSubject { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let missing = self.generateBaseEmail("") try missing.validate() XCTFail("Expected an error to be thrown when a subject is an empty, but nothing was thrown.") } catch SendGrid.Exception.Mail.missingSubject { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let personalizations = [ Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 1", headers: nil, substitutions: nil, customArguments: nil), Personalization(recipients: "[email protected]") ] let missing = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html")) try missing.validate() XCTFail("Expected an error to be thrown when a subject is not set as global, and not present in a personalization, but nothing was thrown.") } catch SendGrid.Exception.Mail.missingSubject { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let personalizations = [ Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "", headers: nil, substitutions: nil, customArguments: nil) ] let missing = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html")) try missing.validate() XCTFail("Expected an error to be thrown when a subject is not set as global, and an empty string in a personalization, but nothing was thrown.") } catch SendGrid.Exception.Mail.missingSubject { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { // No error should be thrown when each personalization has a subject line. let personalizations = [ Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 1", headers: nil, substitutions: nil, customArguments: nil), Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 2", headers: nil, substitutions: nil, customArguments: nil) ] let valid = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html")) try valid.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { // No error should be thrown if all subject properties are `nil` and a template ID is specified. let personalizations = [ Personalization(recipients: "[email protected]"), Personalization(recipients: "[email protected]") ] let valid = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html")) valid.parameters?.templateID = "696DC347-E82F-44EB-8CB1-59320BA1F136" try valid.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } func testHeaderValidation() { do { let good = self.generateBaseEmail() good.parameters!.headers = [ "X-Custom-Header": "Foo", "X-UID": "12345" ] try good.validate() XCTAssertTrue(true) } catch { XCTFail("Unexpected error: \(error)") } do { let bad = self.generateBaseEmail() bad.parameters!.headers = [ "X-Custom-Header": "Foo", "subject": "12345" ] try bad.validate() XCTFail("Expected error when using a reserved header, but no error was thrown") } catch let SendGrid.Exception.Mail.headerNotAllowed(header) { XCTAssertEqual(header, "subject") } catch { XCTFailUnknownError(error) } do { let bad = self.generateBaseEmail() bad.parameters!.headers = [ "X-Custom Header": "Foo" ] try bad.validate() XCTFail("Expected error when using a header with a space, but no error was thrown") } catch let SendGrid.Exception.Mail.malformedHeader(header) { XCTAssertEqual(header, "X-Custom Header") } catch { XCTFailUnknownError(error) } } func testCategoryValidation() { do { let good = self.generateBaseEmail() good.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "Category10"] try good.validate() XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let good = self.generateBaseEmail() good.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "category3"] try good.validate() XCTFail("Expected error when there are duplicate categories, but nothing was thrown.") } catch let SendGrid.Exception.Mail.duplicateCategory(dupe) { XCTAssertEqual(dupe, "category3") } catch { XCTFailUnknownError(error) } do { let bad = self.generateBaseEmail() bad.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "Category10", "Category11"] try bad.validate() XCTFail("Expected error when there are too many categories, but nothing was thrown.") } catch SendGrid.Exception.Mail.tooManyCategories { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } let characters = Array(0..<200).map { "\($0)" } let longCategory = characters.joined(separator: "") do { let bad = self.generateBaseEmail() bad.parameters?.categories = [longCategory] try bad.validate() XCTFail("Expected error when a category name is too long, but nothing was thrown.") } catch SendGrid.Exception.Mail.categoryTooLong(_) { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } func testCustomArgs() { let email = self.generateBaseEmail() email.parameters?.customArguments = ["foo": "bar"] XCTAssertEqual(email.parameters!.customArguments!["foo"], "bar") let new = Personalization(recipients: "[email protected]") new.customArguments = ["foo": "bar"] let over = Email(personalizations: [new], from: self.goodFrom, content: [Content.plainText(body: "plain")], subject: "Custom Args") var args = [String: String]() for i in 0..<300 { args["custom_arg_\(i)"] = "custom value \(i)" } over.parameters?.customArguments = args do { try over.validate() XCTFail("Expected an error when the custom arguments exceed \(Constants.CustomArguments.MaximumBytes) bytes, but nothing was thrown.") } catch SendGrid.Exception.Mail.tooManyCustomArguments(_, _) { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } func testSendAt() { let test = self.generateBaseEmail() let goodDate = Date(timeIntervalSinceNow: 4 * 60 * 60) test.parameters?.sendAt = goodDate do { try test.validate() XCTAssertEqual(test.parameters?.sendAt?.timeIntervalSince1970, goodDate.timeIntervalSince1970) } catch SendGrid.Exception.Mail.invalidScheduleDate { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } let failTest = self.generateBaseEmail() let badDate = Date(timeIntervalSinceNow: 80 * 60 * 60) failTest.parameters?.sendAt = badDate do { try failTest.validate() XCTFail("Expected a failure when scheduling a date further than 72 hours out, but nothing was thrown.") } catch SendGrid.Exception.Mail.invalidScheduleDate { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } }
6505fa6b3c6aeed6445817db5c5022e6
43.863363
195
0.576492
false
true
false
false
Tanglo/OpalStability
refs/heads/master
OpalStability/AppDelegate.swift
mit
1
// // AppDelegate.swift // OpalStability // // Created by Lee Walsh on 30/11/2015. // Copyright © 2015 Lee David Walsh. All rights reserved. // import Cocoa import LabBot @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func applicationShouldOpenUntitledFile(sender: NSApplication) -> Bool { return false } @IBAction func importData(sender: AnyObject){ let openPanel = NSOpenPanel() openPanel.canChooseDirectories = false openPanel.canChooseFiles = true openPanel.allowedFileTypes = ["csv","CSV"] let result = openPanel.runModal() if result == NSModalResponseOK { do{ var newOpalData = try LBDataMatrix(csvURL: openPanel.URL!, titles: true) var metadata: [String] (metadata, newOpalData) = self.importDataMatrix(newOpalData) do{ let newDoc = try NSDocumentController.sharedDocumentController().openUntitledDocumentAndDisplay(false) as! LDWOpalDocument newDoc.opalData = LDWOpalData(data: newOpalData, metadataArray: metadata) newDoc.makeWindowControllers() newDoc.showWindows() } catch { NSDocumentController.sharedDocumentController().presentError((error as NSError)) } } catch { let errorAlert = NSAlert(error: error as NSError) errorAlert.runModal() } } } func importDataMatrix(dataMatrix: LBDataMatrix) -> ([String], LBDataMatrix){ let numVariables = dataMatrix.numberOfVariables() let numObservations = dataMatrix.numberOfObservations() - 1 //the last row of the .csv data from the opal file is blank let metadataIndex = dataMatrix.indexOfVariable("Metadata") var metadata = [String]() let importedDataMatrix = LBDataMatrix(numberOfObservations: numObservations) if metadataIndex != nil{ metadata = dataMatrix.variableAtIndex(metadataIndex!) as! [String] } for i in 0..<numVariables{ if dataMatrix.nameOfVariableAtIndex(i) != "Metadata"{ let variableName = dataMatrix.nameOfVariableAtIndex(i)! importedDataMatrix.appendVariable(variableName, values: dataMatrix.variableAtIndex(i)!) if (importedDataMatrix.variableWithName(variableName)![0] as! String).containsString("."){ importedDataMatrix.changeStringVariableToDouble(variableName) } else { importedDataMatrix.changeStringVariableToInt(variableName) } } } return (metadata, importedDataMatrix) } }
3562b8d0d79624cdff4c855b60462072
38.217949
143
0.632887
false
false
false
false
nifti/CinchKit
refs/heads/master
CinchKit/Serializers/ErrorResponseSerializer.swift
mit
1
// // ErrorResponseSerializer.swift // CinchKit // // Created by Ryan Fitzgerald on 2/19/15. // Copyright (c) 2015 cinch. All rights reserved. // import Foundation import SwiftyJSON class ErrorResponseSerializer : JSONObjectSerializer { func jsonToObject(json: SwiftyJSON.JSON) -> NSError? { let statusCode = json["statusCode"].intValue var userInfo = [String : String]() if let err = json["error"].string { userInfo[NSLocalizedDescriptionKey] = err } if let message = json["message"].string { userInfo[NSLocalizedFailureReasonErrorKey] = message } return NSError(domain: CinchKitErrorDomain, code: statusCode, userInfo: userInfo) } }
8e9b15a65702e8517b5acc244dca1982
24.533333
89
0.63268
false
false
false
false
cubixlabs/GIST-Framework
refs/heads/master
GISTFramework/Classes/GISTSocial/Protocols/Mappable+ToDictionary.swift
agpl-3.0
1
// // Mappable+ToDictionary.swift // FoodParcel // // Created by Shoaib Abdul on 14/10/2016. // Copyright © 2016 Cubixlabs. All rights reserved. // import Foundation import ObjectMapper public protocol ReverseMappable { func toDictionary () -> NSDictionary; } public extension ReverseMappable { func reverseMap (_ obj:Any?) -> Any? { guard (obj != nil) else { return nil; } if let mappableObj:ReverseMappable = obj as? ReverseMappable { return mappableObj.toDictionary(); } if let arrMappableObj:[Any] = obj as? [Any] { return self.reverseMapArray(arrMappableObj); } return obj; } //F.E. func reverseMapArray(_ arrMappableObj:[Any]) -> NSArray { let rtnArr:NSMutableArray = NSMutableArray(); for obj in arrMappableObj { if let mappable = obj as? ReverseMappable { let dict = mappable.toDictionary() rtnArr.add(dict); } } return rtnArr; } }
348014048c4979127168d1c25d51d9d1
23.130435
70
0.557658
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClient/Sources/Requests/Hashtag/FetchHashtagFollowersRequest.swift
mit
1
// // FetchHashtagFollowersRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class FetchHashtagFollowersRequest: Request { override var method: RequestMethod { return .get } override var endpoint: String { let hashtag = hashtagId return "hashtags/"+hashtag+"/followers" } override var parameters: Dictionary<String, AnyObject> { return prepareParameters() } fileprivate let page: Int? fileprivate let perPage: Int? fileprivate let hashtagId: String init(page: Int? = nil, perPage: Int? = nil, hashtagId: String) { self.page = page self.perPage = perPage self.hashtagId = hashtagId } fileprivate func prepareParameters() -> Dictionary<String, AnyObject> { var params = Dictionary<String, AnyObject>() if let page = page { params["page"] = page as AnyObject? } if let perPage = perPage { params["per_page"] = perPage as AnyObject? } return params } }
340e1a055b2f2f645c17be001ebe09e6
36.101695
89
0.686158
false
false
false
false
SandcastleApps/partyup
refs/heads/master
PartyUP/NSDateComponentsFormatter+Postfix.swift
mit
1
// // NSDateComponentsFormatter+Postfix.swift // PartyUP // // Created by Fritz Vander Heide on 2016-03-25. // Copyright © 2016 Sandcastle Application Development. All rights reserved. // import Foundation extension NSDateComponentsFormatter { func stringFromDate(startDate: NSDate, toDate endDate: NSDate, classicThreshold classic: NSTimeInterval?, postfix: Bool = false, substituteZero zero: String? = nil) -> String? { var capped = false var interval = endDate.timeIntervalSinceDate(startDate) if let classic = classic where interval > classic { interval = classic capped = true if unitsStyle != .Abbreviated { return NSLocalizedString("Classic", comment: "Stale time display") } } var formatted = stringFromTimeInterval(interval) ?? "?" formatted = formatted.characters.split(",").prefixUpTo(self.maximumUnitCount).map { String($0) }.joinWithSeparator(",") if capped { formatted += "+" } if let zero = zero where formatted.hasPrefix("0") { formatted = zero } else if postfix { formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old") } return formatted } }
5c90f2b877ad007bde5f85e8e02c1bcd
34.634146
121
0.560959
false
false
false
false
sonsongithub/reddift
refs/heads/master
application/SubredditCellar.swift
mit
1
// // SubredditCellar.swift // reddift // // Created by sonson on 2016/10/05. // Copyright © 2016年 sonson. All rights reserved. // import reddift import Foundation class SubredditCellar: LinkContainerCellar { /// Subreddit var subreddit = Subreddit(subreddit: "") /// Paginator object for paging. var paginator = Paginator() /// Loading flag var loading = false override func tryLoadingMessage() -> String { return "Try loading \(subreddit.displayName)" } override func loadingMessage() -> String { return "Loading \(subreddit.displayName)...." } /// Loading flag override var isLoading: Bool { get { return loading } } /** Initialize SubredditCellar. - parameter subredditName: To be written. - parameter delegate: To be written. - returns: To be written. */ init(subreddit name: String, width newWidth: CGFloat, fontSize newFontSize: CGFloat) { super.init() subreddit = Subreddit(subreddit: name) width = newWidth fontSize = newFontSize } /** Initialize SubredditCellar. - parameter subredditName: To be written. - parameter delegate: To be written. - returns: To be written. */ override init() { } deinit { print("SubredditContentsProvider - deinit") NotificationCenter.default.removeObserver(self) } /** Remove all objects from all mutable arraies of self. */ func removeAllObjects() { self.containers.removeAll() } /** Append new obtained contents to self. - parameter listing: To be written. - parameter width: To be written. */ func appendContentWithListing(listing: Listing, widthConstraint: CGFloat, atTheBeginning: Bool) { /// Create and layout Content objects. let newLinks: [Link] = listing.children.compactMap({ $0 as? Link }) let newContainers: [LinkContainable] = newLinks.compactMap({ LinkContainable.createContainer(with: $0, width: width) }) let pre_count = containers.count let aft_count = containers.count + newContainers.count containers.append(contentsOf: newContainers) var indices: [IndexPath] = [] for i in pre_count..<aft_count { let indexPath = IndexPath(row: i, section: 0) containers[i].prefetch(at: indexPath) indices.append(indexPath) } paginator = listing.paginator if atTheBeginning { postNotification(name: LinkContainerCellarDidLoadName, userInfo: [LinkContainerCellar.isAtTheBeginningKey: true, LinkContainerCellar.providerKey: self]) } else { postNotification(name: LinkContainerCellarDidLoadName, userInfo: [LinkContainerCellar.insertIndicesKey: indices, LinkContainerCellar.providerKey: self]) } } func postNotification(name: Notification.Name, userInfo: [String: Any]) { DispatchQueue.main.async(execute: { () -> Void in self.loading = false NotificationCenter.default.post(name: name, object: nil, userInfo: userInfo) }) } /** Load Subreddit. - parameter appending: To be written. - parameter width: To be written. */ override func load(atTheBeginning: Bool) { /// Do nothing in case paginator is vacant and load subreddit to append contents. if self.paginator.isVacant && !atTheBeginning { return } /// Do nothing in case this controller is loading. if loading { return } do { loading = true try UIApplication.appDelegate()?.session?.getList(paginator, subreddit: subreddit, sort: .hot, timeFilterWithin: .month, completion: { (result) -> Void in switch result { case .failure(let error): /// Callback self.postNotification(name: LinkContainerCellarDidLoadName, userInfo: [LinkContainerCellar.errorKey: error, LinkContainerCellar.providerKey: self]) case .success(let listing): /// Clear all objects before load content from the beginning. if atTheBeginning { self.removeAllObjects() } /// append new contents to self self.appendContentWithListing(listing: listing, widthConstraint: self.width, atTheBeginning: atTheBeginning) } }) } catch { let nserror = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "\(error)"]) postNotification(name: LinkContainerCellarDidLoadName, userInfo: [LinkContainerCellar.errorKey: nserror, LinkContainerCellar.providerKey: self]) } } }
51d85a7bf0cb57374656c7bd593ac4d9
33.843972
167
0.614085
false
false
false
false
joostholslag/BNRiOS
refs/heads/master
iOSProgramming6ed/16 - Archiving/Solutions/Homepwner/Homepwner/Item.swift
gpl-3.0
2
// // Copyright © 2015 Big Nerd Ranch // import Foundation class Item: NSObject, NSCoding { var name: String var valueInDollars: Int var serialNumber: String? let dateCreated: Date let itemKey: String init(name: String, serialNumber: String?, valueInDollars: Int) { self.name = name self.serialNumber = serialNumber self.valueInDollars = valueInDollars self.dateCreated = Date() self.itemKey = UUID().uuidString } convenience init(random: Bool = false) { if random { let adjectives = ["Fluffy", "Rusty", "Shiny"] let nouns = ["Bear", "Spork", "Mac"] var idx = arc4random_uniform(UInt32(adjectives.count)) let randomAdjective = adjectives[Int(idx)] idx = arc4random_uniform(UInt32(nouns.count)) let randomNoun = nouns[Int(idx)] let randomName = "\(randomAdjective) \(randomNoun)" let randomValue = Int(arc4random_uniform(100)) let randomSerialNumber = UUID().uuidString.components(separatedBy: "-").first! self.init(name: randomName, serialNumber: randomSerialNumber, valueInDollars: randomValue) } else { self.init(name: "", serialNumber: nil, valueInDollars: 0) } } required init(coder aDecoder: NSCoder) { name = aDecoder.decodeObject(forKey: "name") as! String dateCreated = aDecoder.decodeObject(forKey: "dateCreated") as! Date itemKey = aDecoder.decodeObject(forKey: "itemKey") as! String serialNumber = aDecoder.decodeObject(forKey: "serialNumber") as! String? valueInDollars = aDecoder.decodeInteger(forKey: "valueInDollars") super.init() } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(dateCreated, forKey: "dateCreated") aCoder.encode(itemKey, forKey: "itemKey") aCoder.encode(serialNumber, forKey: "serialNumber") aCoder.encode(valueInDollars, forKey: "valueInDollars") } }
550acee3f64a4cf852527ddeaa11edc9
32.014925
80
0.594033
false
false
false
false
xmartlabs/Bender
refs/heads/master
Example/Example/Luminance.swift
mit
1
// // LuminanceLayer.swift // Bender // // Created by Mathias Claassen on 4/25/17. // Copyright © 2017 Xmartlabs. All rights reserved. // import MetalPerformanceShaders import MetalPerformanceShadersProxy import MetalBender /// Receives two input images. The first is used to take the luminance and the second is used to take the color for the output image. Used for color preservation class Luminance: NetworkLayer { var enabled: Bool // Custom kernels let pipelineLuminance: MTLComputePipelineState init(enabled: Bool, id: String? = nil) { self.enabled = enabled pipelineLuminance = MetalShaderManager.shared.getFunction(name: "luminance_transfer") super.init(id: id) } override func validate() { let incoming = getIncoming() precondition(incoming.count == 2, "Luminance layer must have two inputs") precondition(incoming[1].outputSize == incoming[0].outputSize, "Luminance layer must have two inputs with same size") } override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) { super.initialize(network: network, device: device, temporaryImage: temporaryImage) let incoming = getIncoming() outputSize = incoming[0].outputSize createOutputs(size: outputSize, temporary: temporaryImage) } override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) { let incoming = getIncoming() let input1 = incoming[0].getOutput(index: index) let input2 = incoming[1].getOutput(index: index) let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index) if !enabled { rewireIdentity(at: index, image: input1) return } let encoder = commandBuffer.makeComputeCommandEncoder()! encoder.label = "Luminance encoder" encoder.setComputePipelineState(pipelineLuminance) encoder.setTexture(input1.texture, index: 0) encoder.setTexture(input2.texture, index: 1) encoder.setTexture(output.texture, index: 2) let threadsPerGroups = MTLSizeMake(32, 8, 1) let threadGroups = MTLSizeMake(output.texture.width / threadsPerGroups.width, output.texture.height / threadsPerGroups.height, 1) encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups) encoder.endEncoding() input1.setRead() input2.setRead() } }
44fb8529952493133995e7f09451a4e2
38.375
161
0.686905
false
false
false
false
ello/ello-ios
refs/heads/master
Specs/Controllers/Notifications/NotificationsGeneratorSpec.swift
mit
1
//// /// NotificationsGeneratorSpec.swift // @testable import Ello import Quick import Nimble class NotificationsGeneratorSpec: QuickSpec { class MockNotificationsDestination: StreamDestination { var placeholderItems: [StreamCellItem] = [] var announcementItems: [StreamCellItem] = [] var notificationItems: [StreamCellItem] = [] var otherPlaceholderLoaded = false var responseConfig: ResponseConfig? var isPagingEnabled: Bool = false func setPlaceholders(items: [StreamCellItem]) { placeholderItems = items } func replacePlaceholder( type: StreamCellType.PlaceholderType, items: [StreamCellItem], completion: @escaping Block ) { switch type { case .announcements: announcementItems = items case .notifications: notificationItems = items default: otherPlaceholderLoaded = true } } func setPrimary(jsonable: Model) { } func primaryModelNotFound() { } func setPagingConfig(responseConfig: ResponseConfig) { self.responseConfig = responseConfig } } override func spec() { describe("NotificationsGenerator") { var destination: MockNotificationsDestination! var currentUser: User! var streamKind: StreamKind! var subject: NotificationsGenerator! beforeEach { destination = MockNotificationsDestination() currentUser = User.stub(["id": "42"]) streamKind = .notifications(category: nil) subject = NotificationsGenerator( currentUser: currentUser, streamKind: streamKind, destination: destination ) } describe("load()") { it("sets 2 placeholders") { subject.load() expect(destination.placeholderItems.count) == 2 } it("replaces only Announcements and Notifications") { subject.load() expect(destination.announcementItems.count) > 0 expect(destination.notificationItems.count) > 0 expect(destination.otherPlaceholderLoaded) == false } it("sets the config response") { subject.load() expect(destination.responseConfig).toNot(beNil()) } } describe("reloadAnnouncements()") { it("does not trigger when identical announcements are found") { ElloProvider.moya = ElloProvider.DefaultProvider() subject.load() let prevItems = destination.announcementItems subject.reloadAnnouncements() expect(destination.announcementItems) == prevItems } } } } }
3dd7cf798e099477510980b1b4858956
30.636364
79
0.54023
false
true
false
false
CUNY-Hunter-CSCI-Capstone-Summer2014/XMPP-Chat
refs/heads/master
DampKeg/OS X/Source Code/RosterListViewItem.swift
apache-2.0
1
// // RosterListItem.swift // DampKeg // // Created by Omar Stefan Evans on 7/23/14. // Copyright (c) 2014 DampKeg. All rights reserved. // import Foundation import Rambler class RosterListViewItem : NSObject { let isGroup: Bool let groupName: String? let rosterItem: RosterItem? var presence: Presence? var items: NSArray? init(rosterItem: RosterItem) { self.rosterItem = rosterItem self.isGroup = false super.init() } init(groupName: String) { self.groupName = groupName self.isGroup = true super.init() } var name: String { get { if isGroup { return groupName!; } else { return rosterItem!.name ? rosterItem!.name : rosterItem!.jid.description } } } var jid: String { return isGroup ? "" : rosterItem!.jid.description } var children:NSArray? { get { return isGroup ? items : nil } set { if isGroup { items = newValue } } } var textColor:NSColor { get{ if isGroup { return NSColor.controlTextColor() } else { if presence? { switch presence!.state { case .Available: return NSColor.controlTextColor(); case .Unavailable: return NSColor.disabledControlTextColor() case .WantsToChat: return NSColor.controlTextColor(); case .DoNotDisturb: return NSColor(calibratedRed: 0.240, green:0.393, blue:0.641, alpha:1.000) case .Away: return NSColor(calibratedRed:0.858, green:0.175, blue:0.159, alpha:1.000) case .ExtendedAway: return NSColor(calibratedRed:0.525, green:0.138, blue:0.153, alpha:1.000) } } return NSColor.controlTextColor(); } } } }
1e8644687ba60ddea7f40c7fc58ed092
21.943182
94
0.528975
false
false
false
false
odigeoteam/TableViewKit
refs/heads/develop
Examples/SampleApp/SampleApp/CustomItem.swift
mit
1
import Foundation import UIKit import TableViewKit public class CustomDrawer: CellDrawer { public static var type = CellType.class(UITableViewCell.self) public static func draw(_ cell: UITableViewCell, with item: CustomItem) { cell.accessoryType = item.accessoryType cell.accessoryView = item.accessoryView cell.textLabel?.text = item.title } } public class CustomItem: Selectable, TableItem { public static var drawer = AnyCellDrawer(CustomDrawer.self) public var title: String? public var onSelection: (Selectable) -> Void = { _ in } public var cellStyle: UITableViewCell.CellStyle = .default public var accessoryType: UITableViewCell.AccessoryType = .none public var accessoryView: UIView? public var cellHeight: CGFloat? = UITableView.automaticDimension public init() { } public convenience init(title: String) { self.init() self.title = title } public func didSelect() { onSelection(self) } }
cb2956aad099223b442dbd511a133288
25.736842
77
0.698819
false
false
false
false
BenziAhamed/Nevergrid
refs/heads/master
NeverGrid/Source/PriorityQueue.swift
isc
1
// // PriorityQueue.swift // MrGreen // // Created by Benzi on 03/09/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation struct PriorityQueueNode<T> { var item:T var priority:Int } class PriorityQueue<T> { var q = [PriorityQueueNode<T>]() var count:Int { return q.count } func put(item:T, priority:Int) { let node = PriorityQueueNode(item: item, priority: priority) if q.count == 0 { q.append(node) } else { var insertIndex = 0 while insertIndex < count && q[insertIndex].priority <= priority { insertIndex++ } if insertIndex < q.count { q.insert(node, atIndex: insertIndex) } else { q.append(node) } } } func get() -> T? { if q.count == 0 { return nil } else { return q.removeAtIndex(0).item } } }
b0b59f4ca31c23b68eea4a689d3b1ede
19.66
78
0.487403
false
false
false
false
wwdc14/SkyNet
refs/heads/master
SkyNet/Classes/Settings/NetworkSettingTableViewController.swift
mit
1
// // NetworkSettingTableViewController.swift // Pods // // Created by FD on 21/08/2017. // // import UIKit struct NetworkSettingModel { let title:String let isOn: Bool let type: HTTPModelShortType } struct NetworkSettingViewModel { let model:[NetworkSettingModel] let sectionTitle: String } class NetworkSettingTableViewController: UITableViewController { var dataSource:[NetworkSettingViewModel]? = nil override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "networkSetting" tableView.register(NetworkSettingTableViewCell.self, forCellReuseIdentifier: "cell") let netViewModel = NetworkSettingViewModel(model: loadData(), sectionTitle: "NetworkFilterType") dataSource = [] dataSource?.append(netViewModel) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return dataSource?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let viewModel = dataSource?[section] return viewModel?.model.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: NetworkSettingTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! NetworkSettingTableViewCell func switchChange() { NetworkSettings.saveFilterType(index: indexPath.row) } if let dataSource = dataSource { let viewModel = dataSource[indexPath.section] let model = viewModel.model[indexPath.row] cell.switchControl.isOn = model.isOn cell.textLabel?.text = model.type.rawValue cell.handler = switchChange } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let dataSource = dataSource { return dataSource[section].sectionTitle }else{ return "" } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } //MARK: - load method func loadData() -> [NetworkSettingModel] { let filter = NetworkSettings.getFilterTypes() let xml = NetworkSettingModel(title: "xml", isOn: filter[HTTPModelShortType.allValues.index(of: .XML)!], type:.XML) let json = NetworkSettingModel(title: "json", isOn: filter[HTTPModelShortType.allValues.index(of: .JSON)!], type: .JSON) let html = NetworkSettingModel(title: "html", isOn: filter[HTTPModelShortType.allValues.index(of: .HTML)!], type: .HTML) let image = NetworkSettingModel(title: "image", isOn: filter[HTTPModelShortType.allValues.index(of: .IMAGE)!], type: .IMAGE) let other = NetworkSettingModel(title: "other", isOn: filter[HTTPModelShortType.allValues.index(of: .OTHER)!], type: .OTHER) return [json,xml,html,image,other] } }
592c0f9fa3daf1716175590023dbc43c
35.119565
134
0.668974
false
false
false
false
Drusy/auvergne-webcams-ios
refs/heads/master
Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/CustomTransformTests.swift
apache-2.0
3
// // CustomTransformTests.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-03-09. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import ObjectMapper #if os(iOS) || os(tvOS) || os(watchOS) typealias TestHexColor = UIColor #else typealias TestHexColor = NSColor #endif class CustomTransformTests: XCTestCase { let mapper = Mapper<Transforms>() 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 testDateTransform() { let transforms = Transforms() transforms.date = Date(timeIntervalSince1970: 946684800) transforms.dateOpt = Date(timeIntervalSince1970: 946684912) transforms.dateMs = transforms.date transforms.dateOptMs = transforms.dateOpt let JSON = mapper.toJSON(transforms) let parsedTransforms = mapper.map(JSON: JSON) XCTAssertNotNil(parsedTransforms) XCTAssertEqual(parsedTransforms?.date, transforms.date) XCTAssertEqual(parsedTransforms?.dateOpt, transforms.dateOpt) XCTAssertEqual(parsedTransforms?.dateMs, transforms.dateMs) XCTAssertEqual(parsedTransforms?.dateOptMs, transforms.dateOptMs) let JSONDateString: [String: Any] = ["date": "946684800", "dateOpt": "946684912", "dateMs": "946684800000", "dateOptMs": "946684912000"] let parsedTransformsDateString = mapper.map(JSON: JSONDateString) XCTAssertNotNil(parsedTransformsDateString) XCTAssertEqual(parsedTransforms?.date, parsedTransformsDateString?.date) XCTAssertEqual(parsedTransforms?.dateOpt, parsedTransformsDateString?.dateOpt) XCTAssertEqual(parsedTransforms?.dateMs, parsedTransformsDateString?.dateMs) XCTAssertEqual(parsedTransforms?.dateOptMs, parsedTransformsDateString?.dateOptMs) } func testISO8601DateTransform() { let transforms = Transforms() transforms.ISO8601Date = Date(timeIntervalSince1970: 1398956159) transforms.ISO8601DateOpt = Date(timeIntervalSince1970: 1398956159) let JSON = mapper.toJSON(transforms) let parsedTransforms = mapper.map(JSON: JSON) XCTAssertNotNil(parsedTransforms) XCTAssertEqual(parsedTransforms?.ISO8601Date, transforms.ISO8601Date) XCTAssertEqual(parsedTransforms?.ISO8601DateOpt, transforms.ISO8601DateOpt) } func testISO8601DateTransformWithInvalidInput() { var JSON: [String: Any] = ["ISO8601Date": ""] let transforms = mapper.map(JSON: JSON) XCTAssertNil(transforms?.ISO8601DateOpt) JSON["ISO8601Date"] = "incorrect format" let transforms2 = mapper.map(JSON: JSON) XCTAssertNil(transforms2?.ISO8601DateOpt) } func testCustomFormatDateTransform(){ let dateString = "2015-03-03T02:36:44" let JSON: [String: Any] = ["customFormateDate": dateString] let transform: Transforms! = mapper.map(JSON: JSON) XCTAssertNotNil(transform) let JSONOutput = mapper.toJSON(transform) XCTAssertEqual(JSONOutput["customFormateDate"] as? String, dateString) } func testIntToStringTransformOf() { let intValue = 12345 let JSON: [String: Any] = ["intWithString": "\(intValue)"] let transforms = mapper.map(JSON: JSON) XCTAssertEqual(transforms?.intWithString, intValue) } func testInt64MaxValue() { let transforms = Transforms() transforms.int64Value = INT64_MAX let JSON = mapper.toJSON(transforms) let parsedTransforms = mapper.map(JSON: JSON) XCTAssertNotNil(parsedTransforms) XCTAssertEqual(parsedTransforms?.int64Value, transforms.int64Value) } func testURLTranform() { let transforms = Transforms() transforms.URL = URL(string: "http://google.com/image/1234")! transforms.URLOpt = URL(string: "http://google.com/image/1234") transforms.URLWithoutEncoding = URL(string: "http://google.com/image/1234#fragment")! let JSON = mapper.toJSON(transforms) let parsedTransforms = mapper.map(JSON: JSON) XCTAssertNotNil(parsedTransforms) XCTAssertEqual(parsedTransforms?.URL, transforms.URL) XCTAssertEqual(parsedTransforms?.URLOpt, transforms.URLOpt) XCTAssertEqual(parsedTransforms?.URLWithoutEncoding, transforms.URLWithoutEncoding) } func testEnumTransform() { let JSON: [String: Any] = ["firstImageType": "cover", "secondImageType": "thumbnail"] let transforms = mapper.map(JSON: JSON) let imageType = Transforms.ImageType.self XCTAssertEqual(transforms?.firstImageType, imageType.Cover) XCTAssertEqual(transforms?.secondImageType, imageType.Thumbnail) } func testHexColorTransform() { let JSON: [String: Any] = [ "colorRed": "#FF0000", "colorGreenLowercase": "#00FF00", "colorBlueWithoutHash": "0000FF", "color3lenght": "F00", "color4lenght": "F00f", "color8lenght": "ff0000ff" ] let transform = mapper.map(JSON: JSON) XCTAssertEqual(transform?.colorRed, TestHexColor.red) XCTAssertEqual(transform?.colorGreenLowercase, TestHexColor.green) XCTAssertEqual(transform?.colorBlueWithoutHash, TestHexColor.blue) XCTAssertEqual(transform?.color3lenght, TestHexColor.red) XCTAssertEqual(transform?.color4lenght, TestHexColor.red) XCTAssertEqual(transform?.color8lenght, TestHexColor.red) let JSONOutput = mapper.toJSON(transform!) XCTAssertEqual(JSONOutput["colorRed"] as? String, "FF0000") XCTAssertEqual(JSONOutput["colorGreenLowercase"] as? String, "00FF00") XCTAssertEqual(JSONOutput["colorBlueWithoutHash"] as? String, "#0000FF") // prefixToJSON = true XCTAssertEqual(JSONOutput["color3lenght"] as? String, "FF0000") XCTAssertEqual(JSONOutput["color4lenght"] as? String, "FF0000") XCTAssertEqual(JSONOutput["color8lenght"] as? String, "FF0000FF") // alphaToJSON = true } } class Transforms: Mappable { internal enum ImageType: String { case Cover = "cover" case Thumbnail = "thumbnail" } var date = Date() var dateOpt: Date? var dateMs = Date() var dateOptMs: Date? var ISO8601Date: Date = Date() var ISO8601DateOpt: Date? var customFormatDate = Date() var customFormatDateOpt: Date? var URL = Foundation.URL(string: "") var URLOpt: Foundation.URL? var URLWithoutEncoding = Foundation.URL(string: "") var intWithString: Int = 0 var int64Value: Int64 = 0 var firstImageType: ImageType? var secondImageType: ImageType? var colorRed: TestHexColor? var colorGreenLowercase: TestHexColor? var colorBlueWithoutHash: TestHexColor? var color3lenght: TestHexColor? var color4lenght: TestHexColor? var color8lenght: TestHexColor? init(){ } required init?(map: Map){ } func mapping(map: Map) { date <- (map["date"], DateTransform()) dateOpt <- (map["dateOpt"], DateTransform()) dateMs <- (map["dateMs"], DateTransform(unit: .milliseconds)) dateOptMs <- (map["dateOptMs"], DateTransform(unit: .milliseconds)) ISO8601Date <- (map["ISO8601Date"], ISO8601DateTransform()) ISO8601DateOpt <- (map["ISO8601DateOpt"], ISO8601DateTransform()) customFormatDate <- (map["customFormateDate"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss")) customFormatDateOpt <- (map["customFormateDateOpt"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss")) URL <- (map["URL"], URLTransform()) URLOpt <- (map["URLOpt"], URLTransform()) URLWithoutEncoding <- (map["URLWithoutEncoding"], URLTransform(shouldEncodeURLString: false)) intWithString <- (map["intWithString"], TransformOf<Int, String>(fromJSON: { $0 == nil ? nil : Int($0!) }, toJSON: { $0.map { String($0) } })) int64Value <- (map["int64Value"], TransformOf<Int64, NSNumber>(fromJSON: { $0?.int64Value }, toJSON: { $0.map { NSNumber(value: $0) } })) firstImageType <- (map["firstImageType"], EnumTransform<ImageType>()) secondImageType <- (map["secondImageType"], EnumTransform<ImageType>()) colorRed <- (map["colorRed"], HexColorTransform()) colorGreenLowercase <- (map["colorGreenLowercase"], HexColorTransform()) colorBlueWithoutHash <- (map["colorBlueWithoutHash"], HexColorTransform(prefixToJSON: true)) color3lenght <- (map["color3lenght"], HexColorTransform()) color4lenght <- (map["color4lenght"], HexColorTransform()) color8lenght <- (map["color8lenght"], HexColorTransform(alphaToJSON: true)) } }
98066c65816246d39558b98deb47a750
34.609023
145
0.738387
false
true
false
false
pman215/ONH305
refs/heads/master
Sources/ONH305SvrLib/ServerUtil.swift
apache-2.0
1
import Foundation import PerfectLib import PerfectLogger struct ServerUtil { let name = "0.0.0.0" let port: UInt16 = 8080 let root = "./v2" let templates = "./v2/templates" let dataPath = "./v2/data" let httpLogFile = "./v2/log/ONH305SvrHTTP.log" let logFile = "./v2/log/ONH305Svr.log" let templateExtension = ".mustache" let dataExtension = ".json" func root(path: String) -> String { guard let url = URL(string: path) else { return "" } var pathComponents = url.pathComponents if !pathComponents.isEmpty { pathComponents.removeFirst() } pathComponents.popLast() pathComponents.insert("", at: 0) return pathComponents.joined(separator: "/") } func templatePath(path: String) -> String { guard let url = URL(string: path) else { return "" } let templateFolder = folder(url: url, name: "templates") let templateName = url.lastPathComponent + templateExtension return templateFolder + "/" + templateName } func data(path: String) -> [String : Any] { guard let url = URL(string: path) else { return [String : Any]() } let templateFolder = folder(url: url, name: "data") let dataFilenames = filenames(in: templateFolder) let dataFiles = dataFilenames.map { File("\(templateFolder)/\($0)") } let dataContent: [String] = dataFiles.map { do { let content = try $0.readString() return content } catch { LogFile.error("Unable to read content of file \($0.path)") return "" } } var values = [String : Any]() dataContent.forEach { do { guard let decodedValues = try $0.jsonDecode() as? [String : Any] else { return } decodedValues.forEach { values[$0.key] = $0.value } } catch { LogFile.error("Unable to decode file as JSON: \($0)") return } } return values } } private extension ServerUtil { func folder(url: URL, name: String) -> String { var pathComponents = url.pathComponents let lastPathComponent = url.lastPathComponent if !pathComponents.isEmpty { pathComponents.removeFirst() } pathComponents.popLast() pathComponents.append(name) pathComponents.append(lastPathComponent) pathComponents.insert(".", at: 0) return pathComponents.joined(separator: "/") } func filenames(in folder: String) -> [String] { guard File(folder).isDir else { LogFile.warning("Path \(folder) is not a folder") return [String]() } let dir = Dir(folder) var files = [String]() do { try dir.forEachEntry { (entry) in files.append(entry) } } catch { LogFile.error("Unable to retrieve folder \(folder) files") } LogFile.debug("Folder \(folder) contains files \(files)") return files } func filenames(in folder: String, ext: String, prefix: String) -> [String] { let allFiles = filenames(in: folder) let allFilesPrefix = allFiles.filter { $0.hasPrefix(prefix) && $0.hasSuffix(ext) } return allFilesPrefix } }
940a369f7bd1f5ac36e58cb1fc2c141d
24.271186
81
0.649229
false
false
false
false
mlpqaz/V2ex
refs/heads/master
ZZV2ex/ZZV2ex/Common/V2Response.swift
apache-2.0
1
// // V2Response.swift // ZZV2ex // // Created by ios on 2017/5/3. // Copyright © 2017年 张璋. All rights reserved. // import UIKit class V2Response: NSObject { var success: Bool = false var message: String = "No message" init(success:Bool,message:String?) { super.init() self.success = success if let message = message{ self.message = message } } init(success:Bool) { super.init() self.success = success } } class V2ValueResponse<T>: V2Response { var value:T? override init(success: Bool) { super.init(success: success) } override init(success: Bool,message:String?) { super.init(success: success) if let message = message { self.message = message } } convenience init(value:T,success:Bool){ self.init(success: success) self.value = value } convenience init(value:T,success:Bool,message:String?) { self.init(value:value,success:success) if let message = message{ self.message = message } } }
a7aea57ac156a421233f1a0a6954e3b4
22.058824
64
0.552721
false
false
false
false
AlexeyGolovenkov/DevHelper
refs/heads/master
DevHelper/Ext/Extensions/DHTextRange.swift
mit
1
// // DHTextRange.swift // DevHelper // // Created by Alexey Golovenkov on 12.03.17. // Copyright © 2017 Alexey Golovenkov. All rights reserved. // import Cocoa struct DHTextPosition: Equatable { var line = 0 var column = 0 public static func ==(lhs: DHTextPosition, rhs: DHTextPosition) -> Bool { return lhs.column == rhs.column && lhs.line == rhs.line } } class DHTextRange: NSObject { var start = DHTextPosition(line: 0, column: 0) var end = DHTextPosition(line: 0, column: 0) convenience init(start: DHTextPosition, end: DHTextPosition) { self.init() self.start = start self.end = end } func isCursorPosition() -> Bool { return self.start == self.end } }
a8f52c02ac2b89ef1242e66c5352d295
20.969697
74
0.652414
false
false
false
false
con-beo-vang/Spendy
refs/heads/master
Spendy/Helpers/Helper.swift
mit
1
// // Helper.swift // Spendy // // Created by Dave Vo on 9/16/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit var logoColor = UIColor.redColor() class Helper: NSObject { static let sharedInstance = Helper() func customizeBarButton(viewController: UIViewController, button: UIButton, imageName: String, isLeft: Bool) { let avatar = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22)) avatar.image = UIImage(named: imageName) button.setImage(avatar.image, forState: .Normal) button.frame = CGRectMake(0, 0, 22, 22) let item: UIBarButtonItem = UIBarButtonItem() item.customView = button if isLeft { viewController.navigationItem.leftBarButtonItem = item } else { viewController.navigationItem.rightBarButtonItem = item } } func getCellAtGesture(gestureRecognizer: UIGestureRecognizer, tableView: UITableView) -> UITableViewCell? { let location = gestureRecognizer.locationInView(tableView) let indexPath = tableView.indexPathForRowAtPoint(location) if let indexPath = indexPath { return tableView.cellForRowAtIndexPath(indexPath)! } else { return nil } } func showActionSheet(viewController: UIViewController, imagePicker: UIImagePickerController) { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let takePhotoAction = UIAlertAction(title: "Take a Photo", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Take a Photo", terminator: "\n") imagePicker.allowsEditing = false imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo imagePicker.modalPresentationStyle = .FullScreen viewController.presentViewController(imagePicker, animated: true, completion: nil) }) let photoLibraryAction = UIAlertAction(title: "Photo from Library", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Photo from Library", terminator: "\n") imagePicker.allowsEditing = true imagePicker.sourceType = .PhotoLibrary viewController.presentViewController(imagePicker, animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in print("Cancelled", terminator: "\n") }) optionMenu.addAction(takePhotoAction) optionMenu.addAction(photoLibraryAction) optionMenu.addAction(cancelAction) viewController.presentViewController(optionMenu, animated: true, completion: nil) } func setPopupShadowAndColor(popupView: UIView, label: UILabel) { // Set shadow popupView.layer.shadowPath = UIBezierPath(roundedRect: popupView.layer.bounds, cornerRadius: 5).CGPath popupView.layer.shadowColor = Color.strongColor.CGColor popupView.layer.shadowOffset = CGSizeMake(5, 5) popupView.layer.shadowRadius = 5 popupView.layer.shadowOpacity = 0.5 // Set header color label.backgroundColor = Color.popupHeaderColor label.textColor = UIColor.whiteColor() } // MARK: Category func createIcon(imageName: String) -> UIImage { let markerView = UIView(frame:CGRectMake(0, 0, 50, 50)) //Add icon let icon = UIImageView(frame: CGRectMake(7, 7, 36, 36)) icon.image = UIImage(named: imageName) markerView.addSubview(icon) return imageFromView(markerView) } func imageFromView(aView:UIView) -> UIImage { if(UIScreen.mainScreen().respondsToSelector("scale")) { UIGraphicsBeginImageContextWithOptions(aView.frame.size, false, UIScreen.mainScreen().scale) } else { UIGraphicsBeginImageContext(aView.frame.size) } aView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func setIconLayer(iconView: UIImageView) { iconView.layer.cornerRadius = iconView.frame.height / 2 iconView.layer.masksToBounds = true // TODO: remove this line after category has type iconView.layer.backgroundColor = Color.strongColor.CGColor } } enum ViewMode: Int { case Weekly = 0, Monthly, Yearly, Custom }
ba3009209f6887d4c2e8688ddaf84186
32.189394
112
0.709427
false
false
false
false
shajrawi/swift
refs/heads/master
stdlib/public/core/StringStorage.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// import SwiftShims // Having @objc stuff in an extension creates an ObjC category, which we don't // want. #if _runtime(_ObjC) internal protocol _AbstractStringStorage : _NSCopying { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } var UTF16Length: Int { get } } internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */ internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */ @_effects(readonly) private func _isNSString(_ str:AnyObject) -> UInt8 { return _swift_stdlib_isNSString(str) } #else internal protocol _AbstractStringStorage { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } } #endif extension _AbstractStringStorage { // ObjC interfaces. #if _runtime(_ObjC) @inline(__always) @_effects(releasenone) internal func _getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange ) { _precondition(aRange.location >= 0 && aRange.length >= 0, "Range out of bounds") _precondition(aRange.location + aRange.length <= Int(count), "Range out of bounds") let range = Range( uncheckedBounds: (aRange.location, aRange.location+aRange.length)) let str = asString str._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(start: buffer, count: range.count), range: range) } @inline(__always) @_effects(releasenone) internal func _getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): guard maxLength >= count + 1 else { return 0 } outputPtr.initialize(from: start, count: count) outputPtr[count] = 0 return 1 default: return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding) } } @inline(__always) @_effects(readonly) internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): return start default: return _cocoaCStringUsingEncodingTrampoline(self, encoding) } } @_effects(readonly) internal func _nativeIsEqual<T:_AbstractStringStorage>( _ nativeOther: T ) -> Int8 { if count != nativeOther.count { return 0 } return (start == nativeOther.start || (memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0 } @inline(__always) @_effects(readonly) internal func _isEqual(_ other: AnyObject?) -> Int8 { guard let other = other else { return 0 } if self === other { return 1 } // Handle the case where both strings were bridged from Swift. // We can't use String.== because it doesn't match NSString semantics. let knownOther = _KnownCocoaString(other) switch knownOther { case .storage: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __StringStorage.self)) case .shared: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __SharedStringStorage.self)) #if !(arch(i386) || arch(arm)) case .tagged: fallthrough #endif case .cocoa: // We're allowed to crash, but for compatibility reasons NSCFString allows // non-strings here. if _isNSString(other) != 1 { return 0 } // At this point we've proven that it is an NSString of some sort, but not // one of ours. defer { _fixLifetime(other) } let otherUTF16Length = _stdlib_binary_CFStringGetLength(other) // CFString will only give us ASCII bytes here, but that's fine. // We already handled non-ASCII UTF8 strings earlier since they're Swift. if let otherStart = _cocoaUTF8Pointer(other) { //We know that otherUTF16Length is also its byte count at this point if count != otherUTF16Length { return 0 } return (start == otherStart || (memcmp(start, otherStart, count) == 0)) ? 1 : 0 } if UTF16Length != otherUTF16Length { return 0 } /* The abstract implementation of -isEqualToString: falls back to -compare: immediately, so when we run out of fast options to try, do the same. We can likely be more clever here if need be */ return _cocoaStringCompare(self, other) == 0 ? 1 : 0 } } #endif //_runtime(_ObjC) } private typealias CountAndFlags = _StringObject.CountAndFlags // // TODO(String docs): Documentation about the runtime layout of these instances, // which is a little complex. The second trailing allocation holds an // Optional<_StringBreadcrumbs>. // // NOTE: older runtimes called this class _StringStorage. The two // must coexist without conflicting ObjC class names, so it was // renamed. The old name must not be used in the new runtime. final internal class __StringStorage : __SwiftNativeNSString, _AbstractStringStorage { #if arch(i386) || arch(arm) // The total allocated storage capacity. Note that this includes the required // nul-terminator. internal var _realCapacity: Int internal var _count: Int internal var _flags: UInt16 internal var _reserved: UInt16 @inline(__always) internal var count: Int { return _count } @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else // The capacity of our allocation. Note that this includes the nul-terminator, // which is not available for overriding. internal var _realCapacityAndFlags: UInt64 internal var _countAndFlags: _StringObject.CountAndFlags @inline(__always) internal var count: Int { return _countAndFlags.count } // The total allocated storage capacity. Note that this includes the required // nul-terminator. @inline(__always) internal var _realCapacity: Int { return Int(truncatingIfNeeded: _realCapacityAndFlags & CountAndFlags.countMask) } #endif @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var UTF16Length: Int { @_effects(readonly) @inline(__always) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) private init(_doNotCallMe: ()) { _internalInvariantFailure("Use the create method") } deinit { _breadcrumbsAddress.deinitialize(count: 1) } } // Determine the actual number of code unit capacity to request from malloc. We // round up the nearest multiple of 8 that isn't a mulitple of 16, to fully // utilize malloc's small buckets while accounting for the trailing // _StringBreadCrumbs. // // NOTE: We may still under-utilize the spare bytes from the actual allocation // for Strings ~1KB or larger, though at this point we're well into our growth // curve. private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int { #if arch(i386) || arch(arm) // FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so // that the instance size will be a multiple of 4. let bias = Int(bitPattern: _StringObject.nativeBias) let minimum = bias + desiredCapacity + 1 let size = (minimum + 3) & ~3 _internalInvariant(size % 4 == 0) let capacity = size - bias _internalInvariant(capacity > desiredCapacity) return capacity #else // Bigger than _SmallString, and we need 1 extra for nul-terminator. let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity) _internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length") // Round up to the nearest multiple of 8 that isn't also a multiple of 16. let capacity = ((minCap + 7) & -16) + 8 _internalInvariant( capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0) return capacity #endif } // Creation extension __StringStorage { @_effects(releasenone) private static func create( realCodeUnitCapacity: Int, countAndFlags: CountAndFlags ) -> __StringStorage { let storage = Builtin.allocWithTailElems_2( __StringStorage.self, realCodeUnitCapacity._builtinWordValue, UInt8.self, 1._builtinWordValue, Optional<_StringBreadcrumbs>.self) #if arch(i386) || arch(arm) storage._realCapacity = realCodeUnitCapacity storage._count = countAndFlags.count storage._flags = countAndFlags.flags #else storage._realCapacityAndFlags = UInt64(truncatingIfNeeded: realCodeUnitCapacity) storage._countAndFlags = countAndFlags #endif storage._breadcrumbsAddress.initialize(to: nil) storage.terminator.pointee = 0 // nul-terminated // NOTE: We can't _invariantCheck() now, because code units have not been // initialized. But, _StringGuts's initializer will. return storage } @_effects(releasenone) private static func create( capacity: Int, countAndFlags: CountAndFlags ) -> __StringStorage { _internalInvariant(capacity >= countAndFlags.count) let realCapacity = determineCodeUnitCapacity(capacity) _internalInvariant(realCapacity > capacity) return __StringStorage.create( realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags) } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, capacity: Int, isASCII: Bool ) -> __StringStorage { let countAndFlags = CountAndFlags( mortalCount: bufPtr.count, isASCII: isASCII) _internalInvariant(capacity >= bufPtr.count) let storage = __StringStorage.create( capacity: capacity, countAndFlags: countAndFlags) let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked storage.mutableStart.initialize(from: addr, count: bufPtr.count) storage._invariantCheck() return storage } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool ) -> __StringStorage { return __StringStorage.create( initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII) } } // Usage extension __StringStorage { @inline(__always) private var mutableStart: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self)) } @inline(__always) private var mutableEnd: UnsafeMutablePointer<UInt8> { return mutableStart + count } @inline(__always) internal var start: UnsafePointer<UInt8> { return UnsafePointer(mutableStart) } @inline(__always) private final var end: UnsafePointer<UInt8> { return UnsafePointer(mutableEnd) } // Point to the nul-terminator. @inline(__always) private final var terminator: UnsafeMutablePointer<UInt8> { return mutableEnd } @inline(__always) private var codeUnits: UnsafeBufferPointer<UInt8> { return UnsafeBufferPointer(start: start, count: count) } // @opaque internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> { let raw = Builtin.getTailAddr_Word( start._rawValue, _realCapacity._builtinWordValue, UInt8.self, Optional<_StringBreadcrumbs>.self) return UnsafeMutablePointer(raw) } // The total capacity available for code units. Note that this excludes the // required nul-terminator. internal var capacity: Int { return _realCapacity &- 1 } // The unused capacity available for appending. Note that this excludes the // required nul-terminator. // // NOTE: Callers who wish to mutate this storage should enfore nul-termination @inline(__always) private var unusedStorage: UnsafeMutableBufferPointer<UInt8> { return UnsafeMutableBufferPointer( start: mutableEnd, count: unusedCapacity) } // The capacity available for appending. Note that this excludes the required // nul-terminator. internal var unusedCapacity: Int { return _realCapacity &- count &- 1 } #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self)) let rawStart = UnsafeRawPointer(start) _internalInvariant(unusedCapacity >= 0) _internalInvariant(count <= capacity) _internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart) _internalInvariant(self._realCapacity > self.count, "no room for nul-terminator") _internalInvariant(self.terminator.pointee == 0, "not nul terminated") let str = asString _internalInvariant(str._guts._object.isPreferredRepresentation) _countAndFlags._invariantCheck() if isASCII { _internalInvariant(_allASCII(self.codeUnits)) } if let crumbs = _breadcrumbsAddress.pointee { crumbs._invariantCheck(for: self.asString) } _internalInvariant(_countAndFlags.isNativelyStored) _internalInvariant(_countAndFlags.isTailAllocated) } #endif // INTERNAL_CHECKS_ENABLED } // Appending extension __StringStorage { // Perform common post-RRC adjustments and invariant enforcement. @_effects(releasenone) private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) { let countAndFlags = CountAndFlags( mortalCount: newCount, isASCII: newIsASCII) #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif self.terminator.pointee = 0 // TODO(String performance): Consider updating breadcrumbs when feasible. self._breadcrumbsAddress.pointee = nil _invariantCheck() } // Perform common post-append adjustments and invariant enforcement. @_effects(releasenone) private func _postAppendAdjust( appendedCount: Int, appendedIsASCII isASCII: Bool ) { let oldTerminator = self.terminator _postRRCAdjust( newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII) _internalInvariant(oldTerminator + appendedCount == self.terminator) } @_effects(releasenone) internal func appendInPlace( _ other: UnsafeBufferPointer<UInt8>, isASCII: Bool ) { _internalInvariant(self.capacity >= other.count) let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked let srcCount = other.count self.mutableEnd.initialize(from: srcAddr, count: srcCount) _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } @_effects(releasenone) internal func appendInPlace<Iter: IteratorProtocol>( _ other: inout Iter, isASCII: Bool ) where Iter.Element == UInt8 { var srcCount = 0 while let cu = other.next() { _internalInvariant(self.unusedCapacity >= 1) unusedStorage[srcCount] = cu srcCount += 1 } _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } internal func clear() { _postRRCAdjust(newCount: 0, newIsASCII: true) } } // Removing extension __StringStorage { @_effects(releasenone) internal func remove(from lower: Int, to upper: Int) { _internalInvariant(lower <= upper) let lowerPtr = mutableStart + lower let upperPtr = mutableStart + upper let tailCount = mutableEnd - upperPtr lowerPtr.moveInitialize(from: upperPtr, count: tailCount) _postRRCAdjust( newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII) } // Reposition a tail of this storage from src to dst. Returns the length of // the tail. @_effects(releasenone) internal func _slideTail( src: UnsafeMutablePointer<UInt8>, dst: UnsafeMutablePointer<UInt8> ) -> Int { _internalInvariant(dst >= mutableStart && src <= mutableEnd) let tailCount = mutableEnd - src dst.moveInitialize(from: src, count: tailCount) return tailCount } @_effects(releasenone) internal func replace( from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8> ) { _internalInvariant(lower <= upper) let replCount = replacement.count _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. lowerPtr.moveInitialize( from: UnsafeMutablePointer( mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked), count: replCount) let isASCII = self.isASCII && _allASCII(replacement) _postRRCAdjust(newCount: lower + replCount + tailCount, newIsASCII: isASCII) } @_effects(releasenone) internal func replace<C: Collection>( from lower: Int, to upper: Int, with replacement: C, replacementCount replCount: Int ) where C.Element == UInt8 { _internalInvariant(lower <= upper) _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. var isASCII = self.isASCII var srcCount = 0 for cu in replacement { if cu >= 0x80 { isASCII = false } lowerPtr[srcCount] = cu srcCount += 1 } _internalInvariant(srcCount == replCount) _postRRCAdjust( newCount: lower + replCount + tailCount, newIsASCII: isASCII) } } // For shared storage and bridging literals // NOTE: older runtimes called this class _SharedStringStorage. The two // must coexist without conflicting ObjC class names, so it was // renamed. The old name must not be used in the new runtime. final internal class __SharedStringStorage : __SwiftNativeNSString, _AbstractStringStorage { internal var _owner: AnyObject? internal var start: UnsafePointer<UInt8> #if arch(i386) || arch(arm) internal var _count: Int internal var _flags: UInt16 @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else internal var _countAndFlags: _StringObject.CountAndFlags #endif internal var _breadcrumbs: _StringBreadcrumbs? = nil internal var count: Int { return _countAndFlags.count } internal init( immortal ptr: UnsafePointer<UInt8>, countAndFlags: _StringObject.CountAndFlags ) { self._owner = nil self.start = ptr #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif super.init() self._invariantCheck() } @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var UTF16Length: Int { @_effects(readonly) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other:AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) } extension __SharedStringStorage { #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { if let crumbs = _breadcrumbs { crumbs._invariantCheck(for: self.asString) } _countAndFlags._invariantCheck() _internalInvariant(!_countAndFlags.isNativelyStored) _internalInvariant(!_countAndFlags.isTailAllocated) let str = asString _internalInvariant(!str._guts._object.isPreferredRepresentation) } #endif // INTERNAL_CHECKS_ENABLED }
5a99c4bfd45ffee73b8a57112f7417d1
28.892552
85
0.689772
false
false
false
false
CodaFi/swift
refs/heads/main
test/PrintAsObjC/accessibility.swift
apache-2.0
19
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -parse-as-library %s -typecheck -emit-objc-header-path %t/accessibility.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-PUBLIC %s < %t/accessibility.h // RUN: %check-in-clang %t/accessibility.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/accessibility-internal.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-internal.h // RUN: %check-in-clang %t/accessibility-internal.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -import-objc-header %S/../Inputs/empty.h -emit-objc-header-path %t/accessibility-imported-header.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-imported-header.h // RUN: %check-in-clang %t/accessibility-imported-header.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -DMAIN -emit-objc-header-path %t/accessibility-main.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-main.h // RUN: %check-in-clang %t/accessibility-main.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -application-extension -emit-objc-header-path %t/accessibility-appext.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-appext.h // RUN: %check-in-clang %t/accessibility-appext.h // REQUIRES: objc_interop // CHECK: #ifndef ACCESSIBILITY_SWIFT_H // CHECK-NEXT: #define ACCESSIBILITY_SWIFT_H // CHECK-LABEL: @interface A_Public{{$}} // CHECK-INTERNAL-NEXT: init // CHECK-NEXT: @end @objc @objcMembers public class A_Public {} // CHECK-PUBLIC-NOT: B_Internal // CHECK-INTERNAL-LABEL: @interface B_Internal{{$}} // CHECK-INTERNAL-NEXT: init // CHECK-INTERNAL-NEXT: @end @objc @objcMembers internal class B_Internal {} // CHECK-NOT: C_Private @objc @objcMembers private class C_Private {} #if MAIN #if canImport(AppKit) import AppKit @NSApplicationMain @objc class AppDelegate : NSApplicationDelegate {} #elseif canImport(UIKit) import UIKit @UIApplicationMain @objc class AppDelegate : NSObject, UIApplicationDelegate {} #else // Uh oh, this test depends on having an app delegate. #error("Unsupported platform") #endif #endif
3113c2b2ef588cc1392dab1b36e32c84
43.135593
238
0.750768
false
false
false
false
huonw/swift
refs/heads/master
test/refactoring/TrailingClosure/basic.swift
apache-2.0
2
struct Foo { static func foo(a: () -> Int) {} func qux(x: Int, y: () -> Int ) {} } func testTrailingClosure() -> String { Foo.foo(a: { 1 }) Foo.bar(a: { print(3); return 1 }) Foo().qux(x: 1, y: { 1 }) let _ = Foo().quux(x: 1, y: { 1 }) [1,2,3] .filter({ $0 % 2 == 0 }) .map({ $0 + 1 }) } // RUN: %empty-directory(%t.result) // RUN: %refactor -trailingclosure -source-filename %s -pos=7:3 > %t.result/L7.swift // RUN: diff -u %S/Outputs/basic/L7.swift.expected %t.result/L7.swift // RUN: %refactor -trailingclosure -source-filename %s -pos=8:11 > %t.result/L8.swift // RUN: diff -u %S/Outputs/basic/L8.swift.expected %t.result/L8.swift // RUN: %refactor -trailingclosure -source-filename %s -pos=9:8 > %t.result/L9.swift // RUN: diff -u %S/Outputs/basic/L9.swift.expected %t.result/L9.swift // RUN: %refactor -trailingclosure -source-filename %s -pos=10:17 > %t.result/L10.swift // RUN: diff -u %S/Outputs/basic/L10.swift.expected %t.result/L10.swift // RUN: %refactor -trailingclosure -source-filename %s -pos=13:5 > %t.result/L13.swift // RUN: diff -u %S/Outputs/basic/L13.swift.expected %t.result/L13.swift // RUN: %refactor -trailingclosure -source-filename %s -pos=14:5 > %t.result/L14.swift // RUN: diff -u %S/Outputs/basic/L14.swift.expected %t.result/L14.swift
6bc863f71c32d7aaf0747b68bf7e2438
37.176471
87
0.644838
false
false
false
false
Pyroh/Fluor
refs/heads/main
Fluor/Views/PoppingLinkButton.swift
mit
1
// // PoppingLinkButton.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa @IBDesignable class PoppingLinkButton: NSButton { @IBInspectable var growsOnHover: Bool = true @IBInspectable var growFactor: CGFloat = 1.15 override func layout() { super.layout() self.centerLayerAnchor() } override func updateTrackingAreas() { super.updateTrackingAreas() self.trackingAreas.forEach(self.removeTrackingArea(_:)) let trackingArea = NSTrackingArea(rect: self.bounds, options: [.activeAlways, .mouseEnteredAndExited], owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } override func resetCursorRects() { super.resetCursorRects() self.addCursorRect(self.bounds, cursor: .pointingHand) } // Thanks to Kite Compositor (kiteapp.co) override func mouseEntered(with event: NSEvent) { guard self.growsOnHover, let layer = self.layer else { return } let transformScaleAnimation = CASpringAnimation() transformScaleAnimation.fillMode = CAMediaTimingFillMode.forwards transformScaleAnimation.duration = 0.99321 transformScaleAnimation.isRemovedOnCompletion = false transformScaleAnimation.keyPath = "transform.scale" transformScaleAnimation.toValue = self.growFactor transformScaleAnimation.stiffness = 200 transformScaleAnimation.damping = 10 transformScaleAnimation.mass = 0.7 transformScaleAnimation.initialVelocity = 4 layer.add(transformScaleAnimation, forKey: "growAnimation") } // Thanks to Kite Compositor (kiteapp.co) override func mouseExited(with event: NSEvent) { guard self.growsOnHover, let layer = self.layer else { return } let transformScaleAnimation1 = CASpringAnimation() transformScaleAnimation1.duration = 0.99321 transformScaleAnimation1.fillMode = CAMediaTimingFillMode.forwards transformScaleAnimation1.isRemovedOnCompletion = false transformScaleAnimation1.keyPath = "transform.scale" transformScaleAnimation1.toValue = 1 transformScaleAnimation1.stiffness = 200 transformScaleAnimation1.damping = 10 transformScaleAnimation1.mass = 0.7 transformScaleAnimation1.initialVelocity = 4 layer.add(transformScaleAnimation1, forKey: "shrinkAnimation") } }
b86a93093ebcf977f1cd6600c0d331b4
38.217391
138
0.707871
false
false
false
false
hilen/TSWeChat
refs/heads/master
TSWeChat/Classes/CoreModule/Http/TSResponseSerializer.swift
mit
1
// // TSResponseSerializer.swift // TSWeChat // // Created by Hilen on 3/2/16. // Copyright © 2016 Hilen. All rights reserved. // import Alamofire import SwiftyJSON private let kKeyMessage = "message" private let kKeyData = "data" private let kKeyCode = "code" // MARK: - SwiftyJSON 和 Alamofire 的自定义解析器 //文件上传的解析,图片和音频 extension Alamofire.DataRequest { @discardableResult // static func responseFileUploadSwiftyJSON(completionHandler: (Alamofire.Result) -> Void) -> Self { // return response(responseSerializer: DataRequest.fileUploadSwiftyJSONResponseSerializer(), completionHandler) //// return response(responseSerializer: <#T##T#>, completionHandler: <#T##(DataResponse<T.SerializedObject>) -> Void#>) // } static func fileUploadSwiftyJSONResponseSerializer() -> DataResponseSerializer<Any> { return DataResponseSerializer { request, response, data, error in guard error == nil else { log.error("error:\(String(describing: error))") let failureReason = "网络不给力,请稍候再试 :)" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "", code: 1002, userInfo: userInfo) return .failure(error) } guard let validData = data, validData.count > 0 else { let failureReason = "数据错误,请稍候再试 :)" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "", code: 1003, userInfo: userInfo) return .failure(error) } //JSON 解析错误 if let json = try? JSON(data: validData) { if let jsonError = json.error { return Result.failure(jsonError) } //服务器返回 code 错误处理, 假设是 1993 let code = json[kKeyCode].intValue if code == 1993 { let userInfo = [NSLocalizedFailureReasonErrorKey: json["message"].stringValue] let error = NSError(domain: "", code: 1004, userInfo: userInfo) return Result.failure(error) } return Result.success(json) } else { let userInfo = [NSLocalizedFailureReasonErrorKey: "JSON parse error"] let error = NSError(domain: "", code: 1005, userInfo: userInfo) return Result.failure(error) } } } }
f72609ab213d657e40af65ccfcc285cb
39.046875
127
0.577448
false
false
false
false
vmanot/swift-package-manager
refs/heads/master
Tests/XcodeprojTests/XcodeProjectModelSerializationTests.swift
apache-2.0
1
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import TestSupport @testable import Xcodeproj import XCTest class XcodeProjectModelSerializationTests: XCTestCase { func testBasicProjectSerialization() { // Create a project. let proj = Xcode.Project() // Serialize it to a property list. let plist = proj.generatePlist() // Assert various things about the property list. guard case let .dictionary(topLevelDict) = plist else { XCTFail("top-level of plist must be a dictionary") return } XCTAssertFalse(topLevelDict.isEmpty) // FIXME: We should factor out all of the following using helper assert // functions that deal with the enum casing. // Archive version should be 1. guard case let .string(archiveVersionStr) = topLevelDict["archiveVersion"]! else { XCTFail("top-level plist dictionary must have an `archiveVersion` string") return } XCTAssertEqual(archiveVersionStr, "1") // Object version should be 46 (Xcode 8.0). guard case let .string(objectVersionStr) = topLevelDict["objectVersion"]! else { XCTFail("top-level plist dictionary must have an `objectVersion` string") return } XCTAssertEqual(objectVersionStr, "46") // There should be a root object. guard case let .identifier(rootObjectID) = topLevelDict["rootObject"]! else { XCTFail("top-level plist dictionary must have a `rootObject` string") return } XCTAssertFalse(rootObjectID.isEmpty) // There should be a dictionary mapping identifiers to object dictionaries. guard case let .dictionary(objectDict) = topLevelDict["objects"]! else { XCTFail("top-level plist dictionary must have a `objects` dictionary") return } XCTAssertFalse(objectDict.isEmpty) // The root object should reference a PBXProject dictionary. guard case let .dictionary(projectDict) = objectDict[rootObjectID]! else { XCTFail("object dictionary must have an entry for the project") return } XCTAssertFalse(projectDict.isEmpty) // Project dictionary's `isa` must be "PBXProject". guard case let .string(projectClassName) = projectDict["isa"]! else { XCTFail("project object dictionary must have an `isa` string") return } XCTAssertEqual(projectClassName, "PBXProject") } func testBuildSettingsSerialization() { // Create build settings. var buildSettings = Xcode.BuildSettingsTable.BuildSettings() let productNameValue = "$(TARGET_NAME:c99extidentifier)" buildSettings.PRODUCT_NAME = productNameValue let otherSwiftFlagValues = ["$(inherited)", "-DXcode"] buildSettings.OTHER_SWIFT_FLAGS = otherSwiftFlagValues // Serialize it to a property list. let plist = buildSettings.asPropertyList() // Assert things about plist guard case let .dictionary(buildSettingsDict) = plist else { XCTFail("build settings plist must be a dictionary") return } guard let productNamePlist = buildSettingsDict["PRODUCT_NAME"], let otherSwiftFlagsPlist = buildSettingsDict["OTHER_SWIFT_FLAGS"] else { XCTFail("build settings plist must contain PRODUCT_NAME and OTHER_SWIFT_FLAGS") return } guard case let .string(productName) = productNamePlist else { XCTFail("productName plist must be a string") return } XCTAssertEqual(productName, productNameValue) guard case let .array(otherSwiftFlagsPlists) = otherSwiftFlagsPlist else { XCTFail("otherSwiftFlags plist must be an array") return } let otherSwiftFlags = otherSwiftFlagsPlists.flatMap { flagPlist -> String? in guard case let .string(flag) = flagPlist else { XCTFail("otherSwiftFlag plist must be string") return nil } return flag } XCTAssertEqual(otherSwiftFlags, otherSwiftFlagValues) } static var allTests = [ ("testBasicProjectSerialization", testBasicProjectSerialization), ("testBuildSettingsSerialization", testBuildSettingsSerialization), ] }
770d8b80e01741eb5621b267a4a78954
36.541985
91
0.629524
false
true
false
false