repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageFilter/DisplacementMap.swift | 1 | 2983 | //
// DisplacementMap.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
@inlinable
@inline(__always)
public func DisplacementMap<S, T>(_ source: Image<S>, _ displacement: Image<T>, _ xChannelSelector: Int, _ yChannelSelector: Int, _ scale: Size) -> Image<S> {
return Image(texture: DisplacementMap(Texture(image: source), Texture(image: displacement), xChannelSelector, yChannelSelector, scale), resolution: displacement.resolution, colorSpace: source.colorSpace)
}
@inlinable
@inline(__always)
public func DisplacementMap<S, T>(_ texture: Texture<S>, _ displacement: Texture<T>, _ xChannelSelector: Int, _ yChannelSelector: Int, _ scale: Size) -> Texture<S> {
let width = displacement.width
let height = displacement.height
let resamplingAlgorithm = texture.resamplingAlgorithm
let fileBacked = texture.fileBacked
var result = Texture<S>(width: width, height: height, resamplingAlgorithm: resamplingAlgorithm, fileBacked: fileBacked)
result.withUnsafeMutableBufferPointer {
guard var result = $0.baseAddress else { return }
displacement.withUnsafeBufferPointer {
guard var displacement = $0.baseAddress else { return }
for y in 0..<height {
for x in 0..<width {
let d = displacement.pointee
let _x = Double(x) + scale.width * (d.component(xChannelSelector) - 0.5)
let _y = Double(y) + scale.height * (d.component(yChannelSelector) - 0.5)
result.pointee = S(texture.pixel(Point(x: _x, y: _y)))
displacement += 1
result += 1
}
}
}
}
return result
}
| mit | 728bf250b53e99ced8837b7d7b3b62e3 | 42.231884 | 207 | 0.648005 | 4.465569 | false | false | false | false |
appplemac/ios9-examples | iOS9Sampler/SampleViewControllers/ReplayKitViewController.swift | 2 | 5924 | //
// ReplayKitViewController.swift
// iOS9Sampler
//
// Created by manhattan918 on 2015/10/25.
// Copyright © 2015年 manhattan918. All rights reserved.
//
import UIKit
import ReplayKit
class ReplayKitViewController: UIViewController, RPScreenRecorderDelegate, RPPreviewViewControllerDelegate {
@IBOutlet weak var startRecordingButton: UIButton!
@IBOutlet weak var stopRecordingButton: UIButton!
@IBOutlet weak var processingView: UIActivityIndicatorView!
private let recorder = RPScreenRecorder.sharedRecorder()
// =========================================================================
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
recorder.delegate = self
processingView.hidden = true
buttonEnabledControl(recorder.recording)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// =========================================================================
// MARK: - RPScreenRecorderDelegate
// called after stopping the recording
func screenRecorder(screenRecorder: RPScreenRecorder, didStopRecordingWithError error: NSError, previewViewController: RPPreviewViewController?) {
NSLog("Stop recording")
}
// called when the recorder availability has changed
func screenRecorderDidChangeAvailability(screenRecorder: RPScreenRecorder) {
let availability = screenRecorder.available
NSLog("Availablility: \(availability)")
}
// =========================================================================
// MARK: - RPPreviewViewControllerDelegate
// called when preview is finished
func previewControllerDidFinish(previewController: RPPreviewViewController) {
NSLog("Preview finish")
dispatch_async(dispatch_get_main_queue()) { [unowned previewController] in
// close preview window
previewController.dismissViewControllerAnimated(true, completion: nil)
}
}
// =========================================================================
// MARK: - IBAction
@IBAction func startRecordingButtonTapped(sender: AnyObject) {
processingView.hidden = false
// start recording
recorder.startRecordingWithMicrophoneEnabled(true) { [unowned self] error in
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.processingView.hidden = true
}
if let error = error {
NSLog("Failed start recording: \(error.localizedDescription)")
return
}
NSLog("Start recording")
self.buttonEnabledControl(true)
}
}
@IBAction func stopRecordingButtonTapped(sender: AnyObject) {
processingView.hidden = false
// end recording
recorder.stopRecordingWithHandler({ [unowned self] (previewViewController, error) in
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.processingView.hidden = true
}
self.buttonEnabledControl(false)
if let error = error {
NSLog("Failed stop recording: \(error.localizedDescription)")
return
}
NSLog("Stop recording")
previewViewController?.previewControllerDelegate = self
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
// show preview window
self.presentViewController(previewViewController!, animated: true, completion: nil)
}
})
}
// =========================================================================
// MARK: - Helper
// control the enabled of each button
private func buttonEnabledControl(isRecording: Bool) {
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
let enebledColor = UIColor(red: 0.0, green: 122.0/255.0, blue:1.0, alpha: 1.0)
let disabledColor = UIColor.lightGrayColor()
if !self.recorder.available {
self.startRecordingButton.enabled = false
self.startRecordingButton.backgroundColor = disabledColor
self.stopRecordingButton.enabled = false
self.stopRecordingButton.backgroundColor = disabledColor
return
}
self.startRecordingButton.enabled = !isRecording
self.startRecordingButton.backgroundColor = isRecording ? disabledColor : enebledColor
self.stopRecordingButton.enabled = isRecording
self.stopRecordingButton.backgroundColor = isRecording ? enebledColor : disabledColor
}
}
private func createHaloAt(location: CGPoint, withRadius radius: CGFloat) {
let halo = PulsingHaloLayer()
halo.repeatCount = 1
halo.position = location
halo.radius = radius * 2.0
halo.fromValueForRadius = 0.5
halo.keyTimeForHalfOpacity = 0.7
halo.animationDuration = 0.8
self.view.layer.addSublayer(halo)
}
// =========================================================================
// MARK: - Touch Handler
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for obj: AnyObject in touches {
let touch = obj as! UITouch
let location = touch.locationInView(self.view)
let radius = touch.majorRadius
self.createHaloAt(location, withRadius: radius)
}
}
}
| mit | c145d7be2753abb091d7226caf931719 | 34.45509 | 150 | 0.566627 | 5.874008 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/server/TKBuzzInfoProvider.swift | 1 | 6718 | //
// TKBuzzInfoProvider.swift
// TripKit
//
// Created by Adrian Schoenig on 11/12/2015.
// Copyright © 2015 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import CoreLocation
import MapKit
// MARK: - Fetcher methods
public enum TKBuzzInfoProvider {
public static func downloadContent(of service: Service, embarkationDate: Date, region: TKRegion?, completion: @escaping (Service, Bool) -> Void) {
assert(service.managedObjectContext?.parent != nil || Thread.isMainThread)
guard !service.isRequestingServiceData else { return }
service.isRequestingServiceData = true
TKRegionManager.shared.requireRegions { result in
if case .failure = result {
service.isRequestingServiceData = false
completion(service, false)
return
}
guard let region = region ?? service.region else {
service.isRequestingServiceData = false
completion(service, false)
return
}
let paras: [String: Any] = [
"region": region.code,
"serviceTripID": service.code,
"operator": service.operatorName ?? "",
"embarkationDate": Int(embarkationDate.timeIntervalSince1970),
"encode": true
]
TKServer.shared.hit(
TKAPI.ServiceResponse.self,
path: "service.json",
parameters: paras,
region: region
) { _, _, result in
service.isRequestingServiceData = false
let response = try? result.get()
let success = response.map { Self.addContent(from: $0, to: service) }
completion(service, success ?? false)
}
}
}
@discardableResult
public static func addContent(from response: TKAPI.ServiceResponse, to service: Service) -> Bool {
guard
let context = service.managedObjectContext,
response.error == nil,
let shapes = response.shapes
else {
return false
}
assert(context.parent != nil || Thread.isMainThread)
if let realTime = response.realTimeStatus {
service.adjustRealTimeStatus(for: realTime)
}
service.addVehicles(primary: response.primaryVehicle, alternatives: response.alternativeVehicles)
TKAPIToCoreDataConverter.updateOrAddAlerts(response.alerts, in: context)
Shape.insertNewShapes(
from: shapes,
for: service,
modeInfo: response.modeInfo,
clearRealTime: false // these are timetable times, so don't clear real-time
)
return true
}
/**
Asynchronously fetches additional region information for the provided region.
*/
public static func fetchRegionInformation(for region: TKRegion) async -> TKAPI.RegionInfo? {
try? await TKServer.shared.hit(
RegionInfoResponse.self,
.POST,
path: "regionInfo.json",
parameters: ["region": region.code],
region: region
).result.get().regions.first
}
@available(*, deprecated, renamed: "fetchRegionInformation(for:)")
public static func fetchRegionInformation(forRegion region: TKRegion) async -> TKAPI.RegionInfo? {
await fetchRegionInformation(for: region)
}
/**
Asynchronously fetches paratransit information for the provided region.
*/
public static func fetchParatransitInformation(for region: TKRegion) async -> TKAPI.Paratransit? {
await fetchRegionInformation(for: region)?.paratransit
}
@available(*, deprecated, renamed: "fetchParatransitInformation(for:)")
public static func fetchParatransitInformation(forRegion region: TKRegion) async -> TKAPI.Paratransit? {
await fetchParatransitInformation(for: region)
}
/**
Asynchronously fetches all available individual public transport modes for the provided region.
*/
public static func fetchPublicTransportModes(for region: TKRegion) async -> [TKModeInfo]? {
await fetchRegionInformation(for: region)?.transitModes
}
@available(*, deprecated, renamed: "fetchPublicTransportModes(for:)")
public static func fetchPublicTransportModes(forRegion region: TKRegion) async throws -> [TKModeInfo]? {
await fetchPublicTransportModes(for: region)
}
/**
Asynchronously fetches additional location information for a specified coordinate.
*/
public static func fetchLocationInformation(_ annotation: MKAnnotation, for region: TKRegion) async throws -> TKAPI.LocationInfo {
let paras: [String: Any]
if let named = annotation as? TKNamedCoordinate, let identifier = named.locationID {
paras = [ "identifier": identifier, "region": region.code ]
} else {
paras = [ "lat": annotation.coordinate.latitude, "lng": annotation.coordinate.longitude ]
}
return try await TKServer.shared.hit(
TKAPI.LocationInfo.self,
path: "locationInfo.json",
parameters: paras,
region: region
).result.get()
}
/**
Asynchronously fetches additional location information for a location of specified ID
*/
public static func fetchLocationInformation(locationID: String, for region: TKRegion) async throws -> TKAPI.LocationInfo {
return try await TKServer.shared.hit(
TKAPI.LocationInfo.self,
path: "locationInfo.json",
parameters: [
"identifier": locationID,
"region": region.code
],
region: region
).result.get()
}
/**
Asynchronously fetches additional location information for a specified coordinate.
*/
public static func fetchLocationInformation(_ coordinate: CLLocationCoordinate2D, for region: TKRegion) async throws -> TKAPI.LocationInfo {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
return try await fetchLocationInformation(annotation, for: region)
}
// MARK: - Transit alerts
/**
Asynchronously fetches transit alerts for the provided region.
*/
public static func fetchTransitAlerts(for region: TKRegion) async throws -> [TKAPI.AlertMapping] {
let paras: [String: Any] = [
"region": region.code,
"v": TKSettings.parserJsonVersion
]
return try await TKServer.shared.hit(
AlertsTransitResponse.self,
path: "alerts/transit.json",
parameters: paras,
region: region
).result.get().alerts
}
@available(*, deprecated, renamed: "fetchTransitAlerts(for:)")
public static func fetchTransitAlerts(forRegion region: TKRegion) async throws -> [TKAPI.AlertMapping] {
try await fetchTransitAlerts(for: region)
}
}
// MARK: - Response data model
extension TKBuzzInfoProvider {
struct RegionInfoResponse: Codable {
let regions: [TKAPI.RegionInfo]
let server: String?
}
public struct AlertsTransitResponse: Codable {
public let alerts: [TKAPI.AlertMapping]
}
}
| apache-2.0 | 71f5aefc249c6b40140d0a97429b0963 | 30.834123 | 148 | 0.688849 | 4.572498 | false | false | false | false |
palle-k/Covfefe | Sources/Covfefe/Normalization.swift | 1 | 11089 | //
// Normalization.swift
// Covfefe
//
// Created by Palle Klewitz on 11.08.17.
// Copyright (c) 2017 Palle Klewitz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension Grammar {
static func eliminateMixedProductions(productions: [Production]) -> [Production] {
return productions.flatMap { production -> [Production] in
// Determine, if the production is invalid and if not, return early
let terminals = production.generatedTerminals
let nonTerminals = production.generatedNonTerminals
if terminals.isEmpty {
return [production]
}
if nonTerminals.isEmpty && terminals.count == 1 {
return [production]
}
// Find all terminals and their indices in the production
let enumeratedTerminals = production.production.enumerated().compactMap { offset, element -> (Int, Terminal)? in
guard case .terminal(let terminal) = element else {
return nil
}
return (offset, terminal)
}
// Generate new patterns which replace the terminals in the existing production
let patterns = enumeratedTerminals.map { element -> NonTerminal in
let (offset, terminal) = element
return NonTerminal(name: "\(production.pattern.name)-\(String(terminal.hashValue % 65526, radix: 16, uppercase: false))-\(offset)")
}
// Update the existing production by replacing all terminals with the new patterns
let updatedProductionElements = zip(enumeratedTerminals, patterns).map{($0.0, $0.1, $1)}.reduce(production.production) { productionElements, element -> [Symbol] in
let (offset, _, nonTerminal) = element
var updatedElements = productionElements
updatedElements[offset] = .nonTerminal(nonTerminal)
return updatedElements
}
let updatedProduction = Production(pattern: production.pattern, production: updatedProductionElements)
// Generate new productions which produce the replaced terminals
let newProductions = zip(enumeratedTerminals, patterns).map{($0.0, $0.1, $1)}.map { element -> Production in
let (_, terminal, nonTerminal) = element
return Production(pattern: nonTerminal, production: [.terminal(terminal)])
}
return newProductions + [updatedProduction]
}
}
static func decomposeProductions(productions: [Production]) -> [Production] {
return productions.flatMap { production -> [Production] in
guard production.generatedNonTerminals.count >= 3 else {
return [production]
}
let newProductions = production.generatedNonTerminals.dropLast().pairs().enumerated().map { element -> Production in
let (offset, (nonTerminal, next)) = element
return Production(
pattern: NonTerminal(name: "\(production.pattern.name)-\(nonTerminal.name)-\(offset)"),
production: [.nonTerminal(nonTerminal), n("\(production.pattern.name)-\(next.name)-\(offset + 1)")]
)
}
let lastProduction = Production(
pattern: NonTerminal(name: "\(production.pattern.name)-\(production.generatedNonTerminals.dropLast().last!.name)-\(production.generatedNonTerminals.count-2)"),
production: production.generatedNonTerminals.suffix(2).map{.nonTerminal($0)}
)
let firstProduction = Production(pattern: production.pattern, production: newProductions[0].production)
let middleProductions = newProductions.dropFirst().collect(Array.init)
return [firstProduction] + middleProductions + [lastProduction]
}
}
static func eliminateEmpty(productions: [Production], start: NonTerminal) -> [Production] {
let groupedProductions = Dictionary(grouping: productions, by: {$0.pattern})
func generatesEmpty(_ nonTerminal: NonTerminal, path: Set<NonTerminal>) -> Bool {
if path.contains(nonTerminal) {
return false
}
let directProductions = groupedProductions[nonTerminal, default: []]
return directProductions.contains { production -> Bool in
if production.production.isEmpty {
return true
}
return production.generatedNonTerminals.count == production.production.count
&& production.generatedNonTerminals.allSatisfy { pattern -> Bool in
generatesEmpty(pattern, path: path.union([nonTerminal]))
}
}
}
func generatesNonEmpty(_ nonTerminal: NonTerminal, path: Set<NonTerminal>) -> Bool {
if path.contains(nonTerminal) {
return false
}
let directProductions = groupedProductions[nonTerminal, default: []]
return directProductions.contains { production -> Bool in
if !production.generatedTerminals.isEmpty {
return true
}
return production.generatedNonTerminals.contains { pattern -> Bool in
generatesNonEmpty(pattern, path: path.union([nonTerminal]))
}
}
}
let result = Dictionary(uniqueKeysWithValues: groupedProductions.keys.map { key -> (NonTerminal, (generatesEmpty: Bool, generatesNonEmpty: Bool)) in
(key, (generatesEmpty: generatesEmpty(key, path: []), generatesNonEmpty: generatesNonEmpty(key, path: [])))
})
let updatedProductions = productions.flatMap { production -> [Production] in
if production.production.isEmpty && production.pattern != start {
return []
}
if production.isFinal {
return [production]
}
let produced = production.production.reduce([[]]) { (partialResult, symbol) -> [[Symbol]] in
if case .nonTerminal(let nonTerminal) = symbol {
let (empty, nonEmpty) = result[nonTerminal] ?? (false, true)
if !nonEmpty {
return partialResult
} else if !empty {
return partialResult.map {$0 + [symbol]}
} else {
return partialResult + partialResult.map {$0 + [symbol]}
}
} else {
return partialResult.map {$0 + [symbol]}
}
}
return produced.compactMap { sequence -> Production? in
guard !sequence.isEmpty || production.pattern == start else {
return nil
}
return Production(pattern: production.pattern, production: sequence)
}
}
return updatedProductions
}
static func eliminateChainProductions(productions: [Production]) -> [Production] {
let nonTerminalProductions = Dictionary(grouping: productions, by: {$0.pattern})
func findNonChainProduction(from start: Production, visited: Set<NonTerminal>, path: [NonTerminal]) -> [(Production, [NonTerminal])] {
if start.isFinal || start.generatedNonTerminals.count != 1 {
return [(start, path)]
} else if visited.contains(start.pattern) {
return []
}
let nonTerminal = start.generatedNonTerminals[0]
let reachableProductions = nonTerminalProductions[nonTerminal] ?? []
return reachableProductions.flatMap{findNonChainProduction(from: $0, visited: visited.union([start.pattern]), path: path + [nonTerminal])}
}
return productions.flatMap { production -> [Production] in
let nonChainProductions = findNonChainProduction(from: production, visited: [], path: [])
return nonChainProductions.map { element -> Production in
let (p, chain) = element
return Production(pattern: production.pattern, production: p.production, chain: chain)
}
}
}
static func eliminateUnusedProductions(productions: [Production], start: NonTerminal) -> [Production] {
let nonTerminalProductions = Dictionary(grouping: productions, by: {$0.pattern})
func mark(nonTerminal: NonTerminal, visited: Set<NonTerminal>) -> Set<NonTerminal> {
if visited.contains(nonTerminal) {
return visited
}
let newVisited = visited.union([nonTerminal])
let reachableProductions = nonTerminalProductions[nonTerminal] ?? []
return reachableProductions.reduce(newVisited) { partialVisited, production -> Set<NonTerminal> in
production.generatedNonTerminals.reduce(partialVisited) { partial, n -> Set<NonTerminal> in
mark(nonTerminal: n, visited: partial)
}
}
}
let reachableNonTerminals = mark(nonTerminal: start, visited: [])
return productions.filter { production -> Bool in
reachableNonTerminals.contains(production.pattern)
}
}
/// Generates a context free grammar equal to the current grammar which is in Chomsky Normal Form.
/// The grammar is converted by decomposing non-terminal productions of lengths greater than 2,
/// introducing new non-terminals to replace terminals in mixed productions, and removing empty productions.
///
/// Chomsky normal form is required for some parsers (like the CYK parser) to work.
///
/// In chomsky normal form, all productions must have the following form:
///
/// A -> B C
/// D -> x
/// Start -> empty
///
/// Note that empty productions are only allowed starting from the start non-terminal
///
/// - Returns: Chomsky normal form of the current grammar
public func chomskyNormalized() -> Grammar {
// Generate weak Chomsky Normal Form by eliminating all productions generating a pattern of nonTerminals mixed with terminals
let nonMixedProductions = Grammar.eliminateMixedProductions(productions: productions)
// Decompose all productions with three or more nonTerminals
let decomposedProductions = Grammar.decomposeProductions(productions: nonMixedProductions)
// Remove empty productions
let nonEmptyProductions = Grammar.eliminateEmpty(productions: decomposedProductions, start: start)
// Remove chains
let nonChainedProductions = Grammar.eliminateChainProductions(productions: nonEmptyProductions)
// Remove duplicates
let uniqueProductions = nonChainedProductions.uniqueElements().collect(Array.init)
// Remove unreachable productions
let reachableProductions = Grammar.eliminateUnusedProductions(productions: uniqueProductions, start: start)
//let reachableProductions = uniqueProductions
let initialNonTerminals = productions.flatMap{[$0.pattern] + $0.generatedNonTerminals}.collect(Set.init)
let generatedNonTerminals = reachableProductions.flatMap{[$0.pattern] + $0.generatedNonTerminals}.collect(Set.init)
let newNonTerminals = generatedNonTerminals.subtracting(initialNonTerminals)
return Grammar(productions: reachableProductions, start: start, utilityNonTerminals: self.utilityNonTerminals.union(newNonTerminals))
}
}
| mit | a0bccac19e88fcac043d7711b56ab227 | 41.163498 | 166 | 0.727568 | 4.025045 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/helper/Categories/UIView+BearingRotation.swift | 1 | 698 | //
// UIView+BearingRotation.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 11/5/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
extension UIView {
func update(magneticHeading: CGFloat, bearing: CGFloat) {
rotate(bearing: bearing - magneticHeading)
}
func rotate(bearing: CGFloat) {
let rotation = Self.rotating(from: bearing)
transform = CGAffineTransform(rotationAngle: rotation)
}
private static func rotating(from bearing: CGFloat) -> CGFloat {
// 0 = North, 90 = East, 180 = South and 270 = West
let start: CGFloat = 90
let rotation = -1 * (start - bearing)
return (rotation * CGFloat.pi) / 180
}
}
| apache-2.0 | 454fc64a46acbf28cfc7380e0cf6a353 | 24.777778 | 66 | 0.672414 | 3.824176 | false | false | false | false |
apple/swift-syntax | Sources/SwiftOperators/PrecedenceGroup.swift | 1 | 4455 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SwiftSyntax
/// Names a precedence group.
///
/// TODO: For now, we'll use strings, but we likely want to move this to
/// a general notion of an Identifier.
public typealias PrecedenceGroupName = String
/// The associativity of a precedence group.
public enum Associativity: String {
/// The precedence group is nonassociative, meaning that one must
/// parenthesize when there are multiple operators in a sequence, e.g.,
/// if ^ was nonassociative, a ^ b ^ c would need to be disambiguated as
/// either (a ^ b ) ^ c or a ^ (b ^ c).
case none
/// The precedence group is left-associative, meaning that multiple operators
/// in the same sequence will be parenthesized from the left. This is typical
/// for arithmetic operators, such that a + b - c is treated as (a + b) - c.
case left
/// The precedence group is right-associative, meaning that multiple operators
/// in the same sequence will be parenthesized from the right. This is used
/// for assignments, where a = b = c is treated as a = (b = c).
case right
}
/// Describes the relationship of a precedence group to another precedence
/// group.
public struct PrecedenceRelation {
/// Describes the kind of a precedence relation.
public enum Kind {
case higherThan
case lowerThan
}
/// The relationship to the other group.
public var kind: Kind
/// The group name.
public var groupName: PrecedenceGroupName
/// The syntax that provides the relation. This specifically refers to the
/// group name itself, but one can follow the parent pointer to find its
/// position.
public var syntax: PrecedenceGroupNameElementSyntax?
/// Return a higher-than precedence relation.
public static func higherThan(
_ groupName: PrecedenceGroupName,
syntax: PrecedenceGroupNameElementSyntax? = nil
) -> PrecedenceRelation {
return .init(kind: .higherThan, groupName: groupName, syntax: syntax)
}
/// Return a lower-than precedence relation.
public static func lowerThan(
_ groupName: PrecedenceGroupName,
syntax: PrecedenceGroupNameElementSyntax? = nil
) -> PrecedenceRelation {
return .init(kind: .lowerThan, groupName: groupName, syntax: syntax)
}
}
/// Precedence groups are used for parsing sequences of expressions in Swift
/// source code. Each precedence group defines the associativity of the
/// operator and its precedence relative to other precedence groups:
///
/// precedencegroup MultiplicativePrecedence {
/// associativity: left
/// higherThan: AdditivePrecedence
/// }
///
/// Operator declarations then specify which precedence group describes their
/// precedence, e.g.,
///
/// infix operator *: MultiplicationPrecedence
public struct PrecedenceGroup {
/// The name of the group, which must be unique.
public var name: PrecedenceGroupName
/// The associativity for the group.
public var associativity: Associativity = .none
/// Whether the operators in this precedence group are considered to be
/// assignment operators.
public var assignment: Bool = false
/// The set of relations to other precedence groups that are defined by
/// this precedence group.
public var relations: [PrecedenceRelation] = []
/// The syntax node that describes this precedence group.
public var syntax: PrecedenceGroupDeclSyntax? = nil
public init(
name: PrecedenceGroupName,
associativity: Associativity = .none,
assignment: Bool = false,
relations: [PrecedenceRelation] = [],
syntax: PrecedenceGroupDeclSyntax? = nil
) {
self.name = name
self.associativity = associativity
self.assignment = assignment
self.relations = relations
self.syntax = syntax
}
}
extension PrecedenceGroup: CustomStringConvertible {
/// The description of a precedence group is the source code that produces it.
public var description: String {
(syntax ?? synthesizedSyntax()).description
}
}
| apache-2.0 | b4ffb2c966e46e0ee8e1fa44aa23b5a0 | 34.07874 | 80 | 0.695398 | 4.837134 | false | false | false | false |
Athlee/ATHKit | Examples/ATHImagePickerController/Storyboard/TestPicker/Pods/Material/Sources/iOS/Material+CALayer.swift | 2 | 10177 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
fileprivate struct MaterialLayer {
/// A reference to the CALayer.
fileprivate weak var layer: CALayer?
/// A property that sets the height of the layer's frame.
fileprivate var heightPreset = HeightPreset.default {
didSet {
layer?.height = CGFloat(heightPreset.rawValue)
}
}
/// A property that sets the cornerRadius of the backing layer.
fileprivate var cornerRadiusPreset = CornerRadiusPreset.none {
didSet {
layer?.cornerRadius = CornerRadiusPresetToValue(preset: cornerRadiusPreset)
}
}
/// A preset property to set the borderWidth.
fileprivate var borderWidthPreset = BorderWidthPreset.none {
didSet {
layer?.borderWidth = BorderWidthPresetToValue(preset: borderWidthPreset)
}
}
/// A preset property to set the shape.
fileprivate var shapePreset = ShapePreset.none
/// A preset value for Depth.
fileprivate var depthPreset: DepthPreset {
get {
return depth.preset
}
set(value) {
depth.preset = value
}
}
/// Grid reference.
fileprivate var depth = Depth.zero {
didSet {
guard let v = layer else {
return
}
v.shadowOffset = depth.offset.asSize
v.shadowOpacity = depth.opacity
v.shadowRadius = depth.radius
v.layoutShadowPath()
}
}
/// Enables automatic shadowPath sizing.
fileprivate var isShadowPathAutoSizing = false
/**
Initializer that takes in a CALayer.
- Parameter view: A CALayer reference.
*/
fileprivate init(layer: CALayer?) {
self.layer = layer
}
}
/// A memory reference to the MaterialLayer instance for CALayer extensions.
fileprivate var MaterialLayerKey: UInt8 = 0
/// Grid extension for UIView.
extension CALayer {
/// MaterialLayer Reference.
fileprivate var materialLayer: MaterialLayer {
get {
return AssociatedObject(base: self, key: &MaterialLayerKey) {
return MaterialLayer(layer: self)
}
}
set(value) {
AssociateObject(base: self, key: &MaterialLayerKey, value: value)
}
}
/// A property that accesses the frame.origin.x property.
@IBInspectable
open var x: CGFloat {
get {
return frame.origin.x
}
set(value) {
frame.origin.x = value
layoutShadowPath()
}
}
/// A property that accesses the frame.origin.y property.
@IBInspectable
open var y: CGFloat {
get {
return frame.origin.y
}
set(value) {
frame.origin.y = value
layoutShadowPath()
}
}
/// A property that accesses the frame.size.width property.
@IBInspectable
open var width: CGFloat {
get {
return frame.size.width
}
set(value) {
frame.size.width = value
if .none != shapePreset {
frame.size.height = value
layoutShape()
}
layoutShadowPath()
}
}
/// A property that accesses the frame.size.height property.
@IBInspectable
open var height: CGFloat {
get {
return frame.size.height
}
set(value) {
frame.size.height = value
if .none != shapePreset {
frame.size.width = value
layoutShape()
}
layoutShadowPath()
}
}
/// HeightPreset value.
open var heightPreset: HeightPreset {
get {
return materialLayer.heightPreset
}
set(value) {
materialLayer.heightPreset = value
}
}
/**
A property that manages the overall shape for the object. If either the
width or height property is set, the other will be automatically adjusted
to maintain the shape of the object.
*/
open var shapePreset: ShapePreset {
get {
return materialLayer.shapePreset
}
set(value) {
materialLayer.shapePreset = value
}
}
/// A preset value for Depth.
open var depthPreset: DepthPreset {
get {
return depth.preset
}
set(value) {
depth.preset = value
}
}
/// Grid reference.
open var depth: Depth {
get {
return materialLayer.depth
}
set(value) {
materialLayer.depth = value
}
}
/// Enables automatic shadowPath sizing.
@IBInspectable
open var isShadowPathAutoSizing: Bool {
get {
return materialLayer.isShadowPathAutoSizing
}
set(value) {
materialLayer.isShadowPathAutoSizing = value
}
}
/// A property that sets the cornerRadius of the backing layer.
open var cornerRadiusPreset: CornerRadiusPreset {
get {
return materialLayer.cornerRadiusPreset
}
set(value) {
materialLayer.cornerRadiusPreset = value
}
}
/// A preset property to set the borderWidth.
open var borderWidthPreset: BorderWidthPreset {
get {
return materialLayer.borderWidthPreset
}
set(value) {
materialLayer.borderWidthPreset = value
}
}
/**
A method that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
open func animate(animation: CAAnimation) {
animation.delegate = self
if let a = animation as? CABasicAnimation {
a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!)
}
if let a = animation as? CAPropertyAnimation {
add(a, forKey: a.keyPath!)
} else if let a = animation as? CAAnimationGroup {
add(a, forKey: nil)
} else if let a = animation as? CATransition {
add(a, forKey: kCATransition)
}
}
/**
A delegation method that is executed when the backing layer stops
running an animation.
- Parameter animation: The CAAnimation instance that stopped running.
- Parameter flag: A boolean that indicates if the animation stopped
because it was completed or interrupted. True if completed, false
if interrupted.
*/
open func animationDidStop(_ animation: CAAnimation, finished flag: Bool) {
guard let a = animation as? CAPropertyAnimation else {
if let a = (animation as? CAAnimationGroup)?.animations {
for x in a {
animationDidStop(x, finished: true)
}
}
return
}
guard let b = a as? CABasicAnimation else {
return
}
guard let v = b.toValue else {
return
}
guard let k = b.keyPath else {
return
}
setValue(v, forKeyPath: k)
removeAnimation(forKey: k)
}
/// Manages the layout for the shape of the view instance.
open func layoutShape() {
guard .none != shapePreset else {
return
}
if 0 == frame.width {
frame.size.width = frame.height
}
if 0 == frame.height {
frame.size.height = frame.width
}
guard .circle == shapePreset else {
return
}
cornerRadius = bounds.size.width / 2
}
/// Sets the shadow path.
open func layoutShadowPath() {
guard isShadowPathAutoSizing else {
return
}
if .none == depthPreset {
shadowPath = nil
} else if nil == shadowPath {
shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
} else {
let a = Motion.shadowPath(to: UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath)
a.fromValue = shadowPath
animate(animation: a)
}
}
}
@available(iOS 10, *)
extension CALayer: CAAnimationDelegate {}
| mit | 3482ea585da4b4da5600941f554bc3ad | 28.413295 | 111 | 0.582392 | 5.11407 | false | false | false | false |
ghodasara/ForecastIO | Tests/DataPointTests.swift | 3 | 1294 | //
// DataPointTests.swift
// ForecastIO
//
// Created by Satyam Ghodasara on 1/23/16.
//
//
import XCTest
@testable import ForecastIO
class DataPointTests: XCTestCase {
var dataPointJSONData: Data!
var decoder: JSONDecoder!
override func setUp() {
super.setUp()
// Load datapoint.json as Data
let dataPointJSONPath = Bundle(for: type(of: self)).path(forResource: "datapoint", ofType: "json")!
self.dataPointJSONData = try! Data(contentsOf: URL(fileURLWithPath: dataPointJSONPath))
// Setup the decoder
self.decoder = JSONDecoder()
self.decoder.dateDecodingStrategy = .secondsSince1970
}
override func tearDown() {
super.tearDown()
}
func testInitFromDecoder() {
// Given
// When
let dataPoint = try! decoder.decode(DataPoint.self, from: self.dataPointJSONData)
// Then
XCTAssertNotNil(dataPoint)
XCTAssertEqual(dataPoint.time, Date(timeIntervalSince1970: 1552546800))
XCTAssertEqual(dataPoint.summary, "Partly cloudy starting in the evening.")
XCTAssertEqual(dataPoint.icon, Icon.partlyCloudyNight)
XCTAssertEqual(dataPoint.precipitationType, Precipitation.rain)
}
}
| mit | 9cbfb0ee94580c6c38f3d164311d6737 | 26.531915 | 107 | 0.647604 | 4.621429 | false | true | false | false |
czechboy0/Buildasaur | BuildaGitServer/GitServerPublic.swift | 2 | 2118 | //
// GitSourcePublic.swift
// Buildasaur
//
// Created by Honza Dvorsky on 12/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
import Keys
import ReactiveCocoa
import Result
public enum GitService: String {
case GitHub = "github"
case BitBucket = "bitbucket"
// case GitLab = "gitlab"
public func prettyName() -> String {
switch self {
case .GitHub: return "GitHub"
case .BitBucket: return "BitBucket"
}
}
public func logoName() -> String {
switch self {
case .GitHub: return "github"
case .BitBucket: return "bitbucket"
}
}
public func hostname() -> String {
switch self {
case .GitHub: return "github.com"
case .BitBucket: return "bitbucket.org"
}
}
public func authorizeUrl() -> String {
switch self {
case .GitHub: return "https://github.com/login/oauth/authorize"
case .BitBucket: return "https://bitbucket.org/site/oauth2/authorize"
}
}
public func accessTokenUrl() -> String {
switch self {
case .GitHub: return "https://github.com/login/oauth/access_token"
case .BitBucket: return "https://bitbucket.org/site/oauth2/access_token"
}
}
public func serviceKey() -> String {
switch self {
case .GitHub: return BuildasaurKeys().gitHubAPIClientId()
case .BitBucket: return BuildasaurKeys().bitBucketAPIClientId()
}
}
public func serviceSecret() -> String {
switch self {
case .GitHub: return BuildasaurKeys().gitHubAPIClientSecret()
case .BitBucket: return BuildasaurKeys().bitBucketAPIClientSecret()
}
}
}
public class GitServer : HTTPServer {
let service: GitService
public func authChangedSignal() -> Signal<ProjectAuthenticator?, NoError> {
return Signal.never
}
init(service: GitService, http: HTTP? = nil) {
self.service = service
super.init(http: http)
}
}
| mit | ec907f7221f01e72d666599ae97c9d67 | 24.518072 | 80 | 0.606704 | 4.331288 | false | false | false | false |
jopamer/swift | test/decl/inherit/inherit.swift | 1 | 3013 | // RUN: %target-typecheck-verify-swift -swift-version 5
public class A { }
public protocol P { }
public protocol P1 { }
// Duplicate inheritance
class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}}
// Duplicate inheritance from protocol
class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}}
// FIXME: These are unnecessary
// expected-note@-2 {{'B2' declares conformance to protocol 'P' here}}
// expected-error@-3 {{redundant conformance of 'B2' to protocol 'P'}}
// Multiple inheritance
class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}}
// Superclass in the wrong position
class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }}
// SR-8160
class D1 : Any, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{15-18=}}{{12-12=A, }}
class D2 : P & P1, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{18-21=}}{{12-12=A, }}
@usableFromInline
class D3 : Any, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{15-18=}}{{12-12=A, }}
@usableFromInline
class D4 : P & P1, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{18-21=}}{{12-12=A, }}
// Struct inheriting a class
struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}}
// Protocol inheriting a class
protocol Q : A { }
// Extension inheriting a class
extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}}
// Keywords in inheritance clauses
struct S2 : struct { } // expected-error{{expected type}}
// Protocol composition in inheritance clauses
struct S3 : P, P & Q { } // expected-error {{redundant conformance of 'S3' to protocol 'P'}}
// expected-error @-1 {{non-class type 'S3' cannot conform to class protocol 'Q'}}
// expected-note @-2 {{'S3' declares conformance to protocol 'P' here}}
struct S4 : P, P { } // FIXME: expected-error {{duplicate inheritance from 'P'}}
// expected-error@-1{{redundant conformance of 'S4' to protocol 'P'}}
// expected-note@-2{{'S4' declares conformance to protocol 'P' here}}
struct S6 : P & { } // expected-error {{expected identifier for type name}}
struct S7 : protocol<P, Q> { } // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}}
// expected-error @-1 {{non-class type 'S7' cannot conform to class protocol 'Q'}}
class GenericBase<T> {}
class GenericSub<T> : GenericBase<T> {} // okay
class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}}
class InheritBody : T { // expected-error {{use of undeclared type 'T'}}
typealias T = A
}
class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}}
func fn() {}
}
| apache-2.0 | d7ebcc4bc4981dc02f379018478eaccb | 44.651515 | 135 | 0.655161 | 3.656553 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/TransactionAPI/TransactionProcessor/TransactionEngine/BitPayEngine/BitPayTransactionEngine.swift | 1 | 10316 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import MoneyKit
import PlatformKit
import RxSwift
import ToolKit
final class BitPayTransactionEngine: TransactionEngine {
var sourceAccount: BlockchainAccount!
var transactionTarget: TransactionTarget!
var askForRefreshConfirmation: AskForRefreshConfirmation!
let currencyConversionService: CurrencyConversionServiceAPI
let walletCurrencyService: FiatCurrencyServiceAPI
var fiatExchangeRatePairs: Observable<TransactionMoneyValuePairs> {
onChainEngine
.fiatExchangeRatePairs
}
// MARK: - Private Properties
/// This is due to the fact that the validation of the timeout occurs on completion of
/// the `Observable<Int>.interval` method from Rx, we kill the interval a second earlier so that we
/// validate the transaction/invoice on the correct beat.
private static let timeoutStop: TimeInterval = 1
private let onChainEngine: OnChainTransactionEngine
private let bitpayRepository: BitPayRepositoryAPI
private let analyticsRecorder: AnalyticsEventRecorderAPI
private var bitpayInvoice: BitPayInvoiceTarget {
transactionTarget as! BitPayInvoiceTarget
}
private var bitpayClientEngine: BitPayClientEngine {
onChainEngine as! BitPayClientEngine
}
private var timeRemainingSeconds: TimeInterval {
bitpayInvoice
.expirationTimeInSeconds
}
private let stopCountdown = PublishSubject<Void>()
init(
onChainEngine: OnChainTransactionEngine,
bitpayRepository: BitPayRepositoryAPI = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
currencyConversionService: CurrencyConversionServiceAPI = resolve(),
walletCurrencyService: FiatCurrencyServiceAPI = resolve()
) {
self.onChainEngine = onChainEngine
self.bitpayRepository = bitpayRepository
self.analyticsRecorder = analyticsRecorder
self.currencyConversionService = currencyConversionService
self.walletCurrencyService = walletCurrencyService
}
func start(
sourceAccount: BlockchainAccount,
transactionTarget: TransactionTarget,
askForRefreshConfirmation: @escaping AskForRefreshConfirmation
) {
self.sourceAccount = sourceAccount
self.transactionTarget = transactionTarget
self.askForRefreshConfirmation = askForRefreshConfirmation
onChainEngine.start(
sourceAccount: sourceAccount,
transactionTarget: transactionTarget,
askForRefreshConfirmation: askForRefreshConfirmation
)
}
func assertInputsValid() {
precondition(sourceAccount is CryptoNonCustodialAccount)
precondition(sourceCryptoCurrency == .bitcoin)
precondition(transactionTarget is BitPayInvoiceTarget)
precondition(onChainEngine is BitPayClientEngine)
onChainEngine.assertInputsValid()
}
func initializeTransaction() -> Single<PendingTransaction> {
onChainEngine
.initializeTransaction()
.map(weak: self) { (self, pendingTransaction) in
pendingTransaction
.update(availableFeeLevels: [.priority])
.update(selectedFeeLevel: .priority)
.update(amount: self.bitpayInvoice.amount.moneyValue)
}
}
func doBuildConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
onChainEngine
.update(
amount: bitpayInvoice.amount.moneyValue,
pendingTransaction: pendingTransaction
)
.flatMap(weak: self) { (self, pendingTransaction) in
self.onChainEngine
.doBuildConfirmations(pendingTransaction: pendingTransaction)
}
.map(weak: self) { (self, pendingTransaction) in
self.startTimeIfNotStarted(pendingTransaction)
}
.map(weak: self) { (self, pendingTransaction) in
pendingTransaction
.insert(
confirmation: TransactionConfirmations.BitPayCountdown(
secondsRemaining: self.timeRemainingSeconds
),
prepend: true
)
}
}
func doRefreshConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
.just(
pendingTransaction
.insert(
confirmation: TransactionConfirmations.BitPayCountdown(secondsRemaining: timeRemainingSeconds),
prepend: true
)
)
}
func update(amount: MoneyValue, pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
/// Don't set the amount here.
/// It is fixed so we can do it in the confirmation building step
.just(pendingTransaction)
}
func validateAmount(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
onChainEngine
.validateAmount(pendingTransaction: pendingTransaction)
}
func doValidateAll(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
doValidateTimeout(pendingTransaction: pendingTransaction)
.flatMap(weak: self) { (self, pendingTx) -> Single<PendingTransaction> in
self.onChainEngine.doValidateAll(pendingTransaction: pendingTx)
}
.updateTxValiditySingle(pendingTransaction: pendingTransaction)
}
func execute(pendingTransaction: PendingTransaction) -> Single<TransactionResult> {
bitpayClientEngine
.doPrepareBitPayTransaction(pendingTransaction: pendingTransaction)
.subscribe(on: MainScheduler.instance)
.flatMap(weak: self) { (self, transaction) -> Single<String> in
self.doExecuteTransaction(
invoiceId: self.bitpayInvoice.invoiceId,
transaction: transaction
)
}
.do(onSuccess: { [weak self] _ in
guard let self = self else { return }
// TICKET: IOS-4492 - Analytics
self.bitpayClientEngine.doOnBitPayTransactionSuccess(
pendingTransaction: pendingTransaction
)
}, onError: { [weak self] error in
guard let self = self else { return }
// TICKET: IOS-4492 - Analytics
self.bitpayClientEngine.doOnBitPayTransactionFailed(
pendingTransaction: pendingTransaction,
error: error
)
}, onSubscribe: { [weak self] in
guard let self = self else { return }
self.stopCountdown.on(.next(()))
})
.map { TransactionResult.hashed(txHash: $0, amount: pendingTransaction.amount) }
}
func doUpdateFeeLevel(pendingTransaction: PendingTransaction, level: FeeLevel, customFeeAmount: MoneyValue) -> Single<PendingTransaction> {
.just(pendingTransaction)
}
// MARK: - Private Functions
private func doExecuteTransaction(invoiceId: String, transaction: EngineTransaction) -> Single<String> {
bitpayRepository
.verifySignedTransaction(
invoiceId: invoiceId,
currency: sourceCryptoCurrency,
transactionHex: transaction.txHash,
transactionSize: transaction.msgSize
)
.asObservable()
.ignoreElements()
.asCompletable()
.delay(.seconds(3), scheduler: MainScheduler.instance)
.andThen(
bitpayRepository
.submitBitPayPayment(
invoiceId: invoiceId,
currency: sourceCryptoCurrency,
transactionHex: transaction.txHash,
transactionSize: transaction.msgSize
)
.asObservable()
.asSingle()
)
.map(\.memo)
}
private func doValidateTimeout(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
Single.just(pendingTransaction)
.map(weak: self) { (self, pendingTx) in
guard self.timeRemainingSeconds > Self.timeoutStop else {
throw TransactionValidationFailure(state: .invoiceExpired)
}
return pendingTx
}
}
private func startTimeIfNotStarted(_ pendingTransaction: PendingTransaction) -> PendingTransaction {
guard pendingTransaction.bitpayTimer == nil else { return pendingTransaction }
var transaction = pendingTransaction
transaction.setCountdownTimer(timer: startCountdownTimer(timeRemaining: timeRemainingSeconds))
return transaction
}
private func startCountdownTimer(timeRemaining: TimeInterval) -> Disposable {
guard let remaining = Int(exactly: timeRemaining) else {
fatalError("Expected an Int value: \(timeRemaining)")
}
return Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.take(until: stopCountdown)
.map { remaining - $0 }
.do(onNext: { [weak self] _ in
guard let self = self else { return }
_ = self.askForRefreshConfirmation(false)
.subscribe()
})
.take(until: { $0 <= Int(Self.timeoutStop) }, behavior: .inclusive)
.do(onCompleted: { [weak self] in
guard let self = self else { return }
Logger.shared.debug("BitPay Invoice Countdown expired")
_ = self.askForRefreshConfirmation(true)
.subscribe()
})
.subscribe()
}
}
extension PendingTransaction {
fileprivate mutating func setCountdownTimer(timer: Disposable) {
engineState.mutate { $0[.bitpayTimer] = timer }
}
var bitpayTimer: Disposable? {
engineState.value[.bitpayTimer] as? Disposable
}
}
| lgpl-3.0 | 33d39e713b5a592914c5405d761a227d | 38.673077 | 143 | 0.630053 | 5.714681 | false | false | false | false |
Amnell/Kreds | Tests/KredsLibTests/KredsLibTests.swift | 1 | 7292 | import XCTest
@testable import KredsLib
class KredsLibTests: XCTestCase {
func testSwiftStructName() {
XCTAssertEqual("StructName".toSwiftStructName(), "StructName")
XCTAssertEqual("structName".toSwiftStructName(), "StructName")
XCTAssertEqual("struct Name".toSwiftStructName(), "StructName")
XCTAssertEqual("struCt Name".toSwiftStructName(), "StruCtName")
XCTAssertEqual("struCt_Name".toSwiftStructName(), "StruCt_Name")
}
func testSwiftPropertyName() {
XCTAssertEqual("VariableName".toSwiftVariableName(), "variableName")
XCTAssertEqual("variable name".toSwiftVariableName(), "variableName")
XCTAssertEqual("variaBle nAme".toSwiftVariableName(), "variaBleNAme")
XCTAssertEqual("Base URL_Prefix".toSwiftVariableName(), "baseURL_Prefix")
}
func testObjCConstName() {
XCTAssertEqual("StructName".toObjCConstName(), "kStructName")
XCTAssertEqual("structName".toObjCConstName(), "kStructName")
XCTAssertEqual("struct Name".toObjCConstName(), "kStructName")
XCTAssertEqual("struCt Name".toObjCConstName(), "kStruCtName")
XCTAssertEqual("struCt_Name".toObjCConstName(), "kStruCt_Name")
}
func testSwiftGroupGenerator() {
let properties = [
Property(name: "property1", value: "value1"),
Property(name: "property2", value: "value2"),
Property(name: "property3", value: "value3")
]
let group = Group(name: "Group Name", properties: properties)
let result = SwiftSourceGenerator.source(forGroup: group)
let expectedResult = """
struct GroupName {
static let property1 = \"value1\"
static let property2 = \"value2\"
static let property3 = \"value3\"
}
"""
XCTAssertEqual(result, expectedResult)
}
func testSwiftGroupArrayGenerator() {
let properties = [
Property(name: "property1", value: "value1"),
Property(name: "property2", value: "value2"),
Property(name: "property3", value: "value3")
]
let group = Group(name: "Group Name", properties: properties)
let result = SwiftSourceGenerator.source(forGroups: [group, group])
let expectedResult =
"""
struct Kreds {
struct GroupName {
static let property1 = "value1"
static let property2 = "value2"
static let property3 = "value3"
}
struct GroupName {
static let property1 = "value1"
static let property2 = "value2"
static let property3 = "value3"
}
}
"""
XCTAssertEqual(result, expectedResult)
}
func testObjectiveCGroupGenerator() {
let properties = [
Property(name: "property1", value: "value1"),
Property(name: "property2", value: "value2"),
Property(name: "property3", value: "value3")
]
let group = Group(name: "GroupName", properties: properties)
let result = ObjectiveCSourceGenerator.source(forGroup: group)
let expectedResult = """
// GroupName
NSString *const kGroupNameProperty1 = @\"value1\";
NSString *const kGroupNameProperty2 = @\"value2\";
NSString *const kGroupNameProperty3 = @\"value3\";
"""
XCTAssertEqual(result, expectedResult)
}
func testObjectiveCGroupArrayGenerator() {
let properties = [
Property(name: "property1", value: "value1"),
Property(name: "property2", value: "value2"),
Property(name: "property3", value: "value3")
]
let group = Group(name: "GroupName", properties: properties)
let result = ObjectiveCSourceGenerator.source(forGroups: [group, group])
let expectedResult =
"""
// GroupName
NSString *const kGroupNameProperty1 = @\"value1\";
NSString *const kGroupNameProperty2 = @\"value2\";
NSString *const kGroupNameProperty3 = @\"value3\";
// GroupName
NSString *const kGroupNameProperty1 = @\"value1\";
NSString *const kGroupNameProperty2 = @\"value2\";
NSString *const kGroupNameProperty3 = @\"value3\";
"""
XCTAssertEqual(result, expectedResult)
}
func testSwiftPropertyToString() {
let property = Property(name: "Property Name", value: "value")
let expected = "static let propertyName = \"value\""
let group = Group(name: "Bogus", properties: [])
XCTAssertEqual(expected, SwiftSourceGenerator.source(property: property, forGroup: group))
}
func testObjcPropertyToString() {
let group = Group(name: "GroupName", properties: [])
let property = Property(name: "Property Name", value: "value")
let expected = "NSString *const kGroupNamePropertyName = @\"value\";"
XCTAssertEqual(expected, ObjectiveCSourceGenerator.source(property: property, forGroup: group))
}
func testDictionaryToGroups() {
let sourceDict = [
"service1": [
"property1": "value1",
"property2": "value2",
"property3": "value3",
],
"service2": [
"property2-1": "value2-1",
"property2-2": "value2-2",
"property2-3": "value2-3",
]
]
let result = Group.array(fromDictionary: sourceDict)
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.first?.properties.count, 3)
}
func testUppercaseFirstLetter() {
XCTAssertEqual(String.uppercasedFirstLetter("thisIsASentence"), "ThisIsASentence")
XCTAssertEqual(String.uppercasedFirstLetter("thisIsASentence"), "ThisIsASentence")
XCTAssertEqual(String.uppercasedFirstLetter("1ThisIsASentence"), "1ThisIsASentence")
XCTAssertEqual(String.uppercasedFirstLetter("öThisIsASentence"), "ÖThisIsASentence")
}
func testLowercaseFirstLetter() {
XCTAssertEqual(String.lowercasingFirstLetter("ThisIsASentence"), "thisIsASentence")
XCTAssertEqual(String.lowercasingFirstLetter("ThisIsASentence"), "thisIsASentence")
XCTAssertEqual(String.lowercasingFirstLetter("1ThisIsASentence"), "1ThisIsASentence")
XCTAssertEqual(String.lowercasingFirstLetter("ÖThisIsASentence"), "öThisIsASentence")
}
static var allTests = [
("testSwiftStructName", testSwiftStructName),
("testSwiftPropertyName", testSwiftPropertyName),
("testObjCConstName", testObjCConstName),
("testSwiftGroupGenerator", testSwiftGroupGenerator),
("testSwiftPropertyToString", testSwiftPropertyToString),
("testObjcPropertyToString", testObjcPropertyToString),
("testObjectiveCGroupGenerator", testObjectiveCGroupGenerator),
("testLowercaseFirstLetter", testLowercaseFirstLetter),
("testUppercaseFirstLetter", testUppercaseFirstLetter)
]
}
| mit | fe00b12b878a3b2b81eda218e5557b95 | 40.885057 | 103 | 0.611828 | 4.717152 | false | true | false | false |
hejunbinlan/QueryKit | QueryKit/ObjectiveC/QKQuerySet.swift | 3 | 1080 | import Foundation
extension QuerySet {
public func asQKQuerySet() -> QKQuerySet {
let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)!
var nsrange:NSRange = NSMakeRange(NSNotFound, NSNotFound)
if let range = self.range {
nsrange = NSMakeRange(range.startIndex, range.endIndex - range.startIndex)
}
return QKQuerySet(managedObjectContext: context, entityDescription: entityDescription, predicate: predicate, sortDescriptors: sortDescriptors, range:nsrange)
}
}
extension QKQuerySet {
public func asQuerySet() -> QuerySet<NSManagedObject> {
var queryset = QuerySet<NSManagedObject>(managedObjectContext, entityDescription.name!)
if let sortDescriptors = sortDescriptors as? [NSSortDescriptor] {
queryset = queryset.orderBy(sortDescriptors)
}
if let predicate = predicate {
queryset = queryset.filter(predicate)
}
if range.location != NSNotFound {
queryset = queryset[range.location..<(range.location + range.length)]
}
return queryset
}
}
| bsd-2-clause | 7fb7b008f33c9eda51e937e7deb801be | 30.764706 | 161 | 0.736111 | 4.8 | false | false | false | false |
tensorflow/tensorflow-pywrap_saved_model | tensorflow/lite/swift/Tests/InterpreterTests.swift | 21 | 12288 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlowLite
class InterpreterTests: XCTestCase {
var interpreter: Interpreter!
override func setUp() {
super.setUp()
interpreter = try! Interpreter(modelPath: AddModel.path)
}
override func tearDown() {
interpreter = nil
super.tearDown()
}
func testInit_ValidModelPath() {
XCTAssertNoThrow(try Interpreter(modelPath: AddModel.path))
}
func testInit_InvalidModelPath_ThrowsFailedToLoadModel() {
XCTAssertThrowsError(try Interpreter(modelPath: "/invalid/path")) { error in
self.assertEqualErrors(actual: error, expected: .failedToLoadModel)
}
}
func testInitWithOptions() throws {
var options = Interpreter.Options()
options.threadCount = 2
let interpreter = try Interpreter(modelPath: AddQuantizedModel.path, options: options)
XCTAssertNotNil(interpreter.options)
XCTAssertNil(interpreter.delegates)
}
func testInputTensorCount() {
XCTAssertEqual(interpreter.inputTensorCount, AddModel.inputTensorCount)
}
func testOutputTensorCount() {
XCTAssertEqual(interpreter.outputTensorCount, AddModel.outputTensorCount)
}
func testInvoke() throws {
try interpreter.allocateTensors()
XCTAssertNoThrow(try interpreter.invoke())
}
func testInvoke_ThrowsAllocateTensorsRequired_ModelNotReady() {
XCTAssertThrowsError(try interpreter.invoke()) { error in
self.assertEqualErrors(actual: error, expected: .allocateTensorsRequired)
}
}
func testInputTensorAtIndex() throws {
try setUpAddModelInputTensor()
let inputTensor = try interpreter.input(at: AddModel.validIndex)
XCTAssertEqual(inputTensor, AddModel.inputTensor)
}
func testInputTensorAtIndex_QuantizedModel() throws {
interpreter = try Interpreter(modelPath: AddQuantizedModel.path)
try setUpAddQuantizedModelInputTensor()
let inputTensor = try interpreter.input(at: AddQuantizedModel.inputOutputIndex)
XCTAssertEqual(inputTensor, AddQuantizedModel.inputTensor)
}
func testInputTensorAtIndex_ThrowsInvalidIndex() throws {
try interpreter.allocateTensors()
XCTAssertThrowsError(try interpreter.input(at: AddModel.invalidIndex)) { error in
let maxIndex = AddModel.inputTensorCount - 1
self.assertEqualErrors(
actual: error,
expected: .invalidTensorIndex(index: AddModel.invalidIndex, maxIndex: maxIndex)
)
}
}
func testInputTensorAtIndex_ThrowsAllocateTensorsRequired() {
XCTAssertThrowsError(try interpreter.input(at: AddModel.validIndex)) { error in
self.assertEqualErrors(actual: error, expected: .allocateTensorsRequired)
}
}
func testOutputTensorAtIndex() throws {
try setUpAddModelInputTensor()
try interpreter.invoke()
let outputTensor = try interpreter.output(at: AddModel.validIndex)
XCTAssertEqual(outputTensor, AddModel.outputTensor)
let expectedResults = [Float32](unsafeData: outputTensor.data)
XCTAssertEqual(expectedResults, AddModel.results)
}
func testOutputTensorAtIndex_QuantizedModel() throws {
interpreter = try Interpreter(modelPath: AddQuantizedModel.path)
try setUpAddQuantizedModelInputTensor()
try interpreter.invoke()
let outputTensor = try interpreter.output(at: AddQuantizedModel.inputOutputIndex)
XCTAssertEqual(outputTensor, AddQuantizedModel.outputTensor)
let expectedResults = [UInt8](outputTensor.data)
XCTAssertEqual(expectedResults, AddQuantizedModel.results)
}
func testOutputTensorAtIndex_ThrowsInvalidIndex() throws {
try interpreter.allocateTensors()
try interpreter.invoke()
XCTAssertThrowsError(try interpreter.output(at: AddModel.invalidIndex)) { error in
let maxIndex = AddModel.outputTensorCount - 1
self.assertEqualErrors(
actual: error,
expected: .invalidTensorIndex(index: AddModel.invalidIndex, maxIndex: maxIndex)
)
}
}
func testOutputTensorAtIndex_ThrowsInvokeInterpreterRequired() {
XCTAssertThrowsError(try interpreter.output(at: AddModel.validIndex)) { error in
self.assertEqualErrors(actual: error, expected: .invokeInterpreterRequired)
}
}
func testResizeInputTensorAtIndexToShape() {
XCTAssertNoThrow(try interpreter.resizeInput(at: AddModel.validIndex, to: [2, 2, 3]))
XCTAssertNoThrow(try interpreter.allocateTensors())
}
func testResizeInputTensorAtIndexToShape_ThrowsInvalidIndex() {
XCTAssertThrowsError(
try interpreter.resizeInput(
at: AddModel.invalidIndex,
to: [2, 2, 3]
)
) { error in
let maxIndex = AddModel.inputTensorCount - 1
self.assertEqualErrors(
actual: error,
expected: .invalidTensorIndex(index: AddModel.invalidIndex, maxIndex: maxIndex)
)
}
}
func testCopyDataToInputTensorAtIndex() throws {
try interpreter.resizeInput(at: AddModel.validIndex, to: AddModel.shape)
try interpreter.allocateTensors()
let inputTensor = try interpreter.copy(AddModel.inputData, toInputAt: AddModel.validIndex)
XCTAssertEqual(inputTensor.data, AddModel.inputData)
}
func testCopyDataToInputTensorAtIndex_ThrowsInvalidIndex() {
XCTAssertThrowsError(
try interpreter.copy(
AddModel.inputData,
toInputAt: AddModel.invalidIndex
)
) { error in
let maxIndex = AddModel.inputTensorCount - 1
self.assertEqualErrors(
actual: error,
expected: .invalidTensorIndex(index: AddModel.invalidIndex, maxIndex: maxIndex)
)
}
}
func testCopyDataToInputTensorAtIndex_ThrowsInvalidDataCount() throws {
try interpreter.resizeInput(at: AddModel.validIndex, to: AddModel.shape)
try interpreter.allocateTensors()
let invalidData = Data(count: AddModel.dataCount - 1)
XCTAssertThrowsError(
try interpreter.copy(
invalidData,
toInputAt: AddModel.validIndex
)
) { error in
self.assertEqualErrors(
actual: error,
expected: .invalidTensorDataCount(provided: invalidData.count, required: AddModel.dataCount)
)
}
}
func testAllocateTensors() {
XCTAssertNoThrow(try interpreter.allocateTensors())
}
// MARK: - Private
private func setUpAddModelInputTensor() throws {
precondition(interpreter != nil)
try interpreter.resizeInput(at: AddModel.validIndex, to: AddModel.shape)
try interpreter.allocateTensors()
try interpreter.copy(AddModel.inputData, toInputAt: AddModel.validIndex)
}
private func setUpAddQuantizedModelInputTensor() throws {
precondition(interpreter != nil)
try interpreter.resizeInput(at: AddQuantizedModel.inputOutputIndex, to: AddQuantizedModel.shape)
try interpreter.allocateTensors()
try interpreter.copy(AddQuantizedModel.inputData, toInputAt: AddQuantizedModel.inputOutputIndex)
}
private func assertEqualErrors(actual: Error, expected: InterpreterError) {
guard let actual = actual as? InterpreterError else {
XCTFail("Actual error should be of type InterpreterError.")
return
}
XCTAssertEqual(actual, expected)
}
}
class InterpreterOptionsTests: XCTestCase {
func testInitWithDefaultValues() {
let options = Interpreter.Options()
XCTAssertNil(options.threadCount)
XCTAssertFalse(options.isXNNPackEnabled)
}
func testInitWithCustomValues() {
var options = Interpreter.Options()
options.threadCount = 2
XCTAssertEqual(options.threadCount, 2)
options.isXNNPackEnabled = false
XCTAssertFalse(options.isXNNPackEnabled)
options.isXNNPackEnabled = true
XCTAssertTrue(options.isXNNPackEnabled)
}
func testEquatable() {
var options1 = Interpreter.Options()
var options2 = Interpreter.Options()
XCTAssertEqual(options1, options2)
options1.threadCount = 2
options2.threadCount = 2
XCTAssertEqual(options1, options2)
options2.threadCount = 3
XCTAssertNotEqual(options1, options2)
options2.threadCount = 2
XCTAssertEqual(options1, options2)
options2.isXNNPackEnabled = true
XCTAssertNotEqual(options1, options2)
options1.isXNNPackEnabled = true
XCTAssertEqual(options1, options2)
}
}
// MARK: - Constants
/// Values for the `add.bin` model.
enum AddModel {
static let info = (name: "add", extension: "bin")
static let inputTensorCount = 1
static let outputTensorCount = 1
static let invalidIndex = 1
static let validIndex = 0
static let shape: Tensor.Shape = [2]
static let dataCount = inputData.count
static let inputData = Data(copyingBufferOf: [Float32(1.0), Float32(3.0)])
static let outputData = Data(copyingBufferOf: [Float32(3.0), Float32(9.0)])
static let results = [Float32(3.0), Float32(9.0)]
static let inputTensor = Tensor(
name: "input",
dataType: .float32,
shape: shape,
data: inputData
)
static let outputTensor = Tensor(
name: "output",
dataType: .float32,
shape: shape,
data: outputData
)
static var path: String = {
let bundle = Bundle(for: InterpreterTests.self)
guard let path = bundle.path(forResource: info.name, ofType: info.extension) else { return "" }
return path
}()
}
/// Values for the `add_quantized.bin` model.
enum AddQuantizedModel {
static let info = (name: "add_quantized", extension: "bin")
static let inputOutputIndex = 0
static let shape: Tensor.Shape = [2]
static let inputData = Data([1, 3])
static let outputData = Data([3, 9])
static let quantizationParameters = QuantizationParameters(scale: 0.003922, zeroPoint: 0)
static let results: [UInt8] = [3, 9]
static let inputTensor = Tensor(
name: "input",
dataType: .uInt8,
shape: shape,
data: inputData,
quantizationParameters: quantizationParameters
)
static let outputTensor = Tensor(
name: "output",
dataType: .uInt8,
shape: shape,
data: outputData,
quantizationParameters: quantizationParameters
)
static var path: String = {
let bundle = Bundle(for: InterpreterTests.self)
guard let path = bundle.path(forResource: info.name, ofType: info.extension) else { return "" }
return path
}()
}
// MARK: - Extensions
extension Array {
/// Creates a new array from the bytes of the given unsafe data.
///
/// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit
/// with no indirection or reference-counting operations; otherwise, copying the raw bytes in
/// the `unsafeData`'s buffer to a new array returns an unsafe copy.
/// - Note: Returns `nil` if `unsafeData.count` is not a multiple of
/// `MemoryLayout<Element>.stride`.
/// - Parameter unsafeData: The data containing the bytes to turn into an array.
init?(unsafeData: Data) {
guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil }
#if swift(>=5.0)
self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) }
#else
self = unsafeData.withUnsafeBytes {
.init(
UnsafeBufferPointer<Element>(
start: $0,
count: unsafeData.count / MemoryLayout<Element>.stride
))
}
#endif // swift(>=5.0)
}
}
extension Data {
/// Creates a new buffer by copying the buffer pointer of the given array.
///
/// - Warning: The given array's element type `T` must be trivial in that it can be copied bit
/// for bit with no indirection or reference-counting operations; otherwise, reinterpreting
/// data from the resulting buffer has undefined behavior.
/// - Parameter array: An array with elements of type `T`.
init<T>(copyingBufferOf array: [T]) {
self = array.withUnsafeBufferPointer(Data.init)
}
}
| apache-2.0 | fd8aa56a85855984ea836ed6b37038f0 | 31.768 | 100 | 0.719971 | 4.196721 | false | true | false | false |
Automattic/Automattic-Tracks-iOS | Sources/Remote Logging/Crash Logging/SentryEvent+Extensions.swift | 1 | 882 | import Sentry
extension Event {
static func from(
error: NSError,
level: SentryLevel = .error,
user: Sentry.User? = nil,
timestamp: Date = Date(),
extra: [String: Any] = [:]
) -> Event {
let event = Event(level: level)
let baseError: NSError = (error.userInfo[NSUnderlyingErrorKey] as? NSError) ?? error
event.message = SentryMessage(formatted: baseError.debugDescription)
/// The error code/domain can be used to reproduce the original error
var mutableExtra = extra
mutableExtra["error-code"] = error.code
mutableExtra["error-domain"] = error.domain
error.userInfo.forEach { key, value in
mutableExtra[key] = value
}
event.timestamp = timestamp
event.extra = mutableExtra
event.user = user
return event
}
}
| gpl-2.0 | 5d2fcb07cf0bddb32d7d9789df2a4ef1 | 28.4 | 92 | 0.602041 | 4.5 | false | false | false | false |
mattermost/mattermost-mobile | ios/NotificationService/NotificationService.swift | 1 | 3872 | import Gekidou
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
let preferences = Gekidou.Preferences.default
let fibonacciBackoffsInSeconds = [1.0, 2.0, 3.0, 5.0, 8.0]
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
var retryIndex = 0
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent,
let jsonData = try? JSONSerialization.data(withJSONObject: bestAttemptContent.userInfo),
let ackNotification = try? JSONDecoder().decode(AckNotification.self, from: jsonData) {
fetchReceipt(ackNotification)
} else {
contentHandler(request.content)
}
}
func processResponse(serverUrl: String, data: Data, bestAttemptContent: UNMutableNotificationContent, contentHandler: ((UNNotificationContent) -> Void)?) {
bestAttemptContent.userInfo["server_url"] = serverUrl
let json = try? JSONSerialization.jsonObject(with: data) as! [String: Any]
if let json = json {
if let message = json["message"] as? String {
bestAttemptContent.body = message
}
if let channelName = json["channel_name"] as? String {
bestAttemptContent.title = channelName
}
let userInfoKeys = ["channel_name", "team_id", "sender_id", "root_id", "override_username", "override_icon_url", "from_webhook", "message"]
for key in userInfoKeys {
if let value = json[key] as? String {
bestAttemptContent.userInfo[key] = value
}
}
}
if (preferences.object(forKey: "ApplicationIsForeground") as? String != "true") {
Network.default.fetchAndStoreDataForPushNotification(bestAttemptContent, withContentHandler: contentHandler)
} else if let contentHandler = contentHandler {
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
func fetchReceipt(_ ackNotification: AckNotification) -> Void {
if (self.retryIndex >= self.fibonacciBackoffsInSeconds.count) {
self.contentHandler?(self.bestAttemptContent!)
return
}
Network.default.postNotificationReceipt(ackNotification) { data, response, error in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
self.contentHandler?(self.bestAttemptContent!)
return
}
guard let data = data, error == nil else {
if (ackNotification.isIdLoaded) {
// Receipt retrieval failed. Kick off retries.
let backoffInSeconds = self.fibonacciBackoffsInSeconds[self.retryIndex]
DispatchQueue.main.asyncAfter(deadline: .now() + backoffInSeconds, execute: {
self.fetchReceipt(ackNotification)
})
self.retryIndex += 1
}
return
}
self.processResponse(serverUrl: ackNotification.serverUrl, data: data, bestAttemptContent: self.bestAttemptContent!, contentHandler: self.contentHandler)
}
}
}
extension Date {
var millisecondsSince1970: Int {
return Int((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds: Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
| apache-2.0 | 942190986b6c60e7427006eca3cc8c8c | 37.72 | 159 | 0.699897 | 4.945083 | false | false | false | false |
mpurland/Swiftz | SwiftzTests/FunctionSpec.swift | 2 | 6055 | //
// FunctionSpec.swift
// Swiftz
//
// Created by Robert Widmann on 6/26/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
class FunctionSpec : XCTestCase {
func testCategoryLaws() {
property("Function obeys the Category left identity law") <- forAll { (fa : ArrowOf<Int, Int>) in
return forAll { (x : Int) in
return (Function.arr(fa.getArrow) • Function<Int, Int>.id()).apply(x) == Function.arr(fa.getArrow).apply(x)
}
}
property("Function obeys the Category right identity law") <- forAll { (fa : ArrowOf<Int, Int>) in
return forAll { (x : Int) in
return (Function<Int, Int>.id() • Function.arr(fa.getArrow)).apply(x) == Function.arr(fa.getArrow).apply(x)
}
}
property("Function obeys the Category associativity law") <- forAll { (fa : ArrowOf<Int8, Int16>, ga : ArrowOf<Int16, Int32>, ha : ArrowOf<Int32, Int64>) in
return forAll { (x : Int8) in
let f = Function.arr(fa.getArrow)
let g = Function.arr(ga.getArrow)
let h = Function.arr(ha.getArrow)
return ((h • g) • f).apply(x) == (h • (g • f)).apply(x)
}
}
}
func testArrowLaws() {
func assoc<A, B, C>(t : ((A, B), C)) -> (A, (B, C)) {
return (t.0.0, (t.0.1, t.1))
}
property("identity") <- forAll { (x : Int8) in
let a = Function<Int8, Int8>.arr(identity)
return a.apply(x) == identity(x)
}
property("composition") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
return forAll { (x : Int8) in
let la = Function.arr(f.getArrow) >>> Function.arr(g.getArrow)
let ra = Function.arr(g.getArrow • f.getArrow)
return la.apply(x) == ra.apply(x)
}
}
property("first") <- forAll { (f : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow).first()
let ra = Function.arr(Function.arr(f.getArrow).first().apply)
return forAll { (x : Int8, y : Int8) in
return la.apply(x, y) == ra.apply(x, y)
}
}
property("first under composition") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow) >>> Function.arr(g.getArrow)
let ra = Function.arr(f.getArrow).first() >>> Function.arr(g.getArrow).first()
return forAll { (x : Int8, y : Int8) in
return la.first().apply(x, y) == ra.apply(x, y)
}
}
property("first") <- forAll { (f : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow).first() >>> Function.arr(fst)
let ra = Function<(Int8, Int8), Int8>.arr(fst) >>> Function.arr(f.getArrow)
return forAll { (x : Int8, y : Int8) in
return la.apply(x, y) == ra.apply(x, y)
}
}
property("split") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow).first() >>> (Function.arr(identity) *** Function.arr(g.getArrow))
let ra = (Function.arr(identity) *** Function.arr(g.getArrow)) >>> Function.arr(f.getArrow).first()
return forAll { (x : Int8, y : Int8) in
return la.apply(x, y) == ra.apply(x, y)
}
}
// property("") <- forAll { (f : ArrowOf<Int8, Int8>) in
// let la = Function<((Int8, Int8), Int8), (Int8, (Int8, Int8))>.arr(f.getArrow).first().first() >>> Function.arr(assoc)
// let im : Function<(Int8, Int8), (Int8, Int8)> = Function.arr(f.getArrow).first()
// let ra = Function<((Int8, Int8), Int8), (Int8, (Int8, Int8))>.arr(assoc) >>> im
// return forAll { (w : Int8, x : Int8, y : Int8, z : Int8) in
// let l = la.apply((w, x), (y, z))
// let r = ra.apply((w, x), (y, z))
// return true
// }
// }
}
func testArrowChoiceLaws() {
property("left") <- forAll { (f : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow).left()
let ra = Function.arr(Function.arr(f.getArrow).left().apply)
return forAll { (e : EitherOf<Int8, Int8>) in
return la.apply(e.getEither) == ra.apply(e.getEither)
}
}
property("composition") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
let la = Function.arr(g.getArrow • f.getArrow).left()
let ra = Function.arr(f.getArrow).left() >>> Function.arr(g.getArrow).left()
return forAll { (e : EitherOf<Int8, Int8>) in
return la.apply(e.getEither) == ra.apply(e.getEither)
}
}
property("left under composition") <- forAll { (f : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow) >>> Function.arr(Either<Int8, Int8>.Left)
let ra = Function.arr(Either<Int8, Int8>.Left) >>> Function.arr(f.getArrow).left()
return forAll { (x : Int8) in
return la.apply(x) == ra.apply(x)
}
}
property("choice") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
let la = Function.arr(f.getArrow).left() >>> (Function.arr(identity) +++ Function.arr(g.getArrow))
let ra = (Function.arr(identity) +++ Function.arr(g.getArrow)) >>> Function.arr(f.getArrow).left()
return forAll { (e : EitherOf<Int8, Int8>) in
return la.apply(e.getEither) == ra.apply(e.getEither)
}
}
func assocSum(e : Either<Either<Int8, Int8>, Int8>) -> Either<Int8, Either<Int8, Int8>> {
switch e {
case let .Left(.Left(x)):
return .Left(x)
case let .Left(.Right(y)):
return .Right(.Left(y))
case let .Right(z):
return .Right(.Right(z))
}
}
// property("") <- forAll { (f : ArrowOf<Int8, Int8>, g : ArrowOf<Int8, Int8>) in
// let la = Function.arr(f.getArrow).left().left() >>> Function.arr(assocSum)
// let ra = Function.arr(assocSum) >>> Function.arr(f.getArrow).left()
// return forAll { (e : EitherOf<Int8, Int8>) in
// return la.apply(e.getEither) == ra.apply(e.getEither)
// }
// }
}
func testArrowApplyLaws() {
property("app") <- forAll { (x : Int8, y : Int8) in
let app : Function<(Function<Int8, (Int8, Int8)>, Int8), (Int8, Int8)> = Function<Int8, (Int8, Int8)>.app()
let la = Function<Int8, Function<Int8, (Int8, Int8)>>.arr({ x in Function.arr({ y in (x, y) }) }).first() >>> app
return la.apply(x, y) == identity(x, y)
}
}
}
| bsd-3-clause | a62759e414898d1ed30884290ee236c8 | 36.503106 | 158 | 0.598046 | 2.781207 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift | 3 | 6148 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
struct Outer<First> {
let first: First
}
struct Inner<First> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// TODO: Once prespecialization is done for generic arguments which are
// themselves generic (Outer<Inner<Int>>, here), a direct reference to
// the prespecialized metadata should be emitted here.
// CHECK: call swiftcc void @"$s4main5OuterV5firstACyxGx_tcfC"(
// CHECK-SAME: %T4main5OuterV* noalias nocapture sret %13,
// CHECK-SAME: %swift.opaque* noalias nocapture %14,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5InnerVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Outer(first: Inner(first: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5InnerVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: to i8*
// CHECK-SAME: ),
// CHECK-SAME: [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5OuterVyAA5InnerVySiGGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.+}}$s4main5OuterVMn{{.+}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5InnerVMa"([[INT]] %0, %swift.type* [[TYPE:%[0-9]+]]) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* [[TYPE]] to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5InnerVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.+}}$s4main5InnerVMn{{.+}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | e3b53bfa9b836f795782fdfb09ddf6ef | 38.159236 | 157 | 0.557092 | 2.994642 | false | false | false | false |
Dekkoh/ElasticSearchQuery | ElasticSearchQuery/Classes/ElasticSearchQuery.swift | 1 | 15597 | import Foundation
import Alamofire
import ObjectMapper
public class ElasticSearchQuery {
static private var urlString : String = ""
static private var pageSize = 10000.0
static private var data: [[ElasticSearchData]] = []
static private func buildBody(sortingFeature: String,
orderType: String,
field: String,
startTimestamp: String,
endTimestamp: String) -> [String : Any] {
let startPosition = 0
let body : [String : Any] = [
"sort": [
[sortingFeature : ["order": orderType]]
],
"size": pageSize,
"from": startPosition,
"query": [
"filtered": [
"filter": [
"bool": [
"must": [[
"exists": [
"field": field
]
],
[
"range": [
"datetime_idx": [
"gte": startTimestamp,
"lte": endTimestamp
]
]
]]
]
]
]
]
]
return body
}
static private func buildRequest(body: Data) -> URLRequest {
var request = URLRequest(url: URL( string: urlString)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = body
return request
}
static private func dictToJSON(data: [String : Any]) -> Data {
let bodyJSON = try! JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: bodyJSON, encoding: String.Encoding.utf8.rawValue)
let jsonData = json!.data(using: String.Encoding.utf8.rawValue);
return jsonData!
}
static private func getDataSize(body: [String : Any],
callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void,
field: String,
sortingFeature: String,
firstDataTimestamp: String) {
var modifiedBody = body
modifiedBody["size"] = 0
let jsonBody = dictToJSON(data: modifiedBody)
let request = buildRequest(body: jsonBody)
Alamofire.request(request).responseJSON { (response) in
var totalPages: Int = 0
switch response.result {
case .success:
guard let result = response.result.value as? [String : Any] else {
print("Data Size Parsing Error")
return
}
guard let hits = result["hits"] as? [String : Any] else {
print("Data Size Parsing Error")
return
}
let total = hits["total"] as! Double
if (total == 0) {
totalPages = 0
} else {
totalPages = Int(ceil(total / self.pageSize))
}
break
case .failure(let error):
print("Get Data Size with error: \(error)")
break
}
makeAssynchronousRequest(body: body, pages: totalPages, callback: callback, field: field, sortingFeature: sortingFeature, firstDataTimestamp: firstDataTimestamp)
}
}
static private func makeAssynchronousRequest(body: [String : Any],
pages: Int,
callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void,
field: String,
sortingFeature: String,
firstDataTimestamp: String) {
self.data = []
let dispatchGroup = DispatchGroup()
for i in (0..<pages) {
dispatchGroup.enter()
var modifiedBody = body
modifiedBody["from"] = Int(pageSize) * (i)
let jsonBody = dictToJSON(data: modifiedBody)
let request = buildRequest(body: jsonBody)
Alamofire.request(request).responseJSON { (response) in
switch response.result {
case .success:
guard let result = response.result.value as? [String : Any] else {
print("Data Parsing Error")
return
}
guard let hits = result["hits"] as? [String : Any] else {
print("Data Parsing Error")
return
}
guard let source = hits["hits"] as? Array<[String : Any]> else {
print("Data Parsing Error")
return
}
self.data = Array<[ElasticSearchData]>()
self.data.append(Mapper<ElasticSearchData>().mapArray(JSONArray: source) as [ElasticSearchData]!)
dispatchGroup.leave()
break
case .failure(let error):
print("Request failed with error: \(error)")
dispatchGroup.leave()
return
}
}
}
DispatchQueue.global(qos: .background).async {
dispatchGroup.wait()
DispatchQueue.main.async {
self.data.sort(by: { (a, b) -> Bool in
if ((a[0].sourceData?.datetime_idx)! < (b[0].sourceData?.datetime_idx)!){
return true
}
return false
})
let reducedData = self.data.reduce([], +)
getFirstDataBeforeStart(rawData: reducedData, callback: callback, field: field, sortingFeature: sortingFeature, firstDataTimestamp: firstDataTimestamp)
}
}
}
static private func getFirstDataBeforeStart(rawData: [ElasticSearchData],
callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void,
field: String,
sortingFeature: String,
firstDataTimestamp: String) {
let orderType: String = "desc"
let startTimestamp: String = "0"
var modifiedBody = buildBody(sortingFeature: sortingFeature, orderType: orderType, field: field, startTimestamp: startTimestamp, endTimestamp: firstDataTimestamp)
modifiedBody["size"] = 1
let jsonBody = dictToJSON(data: modifiedBody)
let request = buildRequest(body: jsonBody)
Alamofire.request(request).responseJSON { (response) in
var firstData = ElasticSearchData()
switch response.result {
case .success:
guard let result = response.result.value as? [String : Any] else {
print("First Data Parsing Error")
return
}
guard let hits = result["hits"] as? [String : Any] else {
print("First Data Parsing Error")
return
}
guard let source = hits["hits"] as? Array<[String : Any]> else {
print("First Data Parsing Error")
return
}
firstData = Mapper<ElasticSearchData>().mapArray(JSONArray: source)[0]
// self.data = Array<[ElasticSearchData]>()
// self.data.append(Mapper<ElasticSearchData>().mapArray(JSONArray: source) as [ElasticSearchData]!)
break
case .failure(let error):
print("Request failed with error: \(error)")
return
}
extractData(rawData: rawData, firstData: firstData, callback: callback, field: field, sortingFeature: sortingFeature, firstDataTimestamp: firstDataTimestamp)
}
}
static private func extractData(rawData: [ElasticSearchData],
firstData: ElasticSearchData,
callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void,
field: String,
sortingFeature: String,
firstDataTimestamp: String) {
var average = 0
var maximum = Int.min
var minimum = Int.max
var dataArray: [Int] = []
var timestampArray: [Int] = []
var elemData = 0
var extractedFirstData = 0
for elem in rawData {
guard elem.sourceData != nil else {
break
}
switch field {
case "dust":
guard elem.sourceData?.dust != nil else {
break
}
elemData = (elem.sourceData?.dust!)!
break
case "temperature":
guard elem.sourceData?.temperature != nil else {
break
}
elemData = (elem.sourceData?.temperature!)!
break
case "humidity":
guard elem.sourceData?.humidity != nil else {
break
}
elemData = (elem.sourceData?.humidity!)!
break
case "methane":
guard elem.sourceData?.methane != nil else {
break
}
elemData = (elem.sourceData?.methane!)!
break
case "co":
guard elem.sourceData?.co != nil else {
break
}
elemData = (elem.sourceData?.co!)!
break
default:
break
}
average += elemData
if (maximum < elemData) {
maximum = elemData
}
if (minimum > elemData) {
minimum = elemData
}
dataArray.append(elemData)
timestampArray.append((elem.sourceData?.datetime_idx)!)
}
if (rawData.count == 0) {
average = 0
maximum = 0
minimum = 0
} else {
average /= rawData.count
}
switch field {
case "dust":
guard firstData.sourceData?.dust != nil else {
break
}
extractedFirstData = (firstData.sourceData?.dust)!
break
case "temperature":
guard firstData.sourceData?.temperature != nil else {
break
}
extractedFirstData = (firstData.sourceData?.temperature)!
break
case "humidity":
guard firstData.sourceData?.humidity != nil else {
break
}
extractedFirstData = (firstData.sourceData?.humidity)!
break
case "methane":
guard firstData.sourceData?.methane != nil else {
break
}
extractedFirstData = (firstData.sourceData?.methane)!
break
case "co":
guard firstData.sourceData?.co != nil else {
break
}
extractedFirstData = (firstData.sourceData?.co)!
break
default:
break
}
callback(average, maximum, minimum, dataArray, timestampArray, extractedFirstData)
}
static public func queryData(field: String = "dust", sortingFeature: String = "datetime_idx", orderType: String = "asc", startTimestamp: String = "1491004800000", endTimestamp: String = "1499177600000", callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let firstDataTimestamp = String(Int(startTimestamp)! - 1)
let body = buildBody(sortingFeature: sortingFeature, orderType: orderType, field: field, startTimestamp: startTimestamp, endTimestamp: endTimestamp)
getDataSize(body: body, callback: callback, field: field, sortingFeature: sortingFeature, firstDataTimestamp: firstDataTimestamp)
}
static public func getDust(from: String, to: String, callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let field = "dust"
let sortingFeature = "datetime_idx"
let orderType = "asc"
queryData(field: field, sortingFeature: sortingFeature, orderType: orderType, startTimestamp: from, endTimestamp: to, callback: callback)
}
static public func getHumidity(from: String, to: String, callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let field = "humidity"
let sortingFeature = "datetime_idx"
let orderType = "asc"
queryData(field: field, sortingFeature: sortingFeature, orderType: orderType, startTimestamp: from, endTimestamp: to, callback: callback)
}
static public func getTemperature(from: String, to: String, callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let field = "temperature"
let sortingFeature = "datetime_idx"
let orderType = "asc"
queryData(field: field, sortingFeature: sortingFeature, orderType: orderType, startTimestamp: from, endTimestamp: to, callback: callback)
}
static public func getMethane(from: String, to: String, callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let field = "methane"
let sortingFeature = "datetime_idx"
let orderType = "asc"
queryData(field: field, sortingFeature: sortingFeature, orderType: orderType, startTimestamp: from, endTimestamp: to, callback: callback)
}
static public func getCO(from: String, to: String, callback: @escaping (Int, Int, Int, [Int], [Int], Int) -> Void) {
let field = "co"
let sortingFeature = "datetime_idx"
let orderType = "asc"
queryData(field: field, sortingFeature: sortingFeature, orderType: orderType, startTimestamp: from, endTimestamp: to, callback: callback)
}
static public func setURL(url : String) -> Void {
self.urlString = url
}
}
| mit | f1a9e802c502ed3f270c40581567365f | 38.090226 | 272 | 0.472591 | 5.584318 | false | false | false | false |
dehli/TouchDraw | Sources/StrokeSettings.swift | 1 | 1885 | //
// StrokeSettings.swift
// TouchDraw
//
// Created by Christian Paul Dehli on 9/4/16.
//
import Foundation
import UIKit
/// Properties to describe a stroke (color, width)
open class StrokeSettings: NSObject {
/// Color of the brush
private static let defaultColor = CIColor(color: UIColor.black)
internal var color: CIColor?
/// Width of the brush
private static let defaultWidth = CGFloat(10.0)
internal var width: CGFloat
/// Default initializer
override public init() {
color = StrokeSettings.defaultColor
width = StrokeSettings.defaultWidth
super.init()
}
/// Initializes a StrokeSettings with another StrokeSettings object
public convenience init(_ settings: StrokeSettings) {
self.init()
self.color = settings.color
self.width = settings.width
}
/// Initializes a StrokeSettings with a color and width
public convenience init(color: CIColor?, width: CGFloat) {
self.init()
self.color = color
self.width = width
}
/// Used to decode a StrokeSettings with a decoder
required public convenience init?(coder aDecoder: NSCoder) {
let color = aDecoder.decodeObject(forKey: StrokeSettings.colorKey) as? CIColor
var width = aDecoder.decodeObject(forKey: StrokeSettings.widthKey) as? CGFloat
if width == nil {
width = StrokeSettings.defaultWidth
}
self.init(color: color, width: width!)
}
}
// MARK: - NSCoding
extension StrokeSettings: NSCoding {
internal static let colorKey = "color"
internal static let widthKey = "width"
/// Used to encode a StrokeSettings with a coder
open func encode(with aCoder: NSCoder) {
aCoder.encode(self.color, forKey: StrokeSettings.colorKey)
aCoder.encode(self.width, forKey: StrokeSettings.widthKey)
}
}
| mit | 6437c47a7a088c4dce1b586f25c2258c | 27.560606 | 86 | 0.669496 | 4.608802 | false | false | false | false |
AlbertMontserrat/AMGCalendarManager | AMGCalendarManager/Classes/AMGCalendarManager.swift | 1 | 11601 | //
// CalendarManager.swift
//
// Created by Albert Montserrat on 16/02/17.
// Copyright (c) 2015 Albert Montserrat. All rights reserved.
//
import EventKit
public class AMGCalendarManager{
public var eventStore = EKEventStore()
public var calendarName: String
public var calendar: EKCalendar? {
get {
return eventStore.calendars(for: .event).filter { (element) in
return element.title == calendarName
}.first
}
}
public static let shared = AMGCalendarManager()
public init(calendarName: String = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String){
self.calendarName = calendarName
}
//MARK: - Authorization
public func requestAuthorization(completion: @escaping (_ allowed:Bool) -> ()){
switch EKEventStore.authorizationStatus(for: EKEntityType.event) {
case .authorized:
if self.calendar == nil {
_ = self.createCalendar()
}
completion(true)
case .denied:
completion(false)
case .notDetermined:
var userAllowed = false
eventStore.requestAccess(to: .event, completion: { (allowed, error) -> Void in
userAllowed = !allowed
if userAllowed {
self.reset()
if self.calendar == nil {
_ = self.createCalendar()
}
completion(userAllowed)
} else {
completion(false)
}
})
default:
completion(false)
}
}
//MARK: - Calendar
public func addCalendar(commit: Bool = true, completion: ((_ error:NSError?) -> ())? = nil) {
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError())
return
}
let error = weakSelf.createCalendar(commit: commit)
completion?(error)
}
}
public func removeCalendar(commit: Bool = true, completion: ((_ error:NSError?)-> ())? = nil) {
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError())
return
}
if let cal = weakSelf.calendar, EKEventStore.authorizationStatus(for: EKEntityType.event) == .authorized {
do {
try weakSelf.eventStore.removeCalendar(cal, commit: true)
completion?(nil)
} catch let error as NSError {
completion?(error)
}
}
}
}
//MARK: - New and update events
public func createEvent(completion: ((_ event:EKEvent?) -> Void)?) {
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(nil)
return
}
if let c = weakSelf.calendar {
let event = EKEvent(eventStore: weakSelf.eventStore)
event.calendar = c
completion?(event)
return
}
completion?(nil)
}
}
public func saveEvent(event: EKEvent, span: EKSpan = .thisEvent, completion: ((_ error:NSError?) -> Void)? = nil) {
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError())
return
}
if !weakSelf.insertEvent(event: event, span: span) {
completion?(weakSelf.getGeneralError())
} else {
completion?(nil)
}
}
}
//MARK: - Remove events
public func removeEvent(eventId: String, completion: ((_ error:NSError?)-> ())? = nil) {
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError())
return
}
weakSelf.getEvent(eventId: eventId, completion: { (error, event) in
if let e = event {
if !weakSelf.deleteEvent(event: e) {
completion?(weakSelf.getGeneralError())
} else {
completion?(nil)
}
} else {
completion?(weakSelf.getGeneralError())
}
})
}
}
public func removeAllEvents(filter: ((EKEvent) -> Bool)? = nil, completion: ((_ error:NSError?) -> ())? = nil){
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError())
return
}
weakSelf.getAllEvents(completion: { (error, events) in
guard error == nil, let events = events else {
completion?(weakSelf.getGeneralError())
return
}
for event in events {
if let f = filter, !f(event) {
continue
}
_ = weakSelf.deleteEvent(event: event)
}
completion?(nil)
})
}
}
//MARK: - Get events
public func getAllEvents(completion: ((_ error:NSError?, _ events:[EKEvent]?)-> ())?){
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError(), nil)
return
}
guard let c = weakSelf.calendar else {
completion?(weakSelf.getGeneralError(),nil)
return
}
let range = 31536000 * 100 as TimeInterval /* 100 Years */
var startDate = Date(timeIntervalSince1970: -range)
let endDate = Date(timeIntervalSinceNow: range * 2) /* 200 Years */
let four_years = 31536000 * 4 as TimeInterval /* 4 Years */
var events = [EKEvent]()
while startDate < endDate {
var currentFinish = Date(timeInterval: four_years, since: startDate)
if currentFinish > endDate {
currentFinish = Date(timeInterval: 0, since: endDate)
}
let pred = weakSelf.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: [c])
events.append(contentsOf: weakSelf.eventStore.events(matching: pred))
startDate = Date(timeInterval: four_years + 1, since: startDate)
}
completion?(nil, events)
}
}
public func getEvents(startDate: Date, endDate: Date, completion: ((_ error:NSError?, _ events:[EKEvent]?)-> ())?){
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError(), nil)
return
}
if let c = weakSelf.calendar {
let pred = weakSelf.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: [c])
completion?(nil, weakSelf.eventStore.events(matching: pred))
} else {
completion?(weakSelf.getGeneralError(),nil)
}
}
}
public func getEvent(eventId: String, completion: ((_ error:NSError?, _ event:EKEvent?)-> ())?){
requestAuthorization() { [weak self] (allowed) in
guard let weakSelf = self else { return }
if !allowed {
completion?(weakSelf.getDeniedAccessToCalendarError(), nil)
return
}
let event = weakSelf.eventStore.event(withIdentifier: eventId)
completion?(nil,event)
}
}
//MARK: - Privates
private func createCalendar(commit: Bool = true, source: EKSource? = nil) -> NSError? {
let newCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
newCalendar.title = self.calendarName
// defaultCalendarForNewEvents will always return a writtable source, even when there is no iCloud support.
newCalendar.source = source ?? self.eventStore.defaultCalendarForNewEvents.source
do {
try self.eventStore.saveCalendar(newCalendar, commit: commit)
return nil
} catch let error as NSError {
if source != nil {
return error
} else {
for source in self.eventStore.sources {
if source.sourceType == .birthdays {
continue
}
let err = createCalendar(source: source)
if err == nil {
return nil
}
}
self.calendarName = self.eventStore.defaultCalendarForNewEvents.title
return error
}
}
}
private func insertEvent(event: EKEvent, span: EKSpan = .thisEvent, commit: Bool = true) -> Bool {
do {
try eventStore.save(event, span: .thisEvent, commit: commit)
return true
} catch {
return false
}
}
private func deleteEvent(event: EKEvent, commit: Bool = true) -> Bool {
do {
try eventStore.remove(event, span: .futureEvents, commit: commit)
return true
} catch {
return false
}
}
//MARK: - Generic
public func commit() -> Bool {
do {
try eventStore.commit()
return true
} catch {
return false
}
}
public func reset(){
eventStore.reset()
}
}
extension AMGCalendarManager {
fileprivate func getErrorForDomain(domain: String, description: String, reason: String, code: Int = 999) -> NSError {
let userInfo = [
NSLocalizedDescriptionKey: description,
NSLocalizedFailureReasonErrorKey: reason
]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
fileprivate func getGeneralError() -> NSError {
return getErrorForDomain(domain: "CalendarError", description: "Unknown Error", reason: "An unknown error ocurred while trying to sync your calendar. Syncing will be turned off.", code: 999)
}
fileprivate func getDeniedAccessToCalendarError() -> NSError {
return getErrorForDomain(domain: "CalendarAuthorization", description: "Calendar access was denied", reason: "To continue syncing your calendars re-enable Calendar access for Técnico Lisboa in Settings->Privacy->Calendars.", code: 987)
}
}
| mit | 7d4cf988f54e5e288aeceba92f4da3fd | 34.913313 | 243 | 0.523966 | 5.360444 | false | false | false | false |
qq565999484/RXSwiftDemo | SWIFT_RX_RAC_Demo/SWIFT_RX_RAC_Demo/ViewController.swift | 1 | 3022 | //
// ViewController.swift
// SWIFT_RX_RAC_Demo
//
// Created by chenyihang on 2017/5/27.
// Copyright © 2017年 chenyihang. All rights reserved.
//
import UIKit
import Foundation
import RxCocoa
import RxSwift
import RxDataSources
struct MySection {
var header: String
var items: [Item]
}
extension MySection: AnimatableSectionModelType
{
typealias Item = Int
var identity: String {
return header
}
init(original: MySection, items: [Item]) {
self = original
self.items = items
}
}
class ViewController: UIViewController {
@IBOutlet weak var rx_tableview: UITableView!
let disposeBag = DisposeBag()
let reuseIdentifier = "\(UITableViewCell.self)"
var dataSource: RxTableViewSectionedReloadDataSource<MySection>?
override func viewDidLoad() {
super.viewDidLoad()
rx_tableview.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
let dataSource = RxTableViewSectionedReloadDataSource<MySection>()
dataSource.configureCell = {
[unowned self] ds,tv,ip,model in
let cell = tv.dequeueReusableCell(withIdentifier: self.reuseIdentifier) ?? UITableViewCell(style: .default , reuseIdentifier: self.reuseIdentifier)
cell.textLabel?.text = "Item \(model)"
return cell;
}
// dataSource.titleForHeaderInSection = { ds,index in
// return ds.sectionModels[index].header
// }
let sections = [
MySection(header: "First Section",items: [1 , 2]),
MySection(header: "Second Section",items: [3 , 4])
]
Observable.just(sections)
.bind(to: rx_tableview.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
rx_tableview.rx.setDelegate(self).addDisposableTo(disposeBag)
self.dataSource = dataSource
Observable.of(
rx_tableview.rx.modelSelected(MySection.self)
)
.merge()
.subscribe(onNext: { item in
print("Let me guess, it's .... It's \(item), isn't it? Yeah, I've got it.")
})
.addDisposableTo(disposeBag)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : UITableViewDelegate
{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// guard let item = dataSource?[indexPath],
// let _ = dataSource?[indexPath.section]
// else {
// return 0.0;
// }
return CGFloat(40 + 1 )
}
}
| apache-2.0 | c84a2ee3cc5fc989ba3bbeb24699066f | 24.584746 | 159 | 0.581318 | 5.065436 | false | false | false | false |
jollyjoester/Schoo-iOS-App-Development-Basic | MyPlayground.playground/Contents.swift | 1 | 1530 | //: Playground - noun: a place where people can play
// コメント
/*
複数行コメント
*/
import UIKit
var str = "Hello, Swift"
str = "こんにちはSwift!"
//str = 1
var int = 1
int = 5
var stringValue : String = "String"
var intValue : Int = 1
var doubleValue : Double = 70.5
var boolValue : Bool = true // false
var strX = "Happy"
var strY = "Birthday"
var strZ = strX + strY
var intX = 100
var intY = 50
var intZ = intX + intY
var doubleX = 50.5
var doubleY = 2.2
var doubeZ = doubleX + doubleY
//var result1 = strX + intX
//var result2 = intX + doubleX
var result1 = strX + String(intX)
var result2 = Double(intX) + doubleX
var strToInt1 = Int("10")
var strToInt2 = Int("十")
//strToInt1 + 20
//strToInt1! + 20
//strToInt2! + 20
if let value1 = strToInt1 {
value1 + 20
} else {
print("value1がnilです")
}
if let value2 = strToInt2 {
value2 + 20
} else {
print("value2がnilです")
}
let score : Int = 85
//score = 100
if score >= 70 {
print("合格")
} else {
print("失格")
}
var label = ""
switch score {
case 50..<70 : // 50〜69まで
label = "可"
case 70..<90 : // 70〜89まで
label = "良"
case 90...100 : // 90〜100まで
label = "優"
default : // 上記以外
label = "不可"
}
print("あなたの点数は\(score)点、成績は\(label)です")
var count = 0
for i in 1...10 {
count += i
}
count = 0
for var i = 1; i <= 10; i++ {
count += i
}
func square(n : Int) -> Int {
return n * n
}
square(4)
square(8)
| mit | 5e4db00e0c3a515d6f1515ebd5fc7b3f | 12.960396 | 52 | 0.59078 | 2.478032 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_361_SellDirectFinalSNSShareController.swift | 1 | 7483 | //
// SLV_361_SellDirectFinalSNSShareController.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 13..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import SwifterSwift
import SnapKit
import RealmSwift
import MaterialKit
class SLV_361_SellDirectFinalSNSShareController: SLVBaseStatusHiddenController {
var tr_presentTransition: TRViewControllerTransitionDelegate?
@IBOutlet weak var snsTitleLabel: UILabel!
@IBOutlet weak var sellButton: UIButton!
@IBOutlet weak var wheelContainerView: UIView!
@IBOutlet weak var rotaryView: HCRotaryWheelView!
let images = [UIImage(named: "sell_share_blog.png"), UIImage(named: "sell_share_fb.png"), UIImage(named: "sell_share_insta.png"), UIImage(named: "sell_share_kakaost.png"), UIImage(named: "sell_share_tw.png")]
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabController.animationTabBarHidden(true)
tabController.hideFab()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.isNavigationBarHidden = false
self.navigationItem.hidesBackButton = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.cancelPreviousPerformRequests(withTarget: self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupNavigationButtons()
self.setupDataBinding()
// self.setupWheelVeiw()
self.setupRotaryView()
defer { self.settingKeypadLayout()}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
lazy var keypadLayout: NSLayoutConstraint? = {
let keyboard = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.bottomLayoutGuide, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0)
return keyboard
}()
// func setupWheelVeiw() {
// // Create circle
// let vFrame = self.wheelContainerView.bounds
// let myCircle = Circle(with: vFrame, numberOfSegments: 5, ringWidth: 51)
// myCircle.dataSource = self
// myCircle.delegate = self
//
// for (i, thumb) in (myCircle.thumbs.enumerated()) {
// let thumb = thumb as! CircleThumb
// thumb.iconView.isSelected = false
// thumb.iconView.isHidden = false
// thumb.separatorStyle = .none
// thumb.isGradientFill = false
// thumb.arcColor = UIColor.clear
//
// // Add circular border to icon
// thumb.iconView.layer.borderWidth = 0
// thumb.iconView.layer.masksToBounds = false
// thumb.iconView.layer.borderColor = UIColor.white.cgColor
// thumb.iconView.layer.cornerRadius = thumb.iconView.frame.height/2
// thumb.iconView.layer.backgroundColor = UIColor.clear.cgColor
// thumb.iconView.clipsToBounds = true
//
// thumb.iconView.tag = 20 + i
// }
//
// // Add to view
// self.wheelContainerView.addSubview(myCircle)
// }
func setupRotaryView() {
self.rotaryView.delegate = self
}
func settingKeypadLayout() {
let layout = self.keypadLayout!
self.view.addConstraint(layout)
}
func clearKeypadLayout() {
self.view.removeConstraint(self.keypadLayout!)
}
func setupNavigationButtons() {
// let back = UIButton()
// back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal)
// back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20)
// back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
// back.addTarget(self, action: #selector(SLV_320_SellDirectStep2ItemInfoController.back(sender:)), for: .touchUpInside)
// let item = UIBarButtonItem(customView: back)
// self.navigationItem.leftBarButtonItem = item
let newDoneButton = UIBarButtonItem(title: "확인", style: UIBarButtonItemStyle.done, target: self, action: #selector(SLV_361_SellDirectFinalSNSShareController.next(sender:)))
self.navigationItem.rightBarButtonItem = newDoneButton
}
//MARK: Data binding
func setupDataBinding() {
}
//MARK: Animation
//MARK: Event
func back(sender: UIBarButtonItem?) {
_ = self.navigationController?.tr_popViewController()
}
func next(sender: UIBarButtonItem? = nil) {
log.debug("next(sender:)")
self.navigationController?.popToRootViewController(animated: false)
}
@IBAction func touchSellButton(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: false)
}
func moveFinalStep() {
// let board = UIStoryboard(name:"Sell", bundle: nil)
// let navigationController = board.instantiateViewController(withIdentifier: "priceNavigationController") as! UINavigationController
// let controller = navigationController.viewControllers.first as! SLV_341_SellStep4PriceDetailController
// controller.modalDelegate = self
// self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.fade) {
// print("Present finished.")
// }
}
}
extension SLV_361_SellDirectFinalSNSShareController: ModalTransitionDelegate {
func modalViewControllerDismiss(callbackData data:AnyObject?) {
log.debug("SLV_361_SellDirectFinalSNSShareController.modalViewControllerDismiss(callbackData:)")
tr_dismissViewController(completion: {
if let back = data {
let cb = back as! [String: String]
let keys = cb.keys
if keys.contains("command") == true {
let key = cb["command"]
if key != nil {
}
}
}
})
}
}
extension SLV_361_SellDirectFinalSNSShareController: RotaryProtocol {
func wheelDidChangeValue(_ currentSector: Int32) {
log.debug("\(currentSector)")
switch currentSector {
case 0://naver blog
break
case 1://facebook
break
case 2://instagram
break
case 3://kakaostory
break
case 4://twitter
break
default:
break
}
}
}
//extension SLV_361_SellDirectFinalSNSShareController: CircleDelegate, CircleDataSource {
//
// func circle(_ circle: Circle, didMoveTo segment: Int, thumb: CircleThumb) {
//
// }
//
// func circle(_ circle: Circle, iconForThumbAt row: Int) -> UIImage {
// let image = self.images[row]
// return image!
// }
//
//}
//
//
//extension UIView {
//
// var height:CGFloat {
// get {
// return self.frame.size.height
// }
// set {
// self.frame.size.height = newValue
// }
// }
//
// var width:CGFloat {
// get {
// return self.frame.size.width
// }
// set {
// self.frame.size.width = newValue
// }
// }
//
//}
| mit | 4a7d55458cb73848b0484541f6c2c695 | 31.620087 | 228 | 0.618072 | 4.446429 | false | false | false | false |
Watson1978/kotori | kotori/Document.swift | 1 | 1517 | import Cocoa
import WebKit
class Document: NSDocument {
override class var autosavesInPlace: Bool {
return false
}
override var isDocumentEdited: Bool {
return false
}
func makeWindowControllersOnly() {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
self.addWindowController(windowController)
}
func makeWindowControllers(withURLString urlString: String) {
makeWindowControllersOnly()
if let viewController = windowControllers.first?.contentViewController as? ViewController {
viewController.load(withURLString: urlString)
}
}
override func makeWindowControllers() {
let urlString = getStartPage()
makeWindowControllers(withURLString: urlString)
}
func makeWindowControllers(withPageName page: String) {
let urlString = getStartPage() + page
makeWindowControllers(withURLString: urlString)
}
func setTabbingMode() {
if #available(macOS 10.12, *) {
windowControllers.first?.window?.tabbingMode = .preferred
}
}
// MARK: Private
private func getStartPage() -> String {
var urlString = UserDefaults.standard.string(forKey: "startPage") ?? "https://esa.io/"
if !urlString.hasSuffix("/") {
urlString += "/"
}
return urlString
}
}
| mit | 46baa21677dfbc733f36a679502bde91 | 28.745098 | 132 | 0.659196 | 5.341549 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/WMFWelcomeExplorationAnimationView.swift | 1 | 3060 | import Foundation
open class WMFWelcomeExplorationAnimationView : WMFWelcomeAnimationView {
lazy var tubeImgView: UIImageView = {
let imgView = UIImageView(frame: bounds)
imgView.image = UIImage(named: "ftux-telescope-tube")
imgView.contentMode = UIView.ContentMode.scaleAspectFit
imgView.layer.zPosition = 102
// Adjust tubeImgView anchorPoint so rotation happens at that point (at hinge)
let anchorPoint = CGPoint(x: 0.50333, y: 0.64)
imgView.layer.anchorPoint = anchorPoint
imgView.layer.position = anchorPoint.wmf_denormalizeUsingSize(imgView.frame.size)
imgView.layer.transform = wmf_lowerTransform
imgView.layer.opacity = 0
return imgView
}()
lazy var baseImgView: UIImageView = {
let imgView = UIImageView(frame: bounds)
imgView.image = UIImage(named: "ftux-telescope-base")
imgView.contentMode = UIView.ContentMode.scaleAspectFit
imgView.layer.zPosition = 101
imgView.layer.transform = wmf_lowerTransform
imgView.layer.opacity = 0
return imgView
}()
override open func addAnimationElementsScaledToCurrentFrameSize() {
super.addAnimationElementsScaledToCurrentFrameSize()
removeExistingSubviewsAndSublayers()
addSubview(baseImgView)
addSubview(tubeImgView)
/*
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(_:))))
*/
}
/*
@objc func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
DDLogDebug("tubeImgView anchorPoint \(gestureRecognizer.location(in: self).wmf_normalizeUsingSize(frame.size))")
}
*/
override open func beginAnimations() {
super.beginAnimations()
CATransaction.begin()
let tubeOvershootRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(15.0)
let tubeFinalRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(-2.0)
baseImgView.layer.wmf_animateToOpacity(
1.0,
transform: CATransform3DIdentity,
delay: 0.1,
duration: 0.9
)
tubeImgView.layer.wmf_animateToOpacity(
1.0,
transform: CATransform3DIdentity,
delay: 0.1,
duration: 0.9
)
baseImgView.layer.wmf_animateToOpacity(
1.0,
transform: CATransform3DIdentity,
delay: 1.1,
duration: 0.9
)
tubeImgView.layer.wmf_animateToOpacity(
1.0,
transform: tubeOvershootRotationTransform,
delay: 1.1,
duration: 0.9
)
tubeImgView.layer.wmf_animateToOpacity(
1.0,
transform: tubeFinalRotationTransform,
delay: 2.1,
duration: 0.9
)
CATransaction.commit()
}
}
| mit | 661e457fd3c455f0e7882237aa53a2d2 | 32.26087 | 120 | 0.627778 | 4.97561 | false | false | false | false |
hollance/swift-algorithm-club | Simulated annealing/simann_example.swift | 2 | 5497 | // The MIT License (MIT)
// Copyright (c) 2017 Mike Taghavi (mitghi[at]me.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(OSX)
import Foundation
import Cocoa
#elseif os(Linux)
import Glibc
#endif
protocol Clonable {
init(current: Self)
}
extension Clonable {
func clone() -> Self {
return Self.init(current: self)
}
}
protocol SAObject: Clonable {
var count: Int { get }
func randSwap(a: Int, b: Int)
func currentEnergy() -> Double
func shuffle()
}
// MARK: - create a new copy of elements
extension Array where Element: Clonable {
func clone() -> Array {
var newArray = Array<Element>()
for elem in self {
newArray.append(elem.clone())
}
return newArray
}
}
typealias Points = [Point]
typealias AcceptanceFunc = (Double, Double, Double) -> Double
class Point: Clonable {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
required init(current: Point){
self.x = current.x
self.y = current.y
}
}
// MARK: - string representation
extension Point: CustomStringConvertible {
public var description: String {
return "Point(\(x), \(y))"
}
}
// MARK: - return distance between two points using operator '<->'
infix operator <->: AdditionPrecedence
extension Point {
static func <-> (left: Point, right: Point) -> Double {
let xDistance = (left.x - right.x)
let yDistance = (left.y - right.y)
return Double((xDistance * xDistance) + (yDistance * yDistance)).squareRoot()
}
}
class Tour: SAObject {
var tour: Points
var energy: Double = 0.0
var count: Int {
get {
return self.tour.count
}
}
init(points: Points){
self.tour = points.clone()
}
required init(current: Tour) {
self.tour = current.tour.clone()
}
}
// MARK: - calculate current tour distance ( energy ).
extension Tour {
func randSwap(a: Int, b: Int) -> Void {
let (cpos1, cpos2) = (self[a], self[b])
self[a] = cpos2
self[b] = cpos1
}
func currentEnergy() -> Double {
if self.energy == 0 {
var tourEnergy: Double = 0.0
for i in 0..<self.count {
let fromCity = self[i]
var destCity = self[0]
if i+1 < self.count {
destCity = self[i+1]
}
let e = fromCity<->destCity
tourEnergy = tourEnergy + e
}
self.energy = tourEnergy
}
return self.energy
}
func shuffle() {
self.tour.shuffle()
}
}
// MARK: - subscript to manipulate elements of Tour.
extension Tour {
subscript(index: Int) -> Point {
get {
return self.tour[index]
}
set(newValue) {
self.tour[index] = newValue
}
}
}
func SimulatedAnnealing<T: SAObject>(initial: T, temperature: Double, coolingRate: Double, acceptance: AcceptanceFunc) -> T {
var temp: Double = temperature
var currentSolution = initial.clone()
currentSolution.shuffle()
var bestSolution = currentSolution.clone()
print("Initial solution: ", bestSolution.currentEnergy())
while temp > 1 {
let newSolution: T = currentSolution.clone()
let pos1: Int = Int.random(in: 0 ..< newSolution.count)
let pos2: Int = Int.random(in: 0 ..< newSolution.count)
newSolution.randSwap(a: pos1, b: pos2)
let currentEnergy: Double = currentSolution.currentEnergy()
let newEnergy: Double = newSolution.currentEnergy()
if acceptance(currentEnergy, newEnergy, temp) > Double.random(in: 0 ..< 1) {
currentSolution = newSolution.clone()
}
if currentSolution.currentEnergy() < bestSolution.currentEnergy() {
bestSolution = currentSolution.clone()
}
temp *= 1-coolingRate
}
print("Best solution: ", bestSolution.currentEnergy())
return bestSolution
}
let points: [Point] = [
(60 , 200), (180, 200), (80 , 180), (140, 180),
(20 , 160), (100, 160), (200, 160), (140, 140),
(40 , 120), (100, 120), (180, 100), (60 , 80) ,
(120, 80) , (180, 60) , (20 , 40) , (100, 40) ,
(200, 40) , (20 , 20) , (60 , 20) , (160, 20) ,
].map{ Point(x: $0.0, y: $0.1) }
let acceptance : AcceptanceFunc = {
(e: Double, ne: Double, te: Double) -> Double in
if ne < e {
return 1.0
}
return exp((e - ne) / te)
}
let result: Tour = SimulatedAnnealing(initial : Tour(points: points),
temperature : 100000.0,
coolingRate : 0.003,
acceptance : acceptance)
| mit | fc0f5c535f387a81d05d5bf3ba102556 | 25.684466 | 125 | 0.6338 | 3.647644 | false | false | false | false |
luispadron/UICircularProgressRing | Example/UICircularProgressRingExample/SceneDelegate.swift | 1 | 2762 | //
// SceneDelegate.swift
// UICircularProgressRingExample
//
// Created by Luis on 5/29/20.
// Copyright © 2020 Luis. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = RingList()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| mit | 760b2c4c09ac4ee20bb7f763428a0471 | 42.140625 | 147 | 0.704455 | 5.340426 | false | false | false | false |
hollance/swift-algorithm-club | Sorted Set/SortedSet.playground/Sources/Random.swift | 3 | 654 | import Foundation
// Returns a random number between the given range.
public func random(min: Int, max: Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
// Generates a random alphanumeric string of a given length.
extension String {
public static func random(length: Int = 8) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
}
| mit | a90553e7901d48e7b1caba3659368f13 | 31.7 | 88 | 0.698777 | 4.192308 | false | false | false | false |
CartoDB/mobile-ios-samples | AdvancedMap.Objective-C/AdvancedMap/GalleryRow.swift | 1 | 3072 | //
// GalleryRow.swift
// Feature Demo
//
// Created by Aare Undo on 19/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
@objc class GalleryRow : UIView {
@objc var imageView: UIImageView!
@objc var titleView: UILabel!
@objc var descriptionView: UILabel!
@objc var sample: Sample!
convenience init() {
self.init(frame: CGRect.zero)
backgroundColor = UIColor.white
layer.borderWidth = 1;
layer.borderColor = Colors.nearWhite.cgColor
imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
addSubview(imageView)
titleView = UILabel()
titleView.textColor = Colors.appleBlue
titleView.font = UIFont(name: "HelveticaNeue-Bold", size: 14)
addSubview(titleView)
descriptionView = UILabel()
descriptionView.textColor = UIColor.lightGray
descriptionView.font = UIFont(name: "HelveticaNeue", size: 12)
descriptionView.lineBreakMode = .byWordWrapping
descriptionView.numberOfLines = 0
addSubview(descriptionView)
}
override func layoutSubviews() {
let padding: CGFloat = 5.0
let imageHeight = frame.height / 5 * 3
titleView.sizeToFit()
descriptionView.sizeToFit()
let titleHeight = titleView.frame.height
let descriptionHeight = descriptionView.frame.height
let x = padding
var y = padding
let w = frame.width - 2 * padding
var h = imageHeight
imageView.frame = CGRect(x: x, y: y, width: w, height: h)
y += h + padding;
h = titleHeight
titleView.frame = CGRect(x: x, y: y, width: w, height: h)
y += h + padding
h = descriptionHeight
descriptionView.frame = CGRect(x: x, y: y, width: w, height: h)
layer.masksToBounds = false
layer.shadowColor = UIColor.lightGray.cgColor
layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
layer.shadowOpacity = 0.5
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
alpha = 0.5
super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
alpha = 1.0
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
alpha = 1.0
super.touchesCancelled(touches, with: event)
}
@objc func update(sample: Sample) {
self.sample = sample
imageView.image = UIImage(named: sample.imageUrl)
titleView.text = sample.title
descriptionView.text = sample.subtitle
}
}
| bsd-2-clause | ad4142a791402010bef1e061812cf31f | 26.176991 | 83 | 0.585151 | 4.77605 | false | false | false | false |
nfls/nflsers | app/v2/Model/Resource/StsToken.swift | 1 | 754 | //
// StsToken.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 2018/8/13.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import ObjectMapper
class StsToken:ImmutableMappable {
let accessKeyId:String
let accessKeySecret:String
let securityToken:String
let expiration:Date
required init(map: Map) throws {
self.accessKeyId = try map.value("AccessKeyId")
self.accessKeySecret = try map.value("AccessKeySecret")
self.securityToken = try map.value("SecurityToken")
let exp:String = try map.value("Expiration")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
self.expiration = formatter.date(from: exp)!
}
}
| apache-2.0 | 60f94a1f8694f395e34447b031b51209 | 27.730769 | 63 | 0.676037 | 3.830769 | false | false | false | false |
hamilyjing/JJSwiftNetwork | Pods/JJSwiftTool/JJSwiftTool/Extension/UIColor+JJ.swift | 1 | 2285 | //
// UIColor+JJ.swift
// PANewToapAPP
//
// Created by jincieryi on 16/9/20.
// Copyright © 2016年 PingAn. All rights reserved.
//
import UIKit
extension UIColor {
fileprivate convenience init?(hex6: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat( (hex6 & 0xFF0000) >> 16 ) / 255.0,
green: CGFloat( (hex6 & 0x00FF00) >> 8 ) / 255.0,
blue: CGFloat( (hex6 & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(alpha))
}
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
self.init(red: r, green: g, blue: b, alpha: a)
}
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
public convenience init?(hex: Int, alpha: CGFloat = 1.0) {
if (0x000000 ... 0xFFFFFF) ~= hex {
self.init(hex6: hex , alpha: alpha)
} else {
return nil
}
}
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var formatted = hexString.replacingOccurrences(of: "0x", with: "")
formatted = formatted.replacingOccurrences(of: "#", with: "")
formatted = formatted.replacingOccurrences(of: " ", with: "")
guard let hexVal = Int(formatted, radix: 16) else {
return nil
}
switch formatted.characters.count {
case 6:
self.init(hex6: hexVal, alpha: alpha)
default:
return nil
}
}
public static func jjs_colorWithHex(hex: Int, alpha: CGFloat = 1.0) -> UIColor {
return UIColor(hex: hex, alpha: alpha)!
}
public static func jjs_colorWithHexString(hexString: String, alpha: CGFloat = 1.0) -> UIColor {
return UIColor(hexString: hexString, alpha: alpha)!
}
public static func jjs_arc4randomColor(_ randomAlpha: Bool = false) -> UIColor {
return UIColor(r: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), g: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), b: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), a: (randomAlpha ? (CGFloat(Float(arc4random()) / Float(UINT32_MAX))) : 1.0))
}
}
| mit | 1e3169bd5ae748e79b802f16bbdacb20 | 33.575758 | 258 | 0.578878 | 3.6512 | false | false | false | false |
dbahat/conventions-ios | Conventions/Conventions/gradient/GradientView.swift | 1 | 2140 | //
// GradientView.swift
// Conventions
//
// Created by David Bahat on 3/18/18.
// Copyright © 2018 Amai. All rights reserved.
//
import UIKit
@IBDesignable
class GradientView: UIButton {
@IBInspectable var FirstColor: UIColor = UIColor.clear {
didSet {
updateView()
}
}
@IBInspectable var SecondColor: UIColor = UIColor.clear {
didSet {
updateView()
}
}
@IBInspectable var ThirdColor: UIColor = UIColor.clear {
didSet {
updateView()
}
}
@IBInspectable var FirstTransition: Double = 0.5 {
didSet {
updateView()
}
}
@IBInspectable var SecondTransition: Double = 0 {
didSet {
updateView()
}
}
@IBInspectable var Angle: Float = 180 {
didSet {
updateView()
}
}
override class var layerClass: AnyClass {
get {
return CAGradientLayer.self
}
}
func updateView() {
let layer = self.layer as! CAGradientLayer
layer.colors = ThirdColor == UIColor.clear
? [ FirstColor.cgColor, SecondColor.cgColor ]
: [ FirstColor.cgColor, SecondColor.cgColor, ThirdColor.cgColor ]
layer.locations = SecondTransition == 0
? [ NSNumber(value: FirstTransition) ]
: [ NSNumber(value: FirstTransition), NSNumber(value: SecondTransition) ]
let alpha: Float = Angle / 360
let startPointX = powf(
sinf(2 * Float.pi * ((alpha + 0.75) / 2)),
2
)
let startPointY = powf(
sinf(2 * Float.pi * ((alpha + 0) / 2)),
2
)
let endPointX = powf(
sinf(2 * Float.pi * ((alpha + 0.25) / 2)),
2
)
let endPointY = powf(
sinf(2 * Float.pi * ((alpha + 0.5) / 2)),
2
)
layer.endPoint = CGPoint(x: CGFloat(endPointX),y: CGFloat(endPointY))
layer.startPoint = CGPoint(x: CGFloat(startPointX), y: CGFloat(startPointY))
}
}
| apache-2.0 | 3dcb08c2df0b7f376765f3aee461664b | 23.872093 | 85 | 0.518467 | 4.446985 | false | false | false | false |
little2s/NoChat | Example/Example/SimpleInputPanel.swift | 1 | 16391 | //
// SimpleInputPanel.swift
// NoChatExample
//
// Created by yinglun on 2020/8/15.
// Copyright © 2020 little2s. All rights reserved.
//
import UIKit
import NoChat
import HPGrowingTextView
class SimpleInputCoordinator {
enum InputStatus {
case idle
case text
}
private(set) var status: InputStatus = .idle
private weak var chatViewController: SimpleChatViewController?
private var inputPanel: SimpleInputPanel? {
chatViewController?.inputPanel as? SimpleInputPanel
}
init(chatViewController: SimpleChatViewController) {
self.chatViewController = chatViewController
self.inputPanel?.inputCoordinator = self
}
func transitionToInputStatus(_ newStatus: InputStatus) {
let oldStatus = self.status
self.status = newStatus
switch (oldStatus, newStatus) {
case (.idle, .text):
if inputPanel?.inputField.internalTextView.isFirstResponder == false {
inputPanel?.inputField.internalTextView.becomeFirstResponder()
}
case (.text, .idle):
if inputPanel?.inputField.internalTextView.isFirstResponder == true {
inputPanel?.inputField.internalTextView.resignFirstResponder()
}
default:
break
}
}
}
protocol SimpleInputPanelDelegate: InputPanelDelegate {
func didInputTextPanelStartInputting(_ inputTextPanel: SimpleInputPanel)
func inputTextPanel(_ inputTextPanel: SimpleInputPanel, requestSendText text: String)
}
class SimpleInputPanel: InputPanel, HPGrowingTextViewDelegate {
struct Layout {
static var rootWindowSafeAreaInsets: UIEdgeInsets {
guard let window = UIApplication.shared.delegate?.window.flatMap({ $0 }) else {
return .zero
}
return window.safeAreaInsets
}
static let safeAreaBottomHeight: CGFloat = rootWindowSafeAreaInsets.bottom
static let baseHeight: CGFloat = 45
static let inputFiledInsets = UIEdgeInsets(top: 5, left: 20, bottom: 4, right: 0)
static let inputFiledEdgeInsets = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 6)
static let inputFiledInternalEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
private class BackgroundView: UIView {
private let effectView = UIVisualEffectView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
effectView.effect = UIBlurEffect(style: .regular)
addSubview(effectView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
effectView.frame = bounds
}
}
private var sendButtonWidth = CGFloat(80)
var backgroundView: UIView!
var inputField: HPGrowingTextView!
var inputFiledClippingContainer: UIView!
var fieldBackground: UIView!
var sendButton: UIButton!
private var parentSize = CGSize.zero
private var messageAreaSize = CGSize.zero
private var keyboardHeight = CGFloat(0)
weak var inputCoordinator: SimpleInputCoordinator?
override init(frame: CGRect) {
backgroundView = BackgroundView()
backgroundView.clipsToBounds = true
fieldBackground = UIView()
fieldBackground.frame = CGRect(x: Layout.inputFiledInsets.left, y: Layout.inputFiledInsets.top, width: frame.width - Layout.inputFiledInsets.left - Layout.inputFiledInsets.right - sendButtonWidth - 1, height: frame.height - Layout.inputFiledInsets.top - Layout.inputFiledInsets.bottom)
fieldBackground.layer.borderWidth = 0.5
if #available(iOS 13.0, *) {
fieldBackground.layer.borderColor = UIColor.systemGray.cgColor
} else {
fieldBackground.layer.borderColor = #colorLiteral(red: 0.7019607843, green: 0.6666666667, blue: 0.6980392157, alpha: 1)
}
fieldBackground.layer.masksToBounds = true
fieldBackground.layer.cornerRadius = 18
fieldBackground.backgroundColor = UIColor.clear
inputFiledClippingContainer = UIView()
inputFiledClippingContainer.clipsToBounds = true
let inputFiledClippingFrame = fieldBackground.frame.inset(by: Layout.inputFiledEdgeInsets)
inputFiledClippingContainer.frame = inputFiledClippingFrame
inputField = HPGrowingTextView()
inputField.frame = CGRect(x: Layout.inputFiledInternalEdgeInsets.left, y: Layout.inputFiledInternalEdgeInsets.top, width: inputFiledClippingFrame.width - Layout.inputFiledInternalEdgeInsets.left, height: inputFiledClippingFrame.height)
inputField.animateHeightChange = false
inputField.animationDuration = 0
inputField.font = UIFont.systemFont(ofSize: 16, weight: .regular)
inputField.backgroundColor = UIColor.clear
inputField.isOpaque = false
inputField.clipsToBounds = true
inputField.internalTextView.backgroundColor = UIColor.clear
inputField.internalTextView.isOpaque = false
inputField.internalTextView.contentMode = .left
inputField.internalTextView.enablesReturnKeyAutomatically = true
inputField.internalTextView.scrollIndicatorInsets = UIEdgeInsets(top: -Layout.inputFiledInternalEdgeInsets.top, left: 0, bottom: 5-0.5, right: 0)
inputField.placeholder = "Message"
if #available(iOS 13.0, *) {
inputField.placeholderColor = UIColor.placeholderText
} else {
inputField.placeholderColor = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)
}
sendButton = UIButton(type: .system)
sendButton.isExclusiveTouch = true
sendButton.setTitle("Send", for: .normal)
sendButton.setTitleColor(UIColor(red: 0/255.0, green: 126/255.0, blue: 229/255.0, alpha: 1), for: .normal)
if #available(iOS 13, *) {
sendButton.setTitleColor(UIColor.placeholderText, for: .disabled)
} else {
sendButton.setTitleColor(UIColor(red: 142/255.0, green: 142/255.0, blue: 147/255.0, alpha: 1), for: .disabled)
}
sendButton.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
sendButton.isEnabled = false
super.init(frame: frame)
addSubview(backgroundView)
addSubview(fieldBackground)
addSubview(inputFiledClippingContainer)
addSubview(sendButton)
inputField.maxNumberOfLines = maxNumberOfLines(forSize: parentSize)
inputField.delegate = self
inputFiledClippingContainer.addSubview(inputField)
sendButton.addTarget(self, action: #selector(didTapSendButton), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var safeArea = UIEdgeInsets.zero
if let vc = delegate as? SimpleChatViewController {
safeArea = vc.safeAreaInsets
}
fieldBackground.frame = CGRect(x: Layout.inputFiledInsets.left + safeArea.left, y: Layout.inputFiledInsets.top, width: bounds.width - Layout.inputFiledInsets.left - Layout.inputFiledInsets.right - sendButtonWidth - 1 - safeArea.left - safeArea.right, height: bounds.height - Layout.inputFiledInsets.top - Layout.inputFiledInsets.bottom)
inputFiledClippingContainer.frame = fieldBackground.frame.inset(by: Layout.inputFiledEdgeInsets)
if let window = UIApplication.shared.delegate?.window {
let backgroundViewHeight = (window?.bounds.height ?? self.frame.minY) - self.frame.minY
backgroundView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: backgroundViewHeight)
}
sendButton.frame = CGRect(x: bounds.width - safeArea.right - sendButtonWidth, y: bounds.height - Layout.baseHeight, width: sendButtonWidth, height: Layout.baseHeight)
}
override func endInputting(animated: Bool) {
inputCoordinator?.transitionToInputStatus(.idle)
}
override func adjust(for size: CGSize, keyboardHeight: CGFloat, duration: TimeInterval, animationCurve: Int) {
let previousSize = parentSize
parentSize = size
if abs(size.width - previousSize.width) > .ulpOfOne {
change(to: size, keyboardHeight: keyboardHeight, duration: 0)
}
adjust(for: size, keyboardHeight: keyboardHeight, inputFiledHeight: inputField.frame.height, duration: duration, animationCurve: animationCurve)
}
override func change(to size: CGSize, keyboardHeight: CGFloat, duration: TimeInterval) {
parentSize = size
let messageAreaSize = size
self.messageAreaSize = messageAreaSize
self.keyboardHeight = keyboardHeight
var inputFieldSnapshotView: UIView?
if duration > .ulpOfOne {
inputFieldSnapshotView = inputField.internalTextView.snapshotView(afterScreenUpdates: false)
if let v = inputFieldSnapshotView {
v.frame = inputField.frame.offsetBy(dx: inputFiledClippingContainer.frame.origin.x, dy: inputFiledClippingContainer.frame.origin.y)
addSubview(v)
}
}
UIView.performWithoutAnimation {
self.updateInputFiledLayout()
}
let inputContainerHeight = heightForInputFiledHeight(inputField.frame.size.height)
var newInputContainerFrame: CGRect = .zero
if (abs(keyboardHeight) < .ulpOfOne) {
if let vc = self.delegate as? SimpleChatViewController {
newInputContainerFrame = CGRect(x: 0, y: messageAreaSize.height - vc.safeAreaInsets.bottom - keyboardHeight - inputContainerHeight, width: messageAreaSize.width, height: inputContainerHeight)
}
} else {
newInputContainerFrame = CGRect(x: 0, y: messageAreaSize.height - keyboardHeight - inputContainerHeight, width: messageAreaSize.width, height: inputContainerHeight)
}
if duration > .ulpOfOne {
if inputFieldSnapshotView != nil {
inputField.alpha = 0
}
UIView.animate(withDuration: duration, animations: {
self.frame = newInputContainerFrame
self.layoutSubviews()
if let v = inputFieldSnapshotView {
self.inputField.alpha = 1
v.frame = self.inputField.frame.offsetBy(dx: self.inputFiledClippingContainer.frame.origin.x, dy: self.inputFiledClippingContainer.frame.origin.y)
v.alpha = 0
}
}, completion: { (_) in
inputFieldSnapshotView?.removeFromSuperview()
})
} else {
frame = newInputContainerFrame
}
}
func clearInputField() {
inputField.internalTextView.text = nil
inputField.refreshHeight()
}
func growingTextView(_ growingTextView: HPGrowingTextView!, willChangeHeight height: Float) {
let inputContainerHeight = heightForInputFiledHeight(CGFloat(height))
var newInputContainerFrame: CGRect = .zero
if (abs(keyboardHeight) < .ulpOfOne) {
if let vc = self.delegate as? SimpleChatViewController {
newInputContainerFrame = CGRect(x: 0, y: messageAreaSize.height - vc.safeAreaInsets.bottom - keyboardHeight - inputContainerHeight, width: messageAreaSize.width, height: inputContainerHeight)
}
} else {
newInputContainerFrame = CGRect(x: 0, y: messageAreaSize.height - keyboardHeight - inputContainerHeight, width: messageAreaSize.width, height: inputContainerHeight)
}
UIView.animate(withDuration: 0.3) {
self.frame = newInputContainerFrame
self.layoutSubviews()
}
delegate?.inputPanel(self, willChange: inputContainerHeight, duration: 0.3, animationCurve: 0)
}
func growingTextViewShouldBeginEditing(_ growingTextView: HPGrowingTextView!) -> Bool {
inputCoordinator?.transitionToInputStatus(.text)
return true
}
func growingTextViewDidBeginEditing(_ growingTextView: HPGrowingTextView!) {
if let d = delegate as? SimpleInputPanelDelegate {
d.didInputTextPanelStartInputting(self)
}
}
private func adjust(for size: CGSize, keyboardHeight: CGFloat, inputFiledHeight: CGFloat, duration: TimeInterval, animationCurve: Int) {
let block = {
let messageAreaSize = size
self.messageAreaSize = messageAreaSize
self.keyboardHeight = keyboardHeight
let inputContainerHeight = self.heightForInputFiledHeight(inputFiledHeight)
if (abs(keyboardHeight) < .ulpOfOne) {
self.frame = CGRect(x: 0, y: messageAreaSize.height - Layout.safeAreaBottomHeight - keyboardHeight - inputContainerHeight, width: self.messageAreaSize.width, height: inputContainerHeight)
} else {
self.frame = CGRect(x: 0, y: messageAreaSize.height - keyboardHeight - inputContainerHeight, width: self.messageAreaSize.width, height: inputContainerHeight)
}
self.layoutSubviews()
}
if duration > .ulpOfOne {
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: UInt(animationCurve << 16)), animations: block, completion: nil)
} else {
block()
}
}
private func heightForInputFiledHeight(_ inputFiledHeight: CGFloat) -> CGFloat {
return max(Layout.baseHeight, inputFiledHeight + Layout.inputFiledInsets.top + Layout.inputFiledInsets.bottom)
}
private func updateInputFiledLayout() {
let range = inputField.internalTextView.selectedRange
inputField.delegate = nil
let inputFiledInsets = Layout.inputFiledInsets
let inputFiledInternalEdgeInsets = Layout.inputFiledInternalEdgeInsets
let inputFiledClippingFrame = CGRect(x: inputFiledInsets.left, y: inputFiledInsets.top, width: parentSize.width - inputFiledInsets.left - inputFiledInsets.right - sendButtonWidth - 1, height: 0)
let inputFieldFrame = CGRect(x: inputFiledInternalEdgeInsets.left, y: inputFiledInternalEdgeInsets.top, width: inputFiledClippingFrame.width - inputFiledInternalEdgeInsets.left, height: 0)
inputField.frame = inputFieldFrame
inputField.internalTextView.frame = CGRect(x: 0, y: 0, width: inputFieldFrame.width, height: inputFieldFrame.height)
inputField.maxNumberOfLines = maxNumberOfLines(forSize: parentSize)
inputField.refreshHeight()
inputField.internalTextView.selectedRange = range
inputField.delegate = self
}
private func maxNumberOfLines(forSize size: CGSize) -> Int32 {
if size.height <= 320 {
return 3
} else if (size.height <= 480) {
return 5;
} else {
return 7
}
}
func growingTextViewDidChange(_ growingTextView: HPGrowingTextView!) {
toggleSendButtonEnabled()
}
@objc func didTapSendButton(_ sender: UIButton) {
guard let text = inputField.internalTextView.text else {
return
}
let str = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if str.count > 0 {
if let d = delegate as? SimpleInputPanelDelegate {
d.inputTextPanel(self, requestSendText: str)
}
clearInputField()
}
}
func toggleSendButtonEnabled() {
let hasText = inputField.internalTextView.hasText
sendButton.isEnabled = hasText
}
}
| mit | 86bd3c031aac89acefa143a541a15046 | 40.918159 | 344 | 0.653142 | 5.101152 | false | false | false | false |
steelwheels/Coconut | CoconutData/Test/UnitTest/UTNativeValue.swift | 1 | 2400 | /**
* @file UTNativeValue.swift
* @brief Test function for CNValue datastructure
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import CoconutData
import Foundation
public func testNativeValue(console cons: CNConsole) -> Bool
{
var result = true
if !parseValue(string: "{}", console: cons){ result = false }
if !parseValue(string: "[]", console: cons){ result = false }
if !parseValue(string: "[10, 20]", console: cons){ result = false }
if !parseValue(string: "[[10, 20], [\"a\", \"b\"]]", console: cons){ result = false }
result = compareValues(console: cons) && result
return result
}
private func parseValue(string str: String, console cons: CNConsole) -> Bool {
cons.print(string: "source: \(str)\n")
let parser = CNValueParser()
let result: Bool
switch parser.parse(source: str) {
case .success(let val):
let valstr = val.toScript().toStrings().joined(separator: "\n")
cons.print(string: "result: \(valstr)\n")
result = true
case .failure(let err):
cons.print(string: "result: [Error] \(err.description)")
result = false
}
return result
}
private func compareValues(console cons: CNConsole) -> Bool {
var result = true
result = compareValue(value0: CNValue.null, value1: CNValue.null, expected: .orderedSame, console: cons) && result
result = compareValue(value0: .numberValue(NSNumber(floatLiteral: 1.23)),
value1: .numberValue(NSNumber(floatLiteral: 1.23)),
expected: .orderedSame, console: cons) && result
result = compareValue(value0: .numberValue(NSNumber(floatLiteral: 1.23)),
value1: .numberValue(NSNumber(floatLiteral: 12.3)),
expected: .orderedAscending, console: cons) && result
result = compareValue(value0: .numberValue(NSNumber(booleanLiteral: false)),
value1: .numberValue(NSNumber(floatLiteral: 12.3)),
expected: .orderedAscending, console: cons) && result
return result
}
private func compareValue(value0 val0: CNValue, value1 val1: CNValue, expected exp: ComparisonResult, console cons: CNConsole) -> Bool {
cons.print(string: "Compare \(val0.toScript().toStrings().joined()) and \(val1.toScript().toStrings().joined()) ... ")
let res = CNCompareValue(nativeValue0: val0, nativeValue1: val1)
cons.print(string: " \(res.toString()) -> ")
if res == exp {
cons.print(string: "OK\n")
return true
} else {
cons.print(string: "Error\n")
return false
}
}
| lgpl-2.1 | de91628a695d367f24c14a2ca913e6ae | 35.363636 | 136 | 0.69125 | 3.404255 | false | false | false | false |
pdil/PDColorPicker | Source/Dimmable.swift | 1 | 4210 | //
// Dimmable.swift
// PDColorPicker
//
// Created by Paolo Di Lorenzo on 8/8/17.
// Copyright © 2017 Paolo Di Lorenzo. All rights reserved.
//
import UIKit
/// Provides a simple mechanism for dimming a view controller.
///
/// The intended usage of this protocol is to allow dimming of a view controller
/// so that another view controller (e.g. an alert) may be presented on top of it.
///
/// - note:
/// Be sure to carefully read the documentation for proper use of the `dim()` and
/// `undim()` methods that are implemented by this protocol. Misuse may cause issues
/// with the view hierarchy of the view controller.
public protocol Dimmable { }
public extension Dimmable where Self: UIViewController {
/// Convenience method that creates a view in frame `rect`,
/// with color `color` and transparency `alpha`.
private func createDimView(in superview: UIView, color: UIColor, alpha: CGFloat) -> UIView? {
let dimView = UIView()
superview.addSubview(dimView)
dimView.anchorFill(view: superview)
dimView.backgroundColor = color
dimView.alpha = 0
if #available(iOS 11.0, *) {
dimView.accessibilityIgnoresInvertColors = true
}
return dimView
}
/**
Dims the view controller that it is called on. If the view controller is inside a `UINavigationController`,
`UITabBarController`, or both, the entire view will be dimmed including the navigation bar and tab bar.
- warning:
Do not add any subviews to the view controller while it is dimmed. Instead, call `undim()` on the
view controller before adding any subviews.
- parameters:
- color: The tint color to be used in dimming. The default is `UIColor.black`.
- alpha: The transparency level of the dim. A value of 0.0 means a completely transparent dim (no effect)
whereas 1.0 is a completely opaque dim. The default value is 0.5.
- speed: The animation speed of the dimming (in seconds). The default value is 0.5.
*/
func dim(_ color: UIColor = .black, alpha: CGFloat = 0.5, speed: TimeInterval = 0.5) {
let viewToDim: UIView
if let navigationController = navigationController {
viewToDim = navigationController.view
} else {
viewToDim = self.view
}
if let dimmingView = createDimView(in: viewToDim, color: color, alpha: alpha) {
UIView.animate(withDuration: 0.25) { dimmingView.alpha = alpha }
}
if let tabBar = tabBarController?.tabBar {
if let tabBarDimView = createDimView(in: tabBar, color: color, alpha: alpha) {
UIView.animate(withDuration: 0.25) { tabBarDimView.alpha = alpha }
}
}
}
/**
Undims the view controller that it is called on. This method has no effect if the view controller
has not been dimmed with `dim()` yet.
- warning:
Do not call this method unless `dim()` has been called first and the view controller has not
been undimmed already. Calling this method when the view controller is not dimmed may cause
issues with the view hierarchy.
- parameters:
- speed: The animation speed of the undimming (in seconds). The default value is 0.5.
- completion: The completion handler that is called after the undimming is complete. Use this
parameter to execute any cleanup or setup code that should be executed immediately after the
view controller becomes visible again.
*/
func undim(speed: TimeInterval = 0.5, completion: @escaping () -> () = {}) {
UIView.animate(withDuration: speed, animations: {
self.tabBarController?.tabBar.subviews.last?.alpha = 0
if let navigationController = self.navigationController {
navigationController.view.subviews.last?.alpha = 0
} else {
self.view.subviews.last?.alpha = 0
}
self.view.subviews.last?.alpha = 0
}, completion: { _ in
self.tabBarController?.tabBar.subviews.last?.removeFromSuperview()
if let navigationController = self.navigationController {
navigationController.view.subviews.last?.removeFromSuperview()
} else {
self.view.subviews.last?.removeFromSuperview()
}
completion()
})
}
}
| mit | 05acb414c32f9424e3f35943e50e5be5 | 35.284483 | 110 | 0.683535 | 4.425868 | false | false | false | false |
lukesutton/uut | Sources/Properties-Border.swift | 1 | 13130 | extension PropertyNames {
public static let border = "border"
public static let borderColor = "border-color"
public static let borderStyle = "border-style"
public static let borderWidth = "border-width"
public static let borderBottom = "border-bottom"
public static let borderBottomColor = "border-bottom-color"
public static let borderBottomStyle = "border-bottom-style"
public static let borderBottomWidth = "border-bottom-width"
public static let borderLeft = "border-left"
public static let borderLeftColor = "border-left-color"
public static let borderLeftStyle = "border-left-style"
public static let borderLeftWidth = "border-left-width"
public static let borderRight = "border-right"
public static let borderRightColor = "border-right-color"
public static let borderRightStyle = "border-right-style"
public static let borderRightWidth = "border-right-width"
public static let borderTop = "border-top"
public static let borderTopColor = "border-top-color"
public static let borderTopStyle = "border-top-style"
public static let borderTopWidth = "border-top-width"
public static let borderRadius = "border-radius"
public static let borderRightRadius = "border-right-radius"
public static let borderLeftRadius = "border-left-radius"
public static let borderTopLeftRadius = "border-top-left-radius"
public static let borderTopRightRadius = "border-top-right-radius"
public static let borderBottomLeftRadius = "border-bottom-left-radius"
public static let borderBottomRightRadius = "border-bottom-right-radius"
}
// Border
public func border(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.border, PropertyValues.Border(width, style, color))
}
public func border(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.border, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, color))
}
public func border(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.border, PropertyValues.Border(width, style, PropertyValues.Color.Value(color)))
}
public func border(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.border, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, PropertyValues.Color.Value(color)))
}
public func border(value: PropertyValues.Reset) -> Property {
return Property(PropertyNames.border, PropertyValues.Border(value))
}
public func borderColor(value: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderColor, value)
}
public func borderColor(value: Values.Color) -> Property {
return Property(PropertyNames.borderColor, PropertyValues.Color.Value(value))
}
public func borderStyle(value: PropertyValues.BorderStyle) -> Property {
return Property(PropertyNames.borderStyle, value)
}
public func borderWidth(value: PropertyValues.BorderWidth) -> Property {
return Property(PropertyNames.borderWidth, value)
}
public func borderWidth(value: Measurement) -> Property {
return Property(PropertyNames.borderColor, PropertyValues.BorderWidth.Value(value))
}
// Border left
public func borderLeft(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderLeft, PropertyValues.Border(width, style, color))
}
public func borderLeft(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderLeft, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, color))
}
public func borderLeft(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderLeft, PropertyValues.Border(width, style, PropertyValues.Color.Value(color)))
}
public func borderLeft(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderLeft, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, PropertyValues.Color.Value(color)))
}
public func borderLeft(value: PropertyValues.Reset) -> Property {
return Property(PropertyNames.borderLeft, PropertyValues.Border(value))
}
public func borderLeftColor(value: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderLeftColor, value)
}
public func borderLeftColor(value: Values.Color) -> Property {
return Property(PropertyNames.borderLeftColor, PropertyValues.Color.Value(value))
}
public func borderLeftStyle(value: PropertyValues.BorderStyle) -> Property {
return Property(PropertyNames.borderLeftStyle, value)
}
public func borderLeftWidth(value: PropertyValues.BorderWidth) -> Property {
return Property(PropertyNames.borderLeftWidth, value)
}
public func borderLeftWidth(value: Measurement) -> Property {
return Property(PropertyNames.borderLeftColor, PropertyValues.BorderWidth.Value(value))
}
// Border Right
public func borderRight(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderRight, PropertyValues.Border(width, style, color))
}
public func borderRight(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderRight, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, color))
}
public func borderRight(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderRight, PropertyValues.Border(width, style, PropertyValues.Color.Value(color)))
}
public func borderRight(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderRight, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, PropertyValues.Color.Value(color)))
}
public func borderRight(value: PropertyValues.Reset) -> Property {
return Property(PropertyNames.borderRight, PropertyValues.Border(value))
}
public func borderRightColor(value: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderRightColor, value)
}
public func borderRightColor(value: Values.Color) -> Property {
return Property(PropertyNames.borderRightColor, PropertyValues.Color.Value(value))
}
public func borderRightStyle(value: PropertyValues.BorderStyle) -> Property {
return Property(PropertyNames.borderRightStyle, value)
}
public func borderRightWidth(value: PropertyValues.BorderWidth) -> Property {
return Property(PropertyNames.borderRightWidth, value)
}
public func borderRightWidth(value: Measurement) -> Property {
return Property(PropertyNames.borderRightColor, PropertyValues.BorderWidth.Value(value))
}
// Border top
public func borderTop(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderTop, PropertyValues.Border(width, style, color))
}
public func borderTop(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderTop, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, color))
}
public func borderTop(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderTop, PropertyValues.Border(width, style, PropertyValues.Color.Value(color)))
}
public func borderTop(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderTop, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, PropertyValues.Color.Value(color)))
}
public func borderTop(value: PropertyValues.Reset) -> Property {
return Property(PropertyNames.borderTop, PropertyValues.Border(value))
}
public func borderTopColor(value: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderTopColor, value)
}
public func borderTopColor(value: Values.Color) -> Property {
return Property(PropertyNames.borderTopColor, PropertyValues.Color.Value(value))
}
public func borderTopStyle(value: PropertyValues.BorderStyle) -> Property {
return Property(PropertyNames.borderTopStyle, value)
}
public func borderTopWidth(value: PropertyValues.BorderWidth) -> Property {
return Property(PropertyNames.borderTopWidth, value)
}
public func borderTopColor(value: Measurement) -> Property {
return Property(PropertyNames.borderTopColor, PropertyValues.BorderWidth.Value(value))
}
// Border bottom
public func borderBottom(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderBottom, PropertyValues.Border(width, style, color))
}
public func borderBottom(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderBottom, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, color))
}
public func borderBottom(width: PropertyValues.BorderWidth, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderBottom, PropertyValues.Border(width, style, PropertyValues.Color.Value(color)))
}
public func borderBottom(width: Measurement, _ style: PropertyValues.BorderStyle, _ color: Values.Color) -> Property {
return Property(PropertyNames.borderBottom, PropertyValues.Border(PropertyValues.BorderWidth.Value(width), style, PropertyValues.Color.Value(color)))
}
public func borderBottom(value: PropertyValues.Reset) -> Property {
return Property(PropertyNames.borderBottom, PropertyValues.Border(value))
}
public func borderBottomColor(value: PropertyValues.Color) -> Property {
return Property(PropertyNames.borderBottomColor, value)
}
public func borderBottomColor(value: Values.Color) -> Property {
return Property(PropertyNames.borderBottomColor, PropertyValues.Color.Value(value))
}
public func borderBottomStyle(value: PropertyValues.BorderStyle) -> Property {
return Property(PropertyNames.borderBottomStyle, value)
}
public func borderBottomWidth(value: PropertyValues.BorderWidth) -> Property {
return Property(PropertyNames.borderBottomWidth, value)
}
public func borderBottomWidth(value: Measurement) -> Property {
return Property(PropertyNames.borderBottomColor, PropertyValues.BorderWidth.Value(value))
}
// Border radius
public func borderRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderRadius, value)
}
public func borderRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderLeftRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderLeftRadius, value)
}
public func borderLeftRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderLeftRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderRightRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderRightRadius, value)
}
public func borderRightRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderRightRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderTopLeftRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderTopLeftRadius, value)
}
public func borderTopLeftRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderTopLeftRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderTopRightRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderTopRightRadius, value)
}
public func borderTopRightRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderTopRightRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderBottomLeftRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderBottomLeftRadius, value)
}
public func borderBottomLeftRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderBottomLeftRadius, PropertyValues.MeasurementStandard.Value(value))
}
public func borderBottomRightRadius(value: PropertyValues.MeasurementStandard) -> Property {
return Property(PropertyNames.borderBottomRightRadius, value)
}
public func borderBottomRightRadius(value: Measurement) -> Property {
return Property(PropertyNames.borderBottomRightRadius, PropertyValues.MeasurementStandard.Value(value))
}
| mit | d9baa186990506af25151bc6d3d33108 | 43.208754 | 151 | 0.801142 | 4.450847 | false | false | false | false |
visualitysoftware/swift-sdk | CloudBoost/SocketParsable.swift | 1 | 6883 | //
// SocketParsable.swift
// Socket.IO-Client-Swift
//
// 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
protocol SocketParsable : SocketClientSpec {
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
}
extension SocketParsable {
private func isCorrectNamespace(nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(p: SocketPacket) {
if p.nsp == "/" && nsp != "/" {
joinNamespace(nsp)
} else if p.nsp != "/" && nsp == "/" {
didConnect()
} else {
didConnect()
}
}
private func handlePacket(pack: SocketPacket) {
switch pack.type {
case .Event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args,
isInternalMessage: false, withAck: pack.id)
case .Ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
didDisconnect("Got Disconnect")
case .Error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
}
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(message: String) -> Either<String, SocketPacket> {
var parser = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
return .Left("Invalid packet type")
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return .Left("Invalid packet")
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, id: -1,
nsp: namespace ?? "/", placeholders: placeholders))
}
var idString = ""
if type == .Error {
parser.advanceIndexBy(-1)
}
while parser.hasNext && type != .Error {
if let int = Int(parser.read(1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
break
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
switch parseData(noPlaceholders) {
case let .Left(err):
// Errors aren't always enclosed in an array
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
} else {
return .Left(err)
}
case let .Right(data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
} catch {
return .Left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .Left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .Right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(data: NSData) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingPackets[waitingPackets.count - 1].addData(data) else {
return
}
let packet = waitingPackets.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
}
}
| mit | 90da8dd3bf4de06f52bba6199c0abbce | 36.612022 | 114 | 0.584774 | 4.843772 | false | false | false | false |
pivotframework/pivot | PivotFoundation/PivotFoundationTests/PivotURLTests.swift | 1 | 712 | import XCTest
import PivotFoundation
class PivotURLTests: XCTestCase {
func testInitWithString() {
let urlString = "http://www.praglabs.com/"
let url = PivotURL(urlString: urlString)
XCTAssertTrue(CFURLCopyAbsoluteURL(url.cfURL) == CFURLCopyAbsoluteURL(CFURLCreateWithString(nil, urlString as CFString, nil)))
}
func testInitWithStringAndBaseURL() {
let baseURL = PivotURL(urlString: "http://www.praglabs.com/")
let urlString = "index.html"
let url = PivotURL(urlString: urlString, baseURL: baseURL)
let cfURL = CFURLCreateWithString(nil, urlString as CFString, baseURL.cfURL)
XCTAssertTrue(CFEqual(cfURL,url.cfURL) != 0)
}
}
| mit | 6df6968353a3c8b76cc50d75f79217ba | 38.555556 | 134 | 0.692416 | 4.238095 | false | true | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/CharData.swift | 1 | 3695 | //
// CharData.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 29.9.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// Chardata is used for storing text within a verse or another container. Character data may have specific styling associated with it (quotation, special meaning, etc.)
struct CharData: Equatable, USXConvertible, AttributedStringConvertible, JSONConvertible, ExpressibleByStringLiteral
{
// typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
// ATTRIBUTES ----
var style: CharStyle?
var text: String
// COMP. PROPERTIES --
var properties: [String : PropertyValue]
{
return [
"style" : (style?.code).value,
"text" : text.value]
}
var toUSX: String
{
// Empty charData is not recorded in USX
if isEmpty
{
return ""
}
else if let style = style
{
return "<char style=\"\(style.code)\">\(text)</char>"
}
else
{
return text
}
}
var isEmpty: Bool { return text.isEmpty }
// INIT ----
init(text: String, style: CharStyle? = nil)
{
self.text = text
self.style = style
}
init(stringLiteral value: String)
{
self.text = value
self.style = nil
}
init(unicodeScalarLiteral value: String)
{
self.text = value
self.style = nil
}
init(extendedGraphemeClusterLiteral value: String)
{
self.text = value
self.style = nil
}
static func parse(from propertyData: PropertySet) -> CharData
{
var style: CharStyle? = nil
if let styleValue = propertyData["style"].string
{
style = CharStyle.of(styleValue)
}
return CharData(text: propertyData["text"].string(), style: style)
}
// OPERATORS ----
static func == (left: CharData, right: CharData) -> Bool
{
return left.text == right.text && left.style == right.style
}
// CONFORMED ---
func toAttributedString(options: [String : Any] = [:]) -> NSAttributedString
{
// TODO: At some point one may wish to add other types of attributes based on the style
let attributes = [CharStyleAttributeName : style as Any]
return NSAttributedString(string: text, attributes: attributes)
}
// OTHER ------
func appended(_ text: String) -> CharData
{
return CharData(text: self.text + text, style: self.style)
}
func emptyCopy() -> CharData
{
return CharData(text: "", style: style)
}
static func text(of data: [CharData]) -> String
{
return data.reduce("") { $0 + $1.text }
/*
var text = ""
for charData in data
{
text.append(charData.text)
}
return text*/
}
static func update(_ first: [CharData], with second: [CharData]) -> [CharData]
{
var updated = [CharData]()
// Updates the text in the first array with the matching style instances in the second array
var lastSecondIndex = -1
for oldVersion in first
{
// Finds the matching version
var matchingIndex: Int?
for secondIndex in lastSecondIndex + 1 ..< second.count
{
if second[secondIndex].style == oldVersion.style
{
matchingIndex = secondIndex
break
}
}
// Copies the new text or empties the array
if let matchingIndex = matchingIndex
{
// In case some of the second array data was skipped, adds it in between
for i in lastSecondIndex + 1 ..< matchingIndex
{
updated.add(second[i])
}
updated.add(CharData(text: second[matchingIndex].text, style: oldVersion.style))
lastSecondIndex = matchingIndex
}
else
{
updated.add(CharData(text: "", style: oldVersion.style))
}
}
// Makes sure the rest of the second array are included
for i in lastSecondIndex + 1 ..< second.count
{
updated.add(second[i])
}
return updated
}
}
| mit | e4f1dc90aac3aed5c9d0f52377c73171 | 19.752809 | 168 | 0.658906 | 3.395221 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/maximum-split-of-positive-even-integers.swift | 1 | 439 | class Solution {
func maximumEvenSplit(_ finalSum: Int) -> [Int] {
guard finalSum % 2 == 0 else { return [] }
var result = [Int]()
var sum = 0
var inc = 2
while (sum + inc) <= finalSum {
result.append(inc)
sum += inc
inc += 2
}
if sum < finalSum {
result[result.count - 1] += finalSum - sum
}
return result
}
}
| mit | 98dd82503e5b0e0cce72a3e00712ef95 | 24.823529 | 54 | 0.446469 | 4.064815 | false | false | false | false |
kgn/KGNCache | Source/Cache.swift | 1 | 7193 | //
// Cache.swift
// Cache
//
// Created by David Keegan on 8/12/15.
// Copyright © 2015 David Keegan. All rights reserved.
//
import Foundation
import Crypto
@objc(KGN) private class CacheObject: NSObject, NSCoding {
var key: String!
var object: AnyObject!
var date: Date!
var expires: DateComponents?
init(key: String, object: AnyObject, expires: DateComponents? = nil) {
self.key = key
self.object = object
self.expires = expires
self.date = Date()
}
@objc required init?(coder aDecoder: NSCoder) {
if let key = aDecoder.decodeObject(forKey: "key") as? String {
self.key = key
}
if let object = aDecoder.decodeObject(forKey: "object") {
self.object = object as AnyObject!
}
if let date = aDecoder.decodeObject(forKey: "date") as? Date {
self.date = date
}
if let expires = aDecoder.decodeObject(forKey: "expires") as? DateComponents {
self.expires = expires
}
}
@objc fileprivate func encode(with aCoder: NSCoder) {
aCoder.encode(self.key, forKey: "key")
aCoder.encode(self.object, forKey: "object")
aCoder.encode(self.expires, forKey: "expires")
aCoder.encode(self.date, forKey: "date")
}
fileprivate func hasExpired() -> Bool {
guard let components = self.expires else {
return false
}
let calander = Calendar(identifier: .gregorian)
guard let componentsDate = calander.date(byAdding: components, to: self.date, wrappingComponents: false) else {
return false
}
return (componentsDate.compare(Date()) != .orderedDescending)
}
}
/// The location of where the cache data came from.
public enum CacheLocation {
case memory
case disk
}
open class Cache {
private let cacheName: String!
private let memoryCache = NSCache<AnyObject, CacheObject>()
private func cacheDirectory(create: Bool = false) -> String? {
guard let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
return nil
}
let cachePath = "\(cacheDirectory)/\(self.cacheName)"
if create && !FileManager().fileExists(atPath: cachePath) {
do {
try FileManager().createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
}
return cachePath
}
private func object(fromCacheObject cacheObject: CacheObject?) -> AnyObject? {
if cacheObject?.hasExpired() == true {
return nil
}
return cacheObject?.object
}
internal func cacheObjectPath(withKeyHash keyHash: String) -> String? {
guard let cacheDirectory = self.cacheDirectory() else {
return nil
}
return "\(cacheDirectory)/\(keyHash)"
}
internal func hash(forKey key: String) -> String? {
return key.sha1
}
// MARK: - Public Methods
/**
Create a `Cache` object. This sets up both the memory and disk cache.
- Parameter named: The name of the cache.
*/
public init(named: String) {
self.cacheName = "\(Bundle.main.bundleIdentifier ?? "kgn.cache").\(named)"
_ = self.cacheDirectory(create: true)
}
/**
Retrieve an object from the cache by it's key.
- Parameter key: The key of the object in the cache.
- Parameter callback: The method to call with the retrieved object from the cache.
The retrieved object may be nil if an object for the given key does not exist, or if it has expired.
*/
open func object(forKey key: String, callback: @escaping (_ object: AnyObject?, _ location: CacheLocation?) -> Void) {
guard let keyHash = self.hash(forKey: key) else {
callback(nil, nil)
return
}
if let cacheObject = self.memoryCache.object(forKey: keyHash as AnyObject) {
callback(self.object(fromCacheObject: cacheObject), .memory)
return
}
guard let cacheObjectPath = self.cacheObjectPath(withKeyHash: keyHash) else {
callback(nil, nil)
return
}
DispatchQueue.global().async { [weak self] in
if FileManager().fileExists(atPath: cacheObjectPath) {
if let cacheObject = NSKeyedUnarchiver.unarchiveObject(withFile: cacheObjectPath) as? CacheObject {
self?.memoryCache.setObject(cacheObject, forKey: keyHash as AnyObject)
callback(self?.object(fromCacheObject: cacheObject), .disk)
} else {
callback(nil, nil)
}
} else {
callback(nil, nil)
}
}
}
/**
Store an object in the cache for a given key.
An optional expiration date components object may be set if the object should expire.
- Parameter object: The object to store in the cache.
- Parameter forKey: The key of the object in the cache.
- Parameter expires: An optional date components object that defines how long the object should be cached for.
- Parameter callback: This method is called when the object has been stored.
*/
open func set(object: AnyObject, forKey key: String, expires: DateComponents? = nil, callback: ((_ location: CacheLocation?) -> Void)? = nil) {
guard let keyHash = self.hash(forKey: key) else {
callback?(nil)
return
}
let cacheObject = CacheObject(key: key, object: object, expires: expires)
self.memoryCache.setObject(cacheObject, forKey: keyHash as AnyObject)
guard let cacheObjectPath = self.cacheObjectPath(withKeyHash: keyHash) else {
callback?(.memory)
return
}
DispatchQueue.global().async {
let data = NSKeyedArchiver.archivedData(withRootObject: cacheObject)
if (try? data.write(to: URL(fileURLWithPath: cacheObjectPath), options: [.atomic])) != nil {
callback?(.disk)
} else {
callback?(.memory)
}
}
}
/**
Remove an object from the cache.
- Parameter forKey: The key of the object in the cache.
*/
open func removeObject(forKey key: String) {
guard let keyHash = self.hash(forKey: key) else {
return
}
self.memoryCache.removeObject(forKey: keyHash as AnyObject)
if let cacheObjectPath = self.cacheObjectPath(withKeyHash: keyHash) {
DispatchQueue.global().async {
try? FileManager().removeItem(atPath: cacheObjectPath)
}
}
}
/// Remove all objects from the cache.
open func clear() {
self.memoryCache.removeAllObjects()
if let cacheDirectory = self.cacheDirectory() {
DispatchQueue.global().async {
try? FileManager().removeItem(atPath: cacheDirectory)
}
}
}
}
| mit | 73011ff6454b04d4b4c04cc3ebd0a7c0 | 31.690909 | 147 | 0.601502 | 4.775564 | false | false | false | false |
alblue/swift | test/IRGen/protocol_conformance_records.swift | 1 | 6536 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
import resilient_struct
import resilient_protocol
public protocol Associate {
associatedtype X
}
public struct Dependent<T> {}
public protocol Runcible {
func runce()
}
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE:@"\$s28protocol_conformance_records8RuncibleMp"]]
// -- type metadata
// CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeValueType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- class metadata
// CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public class NativeClassType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeGenericType<T>: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$sSi28protocol_conformance_records8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- type metadata
// CHECK-SAME: @"{{got.|__imp_}}$sSiMn"
// -- witness table
// CHECK-SAME: @"$sSi28protocol_conformance_records8RuncibleAAWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Int: Runcible {
public func runce() {}
}
// For a resilient struct, reference the NominalTypeDescriptor
// CHECK-LABEL: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|__imp_}}$s16resilient_struct4SizeVMn"
// -- witness table
// CHECK-SAME: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Size: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"\01l_protocols"
// CHECK-SAME: @"$s28protocol_conformance_records8RuncibleMp"
// CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp"
public protocol Spoon { }
// Conditional conformances
// CHECK-LABEL: {{^}}@"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp"
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table accessor
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5Spoon
// -- flags
// CHECK-SAME: i32 131328
// -- conditional requirement #1
// CHECK-SAME: i32 128,
// CHECK-SAME: i32 0,
// CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp"
// CHECK-SAME: }
extension NativeGenericType : Spoon where T: Spoon {
public func runce() {}
}
// Retroactive conformance
// CHECK-LABEL: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"{{got.|__imp_}}$s18resilient_protocol22OtherResilientProtocolMp"
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|__imp_}}$sSiMn"
// -- witness table pattern
// CHECK-SAME: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsWp"
// -- flags
// CHECK-SAME: i32 131144,
// -- module context for retroactive conformance
// CHECK-SAME: @"$s28protocol_conformance_recordsMXM"
// CHECK-SAME: }
extension Int : OtherResilientProtocol { }
// Dependent conformance
// CHECK-LABEL: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$s28protocol_conformance_records9AssociateMp"
// -- nominal type descriptor
// CHECK-SAME: @"$s28protocol_conformance_records9DependentVMn"
// -- witness table pattern
// CHECK-SAME: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAWp"
// -- flags
// CHECK-SAME: i32 0
// -- number of words in witness table
// CHECK-SAME: i16 2,
// -- number of private words in witness table + bit for "needs instantiation"
// CHECK-SAME: i16 1
// CHECK-SAME: }
extension Dependent : Associate {
public typealias X = (T, T)
}
// CHECK-LABEL: @"\01l_protocol_conformances" = private constant
// CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc"
// CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc"
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc"
// CHECK-SAME: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc"
// CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc"
// CHECK-SAME: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc"
| apache-2.0 | 187b693cdcd23e9d1a259c21e94dda3a | 41.167742 | 177 | 0.691248 | 4.012277 | false | false | false | false |
zyrx/eidolon | Kiosk/Bid Fulfillment/ConfirmYourBidEnterYourEmailViewController.swift | 6 | 2217 | import UIKit
import ReactiveCocoa
import Swift_RAC_Macros
class ConfirmYourBidEnterYourEmailViewController: UIViewController {
@IBOutlet var emailTextField: UITextField!
@IBOutlet var confirmButton: UIButton!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidEnterYourEmailViewController {
return storyboard.viewControllerWithID(.ConfirmYourBidEnterEmail) as! ConfirmYourBidEnterYourEmailViewController
}
override func viewDidLoad() {
super.viewDidLoad()
let emailTextSignal = emailTextField.rac_textSignal()
let inputIsEmail = emailTextSignal.map(stringIsEmailAddress)
confirmButton.rac_command = RACCommand(enabled: inputIsEmail) { [weak self] _ in
if (self == nil) {
return RACSignal.empty()
}
let endpoint: ArtsyAPI = ArtsyAPI.FindExistingEmailRegistration(email: self!.emailTextField.text ?? "")
return XAppRequest(endpoint).filterStatusCode(200).doNext({ (__) -> Void in
self?.performSegue(.ExistingArtsyUserFound)
return
}).doError { (error) -> Void in
self?.performSegue(.EmailNotFoundonArtsy)
return
}
}
let unbindSignal = confirmButton.rac_command.executing.ignore(false)
let nav = self.fulfillmentNav()
bidDetailsPreviewView.bidDetails = nav.bidDetails
RAC(nav.bidDetails.newUser, "email") <~ emailTextSignal.takeUntil(unbindSignal)
emailTextField.returnKeySignal().subscribeNext { [weak self] (_) -> Void in
self?.confirmButton.rac_command.execute(nil)
return
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.emailTextField.becomeFirstResponder()
}
}
private extension ConfirmYourBidEnterYourEmailViewController {
@IBAction func dev_emailFound(sender: AnyObject) {
performSegue(.ExistingArtsyUserFound)
}
@IBAction func dev_emailNotFound(sender: AnyObject) {
performSegue(.EmailNotFoundonArtsy)
}
} | mit | f39cef960c3c315a9589cbbf4c671ffe | 31.617647 | 120 | 0.679296 | 5.487624 | false | false | false | false |
flodolo/firefox-ios | Client/Frontend/Home/JumpBackIn/Cell/JumpBackInCell.swift | 1 | 11670 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
import Storage
import UIKit
struct JumpBackInCellViewModel {
let titleText: String
let descriptionText: String
var favIconImage: UIImage?
var heroImage: UIImage?
var accessibilityLabel: String {
return "\(titleText), \(descriptionText)"
}
}
// MARK: - JumpBackInCell
/// A cell used in Home page Jump Back In section
class JumpBackInCell: UICollectionViewCell, ReusableCell {
struct UX {
static let interItemSpacing = NSCollectionLayoutSpacing.fixed(8)
static let interGroupSpacing: CGFloat = 8
static let generalCornerRadius: CGFloat = 12
static let titleFontSize: CGFloat = 15
static let siteFontSize: CGFloat = 12
static let heroImageSize = CGSize(width: 108, height: 80)
static let fallbackFaviconSize = CGSize(width: 36, height: 36)
static let faviconSize = CGSize(width: 24, height: 24)
}
private var faviconCenterConstraint: NSLayoutConstraint?
private var faviconFirstBaselineConstraint: NSLayoutConstraint?
// MARK: - UI Elements
private let heroImage: UIImageView = .build { imageView in
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius
imageView.backgroundColor = .clear
}
private let itemTitle: UILabel = .build { label in
label.adjustsFontForContentSizeCategory = true
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .subheadline,
size: UX.titleFontSize)
label.numberOfLines = 2
}
// Contains the faviconImage and descriptionLabel
private var descriptionContainer: UIStackView = .build { stackView in
stackView.backgroundColor = .clear
stackView.spacing = 8
stackView.axis = .horizontal
stackView.alignment = .leading
stackView.distribution = .fillProportionally
}
private let faviconImage: UIImageView = .build { imageView in
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius
}
private let descriptionLabel: UILabel = .build { label in
label.adjustsFontForContentSizeCategory = true
label.font = DynamicFontHelper.defaultHelper.preferredBoldFont(withTextStyle: .caption1,
size: UX.siteFontSize)
label.textColor = .label
}
// Used as a fallback if hero image isn't set
private let fallbackFaviconImage: UIImageView = .build { imageView in
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.backgroundColor = .clear
imageView.layer.cornerRadius = HomepageViewModel.UX.generalIconCornerRadius
imageView.layer.masksToBounds = true
}
private var fallbackFaviconBackground: UIView = .build { view in
view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius
view.layer.borderWidth = HomepageViewModel.UX.generalBorderWidth
}
// Contains the hero image and fallback favicons
private var imageContainer: UIView = .build { view in
view.backgroundColor = .clear
}
// MARK: - Inits
override init(frame: CGRect) {
super.init(frame: .zero)
isAccessibilityElement = true
accessibilityIdentifier = AccessibilityIdentifiers.FirefoxHomepage.JumpBackIn.itemCell
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
heroImage.image = nil
faviconImage.image = nil
fallbackFaviconImage.image = nil
descriptionLabel.text = nil
itemTitle.text = nil
setFallBackFaviconVisibility(isHidden: false)
faviconImage.isHidden = false
descriptionContainer.addArrangedViewToTop(faviconImage)
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.layer.shadowPath = UIBezierPath(roundedRect: contentView.bounds,
cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath
}
// MARK: - Helpers
func configure(viewModel: JumpBackInCellViewModel, theme: Theme) {
configureImages(viewModel: viewModel)
itemTitle.text = viewModel.titleText
descriptionLabel.text = viewModel.descriptionText
accessibilityLabel = viewModel.accessibilityLabel
adjustLayout()
applyTheme(theme: theme)
}
private func configureImages(viewModel: JumpBackInCellViewModel) {
if viewModel.heroImage == nil {
// Sets a small favicon in place of the hero image in case there's no hero image
fallbackFaviconImage.image = viewModel.favIconImage
} else if viewModel.heroImage?.size.width == viewModel.heroImage?.size.height {
// If hero image is a square use it as a favicon
fallbackFaviconImage.image = viewModel.heroImage
} else {
setFallBackFaviconVisibility(isHidden: true)
heroImage.image = viewModel.heroImage
}
faviconImage.image = viewModel.favIconImage
}
private func setFallBackFaviconVisibility(isHidden: Bool) {
fallbackFaviconBackground.isHidden = isHidden
fallbackFaviconImage.isHidden = isHidden
}
private func setupLayout() {
fallbackFaviconBackground.addSubviews(fallbackFaviconImage)
imageContainer.addSubviews(heroImage, fallbackFaviconBackground)
descriptionContainer.addArrangedSubview(faviconImage)
descriptionContainer.addArrangedSubview(descriptionLabel)
contentView.addSubviews(itemTitle, imageContainer, descriptionContainer)
NSLayoutConstraint.activate([
itemTitle.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),
itemTitle.leadingAnchor.constraint(equalTo: imageContainer.trailingAnchor, constant: 16),
itemTitle.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
// Image container, hero image and fallback
imageContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
imageContainer.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height),
imageContainer.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width),
imageContainer.topAnchor.constraint(equalTo: itemTitle.topAnchor),
imageContainer.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -16),
heroImage.topAnchor.constraint(equalTo: imageContainer.topAnchor),
heroImage.leadingAnchor.constraint(equalTo: imageContainer.leadingAnchor),
heroImage.trailingAnchor.constraint(equalTo: imageContainer.trailingAnchor),
heroImage.bottomAnchor.constraint(equalTo: imageContainer.bottomAnchor),
fallbackFaviconBackground.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor),
fallbackFaviconBackground.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor),
fallbackFaviconBackground.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height),
fallbackFaviconBackground.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width),
fallbackFaviconImage.heightAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.height),
fallbackFaviconImage.widthAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.width),
fallbackFaviconImage.centerXAnchor.constraint(equalTo: fallbackFaviconBackground.centerXAnchor),
fallbackFaviconImage.centerYAnchor.constraint(equalTo: fallbackFaviconBackground.centerYAnchor),
// Description container, it's image and label
descriptionContainer.topAnchor.constraint(greaterThanOrEqualTo: itemTitle.bottomAnchor, constant: 8),
descriptionContainer.leadingAnchor.constraint(equalTo: itemTitle.leadingAnchor),
descriptionContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
descriptionContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16),
faviconImage.heightAnchor.constraint(equalToConstant: UX.faviconSize.height),
faviconImage.widthAnchor.constraint(equalToConstant: UX.faviconSize.width),
])
faviconCenterConstraint = descriptionLabel.centerYAnchor.constraint(equalTo: faviconImage.centerYAnchor).priority(UILayoutPriority(999))
faviconFirstBaselineConstraint = descriptionLabel.firstBaselineAnchor.constraint(equalTo: faviconImage.bottomAnchor,
constant: -UX.faviconSize.height / 2)
descriptionLabel.setContentCompressionResistancePriority(UILayoutPriority(1000), for: .vertical)
}
private func adjustLayout() {
let contentSizeCategory = UIApplication.shared.preferredContentSizeCategory
// Center favicon on smaller font sizes. On bigger font sizes align with first baseline
faviconCenterConstraint?.isActive = !contentSizeCategory.isAccessibilityCategory
faviconFirstBaselineConstraint?.isActive = contentSizeCategory.isAccessibilityCategory
}
private func setupShadow(theme: Theme) {
contentView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius
contentView.layer.shadowPath = UIBezierPath(roundedRect: contentView.bounds,
cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath
contentView.layer.shadowRadius = HomepageViewModel.UX.shadowRadius
contentView.layer.shadowOffset = HomepageViewModel.UX.shadowOffset
contentView.layer.shadowColor = theme.colors.shadowDefault.cgColor
contentView.layer.shadowOpacity = HomepageViewModel.UX.shadowOpacity
}
}
// MARK: - ThemeApplicable
extension JumpBackInCell: ThemeApplicable {
func applyTheme(theme: Theme) {
itemTitle.textColor = theme.colors.textPrimary
descriptionLabel.textColor = theme.colors.textSecondary
faviconImage.tintColor = theme.colors.iconPrimary
fallbackFaviconImage.tintColor = theme.colors.iconPrimary
fallbackFaviconBackground.backgroundColor = theme.colors.layer1
fallbackFaviconBackground.layer.borderColor = theme.colors.layer1.cgColor
adjustBlur(theme: theme)
}
}
// MARK: - Blurrable
extension JumpBackInCell: Blurrable {
func adjustBlur(theme: Theme) {
// Add blur
if shouldApplyWallpaperBlur {
contentView.addBlurEffectWithClearBackgroundAndClipping(using: .systemThickMaterial)
contentView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius
} else {
contentView.removeVisualEffectView()
contentView.backgroundColor = theme.colors.layer5
setupShadow(theme: theme)
}
}
}
| mpl-2.0 | c1f594a95380b7fa48b6d582c2730e06 | 43.712644 | 144 | 0.706855 | 5.637681 | false | false | false | false |
cybertunnel/SplashBuddy | SplashBuddy/Preferences.swift | 1 | 8014 | //
// Preferences.swift
// SplashBuddy
//
// Created by ftiff on 03/08/16.
// Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//
import Cocoa
/**
Preferences() keeps the relevant preferences
*/
class Preferences {
static let sharedInstance = Preferences()
public let logFileHandle: FileHandle?
public var doneParsingPlist: Bool = false
internal let userDefaults: UserDefaults
internal let jamfLog = "/var/log/jamf.log"
//-----------------------------------------------------------------------------------
/// INIT
//-----------------------------------------------------------------------------------
init(nsUserDefaults: UserDefaults = UserDefaults.standard) {
self.userDefaults = nsUserDefaults
do {
self.logFileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: self.jamfLog, isDirectory: false))
} catch {
Log.write(string: "Cannot read /var/log/jamf.log",
cat: "Preferences",
level: .error)
self.logFileHandle = nil
}
// HTML Path
if let htmlPath = getPreferencesHtmlPath() {
self.htmlPath = htmlPath
} else {
Log.write(string: "Cannot get htmlPath from io.fti.SplashBuddy.plist",
cat: "Preferences",
level: .info)
}
// Asset Path
if let assetPath = getPreferencesAssetPath() {
self.assetPath = assetPath
} else {
self.assetPath = defaultAssetPath
}
}
//-----------------------------------------------------------------------------------
// Asset Path
//-----------------------------------------------------------------------------------
internal var assetPath = String()
internal let defaultAssetPath = "/Library/Application Support/SplashBuddy"
func getPreferencesAssetPath() -> String? {
return self.userDefaults.string(forKey: "assetPath")
}
//-----------------------------------------------------------------------------------
// HTML Path
//-----------------------------------------------------------------------------------
internal var htmlPath: String?
func getPreferencesHtmlPath() -> String? {
return self.userDefaults.string(forKey: "htmlPath")
}
/**
Absolute path to html index
- returns: Absolute Path if set in preferences, otherwise the placeholder.
*/
public var htmlAbsolutePath: String {
get {
if let htmlPath = self.htmlPath {
let htmlAbsolutePath = assetPath + "/" + htmlPath
if FileManager.default.fileExists(atPath: htmlAbsolutePath) {
return htmlAbsolutePath
}
}
return Bundle.main.path(forResource: "index", ofType: "html")!
}
}
var setupDone: Bool {
get {
return FileManager.default.fileExists(atPath: "Library/.SplashBuddyDone")
}
set(myValue) {
if myValue == true {
FileManager.default.createFile(atPath: "Library/.SplashBuddyDone", contents: nil, attributes: nil)
} else {
do {
try FileManager.default.removeItem(atPath: "Library/.SplashBuddyDone")
} catch {
Log.write(string: "Couldn't remove .SplashBuddyDone",
cat: "Preferences",
level: .info)
}
}
}
}
//-----------------------------------------------------------------------------------
// Software
//-----------------------------------------------------------------------------------
func extractSoftware(from dict: NSDictionary) -> Software? {
guard let name = dict["packageName"] as? String else {
Log.write(string: "Error reading name from an application in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let displayName: String = dict["displayName"] as? String else {
Log.write(string: "Error reading displayName from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let description: String = dict["description"] as? String else {
Log.write(string: "Error reading description from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let iconRelativePath: String = dict["iconRelativePath"] as? String else {
Log.write(string: "Error reading iconRelativePath from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let canContinueBool: Bool = getBool(from: dict["canContinue"]) else {
Log.write(string: "Error reading canContinueBool from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
let iconPath = self.assetPath + "/" + iconRelativePath
return Software(packageName: name,
version: nil,
status: .pending,
iconPath: iconPath,
displayName: displayName,
description: description,
canContinue: canContinueBool,
displayToUser: true)
}
/**
Try to get a Bool from an Any (String, Int or Bool)
- returns:
- True if 1, "1" or True
- False if any other value
- nil if cannot cast to String, Int or Bool.
- parameter object: Any? (String, Int or Bool)
*/
func getBool(from object: Any?) -> Bool? {
// In practice, canContinue is sometimes seen as int, sometimes as String
// This workaround helps to be more flexible
if let canContinue = object as? Int {
return (canContinue == 1)
} else if let canContinue = object as? String {
return (canContinue == "1")
} else if let canContinue = object as? Bool {
return canContinue
} else {
return nil
}
}
/// Generates Software objects from Preferences
func getPreferencesApplications() {
guard let applicationsArray = self.userDefaults.array(forKey: "applicationsArray") else {
Log.write(string: "Couldn't find applicationsArray in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return
}
for application in applicationsArray {
guard let application = application as? NSDictionary else {
Log.write(string: "applicationsArray: application is malformed",
cat: "Preferences",
level: .error)
return
}
if let software = extractSoftware(from: application) {
SoftwareArray.sharedInstance.array.append(software)
}
}
self.doneParsingPlist = true
}
}
| apache-2.0 | 56906526e76cf34c37a6d3da70a9abcc | 29.580153 | 119 | 0.463929 | 5.891176 | false | false | false | false |
Mathpix/ios-client | MathpixClient/Classes/Camera/Camera Overlay/CropControl.swift | 1 | 7540 | //
// CropControl.swift
// SliderTest
//
// Created by Gilbert Jolly on 30/04/2016.
// Copyright © 2016 Gilbert Jolly. All rights reserved.
//
import PureLayout
import Foundation
class CropControl: UIView {
var widthConstraint: NSLayoutConstraint?
var heightConstraint: NSLayoutConstraint?
var initialTouchOffset = CGPoint.zero
var panStateCallback: ((_ state: UIGestureRecognizerState) -> ())?
var cropFrameDidChangedCallback: ((_ bottomCenter: CGPoint) -> ())?
let imageOverlay = UIImageView()
var boxOverlay : MPOverlayView?
var color: UIColor = UIColor.white
fileprivate var maxEdges : CGSize?
fileprivate let cornersBorderMovement = UIEdgeInsets(top: 80, left: 0, bottom: 80, right: 0)
fileprivate var defaultCropSize : CGSize {
return CGSize(width: cornerLength * 7.0, height: cornerLength * 3.5)
}
//The length of each line from the corner (each corner control is double this size)
let cornerLength :CGFloat = 40
init(color: UIColor){
super.init(frame: CGRect.zero)
self.color = color
setupView()
setupCorners()
setupSizeConstraints()
}
func setupView(){
backgroundColor = UIColor.clear
layer.borderColor = color.cgColor
layer.borderWidth = 1
layer.masksToBounds = true
addSubview(imageOverlay)
imageOverlay.autoPinEdgesToSuperviewEdges()
imageOverlay.isUserInteractionEnabled = false
}
override func layoutSubviews() {
super.layoutSubviews()
// take superview bounds when exist only once and send to owner to layout
if maxEdges?.height == 0 || maxEdges == nil {
maxEdges = superview?.frame.size
self.sendBottomBoundsToOwner()
}
}
func setupSizeConstraints() {
widthConstraint = autoSetDimension(.width, toSize: defaultCropSize.width)
widthConstraint?.priority = UILayoutPriorityDefaultHigh
heightConstraint = autoSetDimension(.height, toSize: defaultCropSize.height)
heightConstraint?.priority = UILayoutPriorityDefaultHigh
}
func resetView(){
imageOverlay.image = nil
widthConstraint?.constant = defaultCropSize.width
heightConstraint?.constant = defaultCropSize.height
boxOverlay?.removeFromSuperview()
self.sendBottomBoundsToOwner()
}
func displayBoxes(_ boxes: [AnyObject], callback: @escaping () -> ()){
self.boxOverlay?.removeFromSuperview()
let boxOverlay = MPOverlayView()
addSubview(boxOverlay)
boxOverlay.autoPinEdgesToSuperviewEdges()
layoutIfNeeded()
boxOverlay.backgroundColor = UIColor.clear
boxOverlay.isUserInteractionEnabled = false
boxOverlay.displayBoxes(boxes, completionCallback: callback)
boxOverlay.isHidden = false
boxOverlay.setNeedsDisplay()
self.boxOverlay = boxOverlay
}
func setupCorners(){
//Create corner views, defined by the edges they stick to, and the direction of the lines
let topLeft = addControlToCornerWithEdges([.top, .left], lineDirections: [.down, .right])
let topRight = addControlToCornerWithEdges([.top, .right], lineDirections: [.down, .left])
let bottomLeft = addControlToCornerWithEdges([.bottom, .left], lineDirections: [.up, .right])
let bottomRight = addControlToCornerWithEdges([.bottom, .right], lineDirections: [.up, .left])
let corners = [topLeft, topRight, bottomLeft, bottomRight]
for corner in corners {
handleMovementForCorner(corner)
}
}
//Stick the corner to the edges in pinEdges, tell the corners how to draw themselves
func addControlToCornerWithEdges(_ pinEdges: [ALEdge], lineDirections: [LineDirection]) -> CropControlCorner {
let controlCorner = CropControlCorner(lineDirections: lineDirections, color: color)
addSubview(controlCorner)
for edge in pinEdges {
controlCorner.autoPinEdge(toSuperviewEdge: edge, withInset: -cornerLength)
}
//We double the corner length for the width, as the corner view is a box surrounding the corner
controlCorner.autoSetDimensions(to: CGSize(width: cornerLength * 2, height: cornerLength * 2))
return controlCorner
}
func handleMovementForCorner(_ corner: CropControlCorner) {
let rec = UIPanGestureRecognizer()
rec.addTarget(self, action: #selector(cornerMoved))
rec.delegate = self
corner.addGestureRecognizer(rec)
}
func cornerMoved(_ gestureRecogniser: UIPanGestureRecognizer){
if let corner = gestureRecogniser.view as? CropControlCorner {
let viewCenter = CGPoint(x: frame.width/2, y: frame.height/2)
let touchCenter = gestureRecogniser.location(in: self)
//Store the initial offset of the touch, so we can get delta's later
if gestureRecogniser.state == .began {
let offsetX = corner.center.x - touchCenter.x
let offsetY = corner.center.y - touchCenter.y
initialTouchOffset = CGPoint(x: offsetX, y: offsetY)
resetView()
}
//Set the width + height of the view based on the distance of the corner from the center
guard let maxEdges = self.maxEdges else { return }
let newCalculatedWidthValue = 2 * abs(touchCenter.x - viewCenter.x + initialTouchOffset.x)
let maxWidthValue = maxEdges.width
widthConstraint?.constant = max(min(newCalculatedWidthValue, maxWidthValue),cornerLength * 1.5)
let newCalculatedHeightValue = 2 * abs(touchCenter.y - viewCenter.y + initialTouchOffset.y)
let maxHeightValue = maxEdges.height - (cornersBorderMovement.top + cornersBorderMovement.bottom)
heightConstraint?.constant = max(min(newCalculatedHeightValue, maxHeightValue), cornerLength * 1.5)
self.sendBottomBoundsToOwner()
//Let the owner know something happened
self.panStateCallback?(gestureRecogniser.state)
}
}
private func sendBottomBoundsToOwner() {
guard let maxEdges = self.maxEdges else { return }
let bottomPoint = CGPoint(x: self.center.x, y: maxEdges.height - (maxEdges.height - heightConstraint!.constant) / 2)
self.cropFrameDidChangedCallback?(bottomPoint)
}
//Much of the corner control view is outside the bounds of this view,
//We override hitTest to allow all of the view to recieve touches
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
for subView in subviews {
let subViewPoint = subView.convert(point, from: self)
if subView.point(inside: subViewPoint, with: event) && subView.isUserInteractionEnabled {
return subView.hitTest(subViewPoint, with: event)
}
}
return nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CropControl: UIGestureRecognizerDelegate {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return self.isUserInteractionEnabled
}
}
| mit | a53abb85550360ec9d213680f347d98d | 38.265625 | 124 | 0.652739 | 5.022652 | false | false | false | false |
connienguyen/volunteers-iOS | VOLA/VOLA/ViewModels/EventsViewModel.swift | 1 | 2403 | //
// EventsViewModel.swift
// VOLA
//
// Created by Connie Nguyen on 7/20/17.
// Copyright © 2017 Systers-Opensource. All rights reserved.
//
import Foundation
import PromiseKit
/// Protocol for views displaying changes on EventsViewModel
protocol EventsViewModelDelegate: class {
/// Reload view displaying data from EventsViewModel to reflect changes to viewmodel data
func reloadEventsView()
}
/**
ViewModel for view controllers that display information from an array of Events
(e.g. EventTableViewController, MapViewController)
*/
class EventsViewModel {
private var _eventTableType: EventTableType
private var _events: [Event] = []
weak var delegate: EventsViewModelDelegate?
/// Publically accessible array of event models
var events: [Event] {
return _events
}
/// Length of events array (for use with table views)
var eventCount: Int {
return _events.count
}
/// Initialize view model and retrieve available events
init(_ tableType: EventTableType) {
_eventTableType = tableType
retrieveEvents()
}
/**
Find event in data array given eventID if it exists
- Parameters:
- eventID: eventID of Event to retrieve as a String
- Returns: Event with matching eventID if it exists, otherwise nil
*/
func event(with eventID: String) -> Event? {
return _events.first(where: { String($0.eventID) == eventID })
}
/**
Find event given index
- Parameters:
- index: Array index for Event in array
- Returns: Event in data array given an index
*/
func event(at index: Int) -> Event {
return _events[index]
}
/**
Reload events array with data from eTouches API and call reloadViewCallback
*/
func retrieveEvents() {
var eventsPromise: Promise<[Event]>
switch _eventTableType {
case .calendar:
eventsPromise = FirebaseDataManager.shared.getRegisteredEvents()
case .home:
eventsPromise = FirebaseDataManager.shared.getAvailableEvents()
}
eventsPromise
.then { (events) -> Void in
self._events = events
self.delegate?.reloadEventsView()
}.catch { error in
Logger.error(error)
}
}
}
| gpl-2.0 | 808505f3a08c5ba50af57024ceb55088 | 27.258824 | 93 | 0.625729 | 4.775348 | false | false | false | false |
jshultz/ios9-swift2-advanced-seque | advanced-seque/AppDelegate.swift | 1 | 6118 | //
// AppDelegate.swift
// advanced-seque
//
// Created by Jason Shultz on 10/15/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Open-Sky-Media--LLC.advanced_seque" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("advanced_seque", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | c71ce785dffdaa32889b7166b49f7d22 | 54.108108 | 291 | 0.719797 | 5.870441 | false | false | false | false |
oz-swu/studyIOS | studyIOS/studyIOS/Classes/Main/View/PageContentView.swift | 1 | 4661 | //
// PageContentView.swift
// studyIOS
//
// Created by musou on 18/06/2017.
// Copyright © 2017 musou. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView: PageContentView, progress: CGFloat, source: Int, target: Int);
}
private let ContentCellId = "ContentCellId";
class PageContentView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
open var childVcs : [UIViewController];
open weak var parentViewController: UIViewController?;
weak var delegate: PageContentViewDelegate?;
open var doDelegate : Bool = true;
open lazy var collectionView: UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout();
layout.itemSize = (self?.bounds.size)!;
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
layout.scrollDirection = .horizontal;
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout);
collectionView.showsHorizontalScrollIndicator = false;
collectionView.isPagingEnabled = true;
collectionView.bounces = false;
collectionView.dataSource = self;
collectionView.delegate = self;
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellId)
return collectionView;
}();
open var startDragX : CGFloat = 0;
// MRAK:- init
init(frame: CGRect, childVcs: [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs;
self.parentViewController = parentViewController;
super.init(frame: frame);
setupUI();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
open func setupUI() {
for childVc in childVcs {
parentViewController?.addChildViewController(childVc);
}
addSubview(collectionView);
collectionView.frame = bounds;
}
}
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellId, for: indexPath);
for view in cell.contentView.subviews {
view.removeFromSuperview();
}
let childVc = childVcs[indexPath.item];
childVc.view.frame = cell.contentView.bounds;
cell.contentView.addSubview(childVc.view);
return cell;
}
}
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startDragX = scrollView.contentOffset.x;
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (doDelegate) {
var progress : CGFloat = 0;
var sourceIndex : Int = 0;
var targetIndex : Int = 0;
let currentDragX = scrollView.contentOffset.x;
let scrollViewW = scrollView.bounds.width;
sourceIndex = Int(startDragX / scrollViewW);
if (currentDragX > startDragX) {
targetIndex = sourceIndex + 1;
progress = currentDragX / scrollViewW - CGFloat(sourceIndex);
} else if (currentDragX < startDragX) {
targetIndex = sourceIndex - 1;
progress = CGFloat(sourceIndex) - currentDragX / scrollViewW;
} else {
targetIndex = sourceIndex;
progress = 0;
}
// print("progress:", progress, " sourceIndex:", sourceIndex, " targetIndex:", targetIndex);
delegate?.pageContentView(contentView: self, progress: progress, source: sourceIndex, target: targetIndex);
}
}
}
extension PageContentView {
func setCurrentIndex(currentIndex : Int) {
doDelegate = false;
let offsetX = CGFloat(currentIndex) * collectionView.frame.width;
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false);
doDelegate = true;
}
}
| mit | 03c666e6b1d51b2085d3bbb74a0ced0b | 31.587413 | 121 | 0.63691 | 5.521327 | false | false | false | false |
karstengresch/rw_studies | Apprentice/Checklists10/Checklists10/Checklists10/DataModel10.swift | 1 | 2677 | //
// DataModel10.swift
// Checklists10
//
// Created by Karsten Gresch on 11.04.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import Foundation
class DataModel10 {
var checklist10s = [Checklist10]()
var indexOfSelectedChecklist10: Int {
get {
return UserDefaults.standard.integer(forKey: "Checklist10Index")
}
set {
UserDefaults.standard.set(newValue, forKey: "Checklist10Index")
}
}
init() {
loadChecklist10s()
registerDefaults()
handleFirstTime()
}
// Utility methods
func documentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func dataFilePath() -> URL {
return documentsDirectory().appendingPathComponent("Checklist10.plist")
}
func saveChecklist10s() {
print("saveChecklist10s called")
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(checklist10s, forKey: "Checklist10s")
archiver.finishEncoding()
data.write(to: dataFilePath(), atomically: true)
}
func loadChecklist10s() {
let path = dataFilePath()
print("loadChecklist10s called for \(path)")
if let data = try? Data(contentsOf: path) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
checklist10s = unarchiver.decodeObject(forKey: "Checklist10s") as! [Checklist10]
unarchiver.finishDecoding()
sortChecklist10s()
}
}
func registerDefaults() {
let dictionary: [String: Any] = ["Checklist10Index": -1,
"FirstTime": true,
"Checklist10ItemId": 0 ]
UserDefaults.standard.register(defaults: dictionary)
}
func handleFirstTime() {
let userDefaults = UserDefaults.standard
let isFirstTime = userDefaults.bool(forKey: "FirstTime")
if isFirstTime {
let firstChecklist10 = Checklist10(name: "List")
checklist10s.append(firstChecklist10)
indexOfSelectedChecklist10 = 0
userDefaults.set(false, forKey: "FirstTime")
userDefaults.synchronize()
}
}
func sortChecklist10s() {
checklist10s.sort(by: { checklist101, checklist102 in return checklist101.name.localizedStandardCompare(checklist102.name) == .orderedAscending })
}
class func nextChecklist10ItemId() -> Int {
let userDefaults = UserDefaults.standard
let checklist10ItemId = userDefaults.integer(forKey: "Checklist10ItemId")
userDefaults.set(checklist10ItemId + 1, forKey: "Checklist10ItemId")
userDefaults.synchronize()
return checklist10ItemId
}
}
| unlicense | 71d8fda27577c5f9aa0fd2f0b7aba240 | 26.875 | 150 | 0.672646 | 4.474916 | false | false | false | false |
joerocca/GitHawk | Pods/Tabman/Sources/Tabman/TabmanBar/Behaviors/Activists/AutoHideBarBehaviorActivist.swift | 1 | 906 | //
// AutoHideBarBehaviorActivist.swift
// Tabman
//
// Created by Merrick Sapsford on 21/11/2017.
// Copyright © 2017 UI At Six. All rights reserved.
//
import Foundation
class AutoHideBarBehaviorActivist: BarBehaviorActivist {
// MARK: Properties
private var autoHideBehavior: TabmanBar.Behavior.AutoHiding? {
if case .autoHide(let behavior) = self.behavior {
return behavior
}
return nil
}
// MARK: Lifecycle
override func update() {
super.update()
guard let behavior = self.autoHideBehavior else {
return
}
switch behavior {
case .always:
bar?.isHidden = true
case .withOneItem:
bar?.isHidden = bar?.items?.count == 1
default:
bar?.isHidden = false
}
}
}
| mit | 27859e103a953097253379f7ade9b718 | 20.547619 | 66 | 0.544751 | 4.73822 | false | false | false | false |
bignerdranch/CoreDataStack | Tests/CoreDataStackTVTests.swift | 1 | 1377 | //
// CoreDataStackTVTests.swift
// CoreDataStackTVTests
//
// Created by Robert Edwards on 12/17/15.
// Copyright © 2015-2016 Big Nerd Ranch. All rights reserved.
//
import XCTest
@testable import CoreDataStack
class CoreDataStackTVTests: TempDirectoryTestCase {
var inMemoryStack: CoreDataStack!
var sqlStack: CoreDataStack!
override func setUp() {
super.setUp()
let modelName = "Sample"
do {
inMemoryStack = try CoreDataStack.constructInMemoryStack(modelName: modelName, in: unitTestBundle)
} catch {
failingOn(error)
}
guard let tempStoreURL = tempStoreURL else {
XCTFail("Temp Dir not created")
return
}
weak var ex1 = expectation(description: "SQLite Setup")
CoreDataStack.constructSQLiteStack(modelName: modelName, in: unitTestBundle, at: tempStoreURL) { result in
switch result {
case .success(let stack):
self.sqlStack = stack
case .failure(let error):
self.failingOn(error)
}
ex1?.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
func testInMemoryInitialization() {
XCTAssertNotNil(inMemoryStack)
}
func testSQLiteInitialization() {
XCTAssertNotNil(sqlStack)
}
}
| mit | 6819726e458fc14fe80ccbdb08249fa1 | 24.481481 | 114 | 0.617733 | 4.794425 | false | true | false | false |
apple/swift-nio-extras | Sources/NIOSOCKS/State/ClientStateMachine.swift | 1 | 5104 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
private enum ClientState: Hashable {
case inactive
case waitingForClientGreeting
case waitingForAuthenticationMethod(ClientGreeting)
case waitingForClientRequest
case waitingForServerResponse(SOCKSRequest)
case active
case error
}
enum ClientAction: Hashable {
case waitForMoreData
case sendGreeting
case sendRequest
case proxyEstablished
}
struct ClientStateMachine {
private var state: ClientState
var proxyEstablished: Bool {
switch self.state {
case .active:
return true
case .error, .inactive, .waitingForAuthenticationMethod, .waitingForClientGreeting, .waitingForClientRequest, .waitingForServerResponse:
return false
}
}
var shouldBeginHandshake: Bool {
switch self.state {
case .inactive:
return true
case .active, .error, .waitingForAuthenticationMethod, .waitingForClientGreeting, .waitingForClientRequest, .waitingForServerResponse:
return false
}
}
init() {
self.state = .inactive
}
}
// MARK: - Incoming
extension ClientStateMachine {
mutating func receiveBuffer(_ buffer: inout ByteBuffer) throws -> ClientAction {
do {
switch self.state {
case .waitingForAuthenticationMethod(let greeting):
guard let action = try self.handleSelectedAuthenticationMethod(&buffer, greeting: greeting) else {
return .waitForMoreData
}
return action
case .waitingForServerResponse(let request):
guard let action = try self.handleServerResponse(&buffer, request: request) else {
return .waitForMoreData
}
return action
case .active, .error, .inactive, .waitingForClientGreeting, .waitingForClientRequest:
throw SOCKSError.UnexpectedRead()
}
} catch {
self.state = .error
throw error
}
}
mutating func handleSelectedAuthenticationMethod(_ buffer: inout ByteBuffer, greeting: ClientGreeting) throws -> ClientAction? {
return try buffer.parseUnwindingIfNeeded { buffer -> ClientAction? in
guard let selected = try buffer.readMethodSelection() else {
return nil
}
guard greeting.methods.contains(selected.method) else {
throw SOCKSError.InvalidAuthenticationSelection(selection: selected.method)
}
// we don't current support any form of authentication
return self.authenticate(&buffer, method: selected.method)
}
}
mutating func handleServerResponse(_ buffer: inout ByteBuffer, request: SOCKSRequest) throws -> ClientAction? {
return try buffer.parseUnwindingIfNeeded { buffer -> ClientAction? in
guard let response = try buffer.readServerResponse() else {
return nil
}
guard response.reply == .succeeded else {
throw SOCKSError.ConnectionFailed(reply: response.reply)
}
self.state = .active
return .proxyEstablished
}
}
mutating func authenticate(_ buffer: inout ByteBuffer, method: AuthenticationMethod) -> ClientAction {
precondition(method == .noneRequired, "No authentication mechanism is supported. Use .noneRequired only.")
// we don't currently support any authentication
// so assume all is fine, and instruct the client
// to send the request
self.state = .waitingForClientRequest
return .sendRequest
}
}
// MARK: - Outgoing
extension ClientStateMachine {
mutating func connectionEstablished() throws -> ClientAction {
guard self.state == .inactive else {
throw SOCKSError.InvalidClientState()
}
self.state = .waitingForClientGreeting
return .sendGreeting
}
mutating func sendClientGreeting(_ greeting: ClientGreeting) throws {
guard self.state == .waitingForClientGreeting else {
throw SOCKSError.InvalidClientState()
}
self.state = .waitingForAuthenticationMethod(greeting)
}
mutating func sendClientRequest(_ request: SOCKSRequest) throws {
guard self.state == .waitingForClientRequest else {
throw SOCKSError.InvalidClientState()
}
self.state = .waitingForServerResponse(request)
}
}
| apache-2.0 | e72ca63a309cf16d932be23f4c680a00 | 32.801325 | 144 | 0.617163 | 5.470525 | false | false | false | false |
uShip/iOSIdeaFlow | IdeaFlow/NSDate+IsInDay.swift | 1 | 2734 | //
// NSDate+IsInDay.swift
// IdeaFlow
//
// Created by Matt Hayes on 8/15/15.
// Copyright (c) 2015 uShip. All rights reserved.
//
import Foundation
extension NSDate
{
func midnight() -> NSDate?
{
let dayComponents = self.dayComponents()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let midnightComponents = NSDateComponents()
midnightComponents.second = 0
midnightComponents.minute = 0
midnightComponents.hour = 0
midnightComponents.day = dayComponents.day
midnightComponents.month = dayComponents.month
midnightComponents.year = dayComponents.year
return calendar?.dateFromComponents(midnightComponents)
}
func oneSecondBeforeMidnight() -> NSDate?
{
let todayComponents = self.dayComponents()
let comps = NSDateComponents()
comps.year = todayComponents.year
comps.month = todayComponents.month
comps.day = todayComponents.day
comps.hour = 23
comps.minute = 59
comps.second = 59
return NSCalendar.currentCalendar().dateFromComponents(comps)
}
func dateOffsetBy(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> NSDate?
{
let deltaComps = NSDateComponents()
deltaComps.year = years
deltaComps.month = months
deltaComps.day = days
deltaComps.hour = hours
deltaComps.minute = minutes
deltaComps.second = seconds
let offsetDate = NSCalendar.currentCalendar().dateByAddingComponents(deltaComps, toDate: self, options: NSCalendarOptions(rawValue: 0))
return offsetDate
}
func dayComponents() -> (day: Int, month: Int, year: Int, hour: Int, minute: Int, second: Int)
{
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar?.components([.Day, .Month, .Year, .Hour, .Minute, .Second], fromDate: self)
let day = Int(dateComponents?.day ?? 0)
let month = Int(dateComponents?.month ?? 0)
let year = Int(dateComponents?.year ?? 0)
let hour = Int(dateComponents?.hour ?? 0)
let minute = Int(dateComponents?.minute ?? 0)
let second = Int(dateComponents?.second ?? 0)
return (day, month, year, hour, minute, second)
}
func isInDay(otherDate: NSDate) -> Bool
{
let myDay = dayComponents()
let otherDay = otherDate.dayComponents()
return (myDay.day == otherDay.day) &&
(myDay.month == otherDay.month) &&
(myDay.year == otherDay.year)
}
} | gpl-3.0 | 3765aafbfa68ac3c4cfd870dcebe20a4 | 33.620253 | 143 | 0.627652 | 4.594958 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftDemo/Pods/SwiftyAttributes/SwiftyAttributes/Sources/common/Attribute+Sequence.swift | 1 | 1933 | //
// AttributeConversions.swift
// SwiftyAttributes
//
// Created by Eddie Kaiger on 11/23/16.
// Copyright © 2016 Eddie Kaiger. All rights reserved.
//
/**
An extension on dictionaries that allows us to convert a Foundation-based dictionary of attributes to an array of `Attribute`s.
A Sequence with an iterator of (String, Any) is equivalent to [String: Any]
This is a simple syntactic workaround since we can't write "extension Dictionary where Key == String". Thanks Swift :)
*/
#if swift(>=4.0)
extension Dictionary where Key == NSAttributedStringKey {
/// Returns an array of `Attribute`s converted from the dictionary of attributes. Use this whenever you want to convert [NSAttributeStringKey: Any] to [Attribute].
public var swiftyAttributes: [Attribute] {
return map(Attribute.init)
}
}
#else
extension Sequence where Iterator.Element == (key: String, value: Any) {
/// Returns an array of `Attribute`s converted from the dictionary of attributes. Use this whenever you want to convert [String: Any] to [Attribute].
public var swiftyAttributes: [Attribute] {
return flatMap { name, value in
if let attrName = AttributeName(rawValue: name) {
return Attribute(name: attrName, foundationValue: value)
} else {
return nil
}
}
}
}
#endif
extension Sequence where Iterator.Element == Attribute {
/// Returns the attribute dictionary required by Foundation's API for attributed strings. Use this whenever you need to convert [Attribute] to [String: Any].
public var foundationAttributes: [StringKey: Any] {
return reduce([StringKey: Any]()) { dictionary, attribute in
var dict = dictionary
dict[attribute.keyName] = attribute.foundationValue
return dict
}
}
}
| apache-2.0 | a8d9b181af85ac1219be9b3825206b49 | 36.153846 | 171 | 0.655797 | 4.794045 | false | false | false | false |
codefellows/sea-b23-iOS | Pinchot/Pinchot/AppDelegate.swift | 1 | 3331 | //
// AppDelegate.swift
// Pinchot
//
// Created by Andrew Shepard on 10/21/14.
// Copyright (c) 2014 Andrew Shepard. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UINavigationControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Find the nav controller in the view controller stack
// and set ourselves as the delegate
let navController = self.window!.rootViewController as UINavigationController
navController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// This is called whenever during all navigation operations
// Only return a custom animator for two view controller types
if let mainViewController = fromVC as? ViewController {
let animator = ShowImageAnimator()
animator.origin = mainViewController.origin
return animator
}
else if let imageViewController = fromVC as? ImageViewController {
let animator = HideImageAnimator()
animator.origin = imageViewController.reverseOrigin
return animator
}
// All other types use default transition
return nil
}
}
| mit | 36338cb7257caf4b465aee3d6eb91b94 | 46.585714 | 285 | 0.727709 | 6.145756 | false | false | false | false |
googleprojectzero/fuzzilli | Tests/FuzzilliTests/ProgramBuilderTest.swift | 1 | 52904 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import Fuzzilli
class ProgramBuilderTests: XCTestCase {
// Verify that program building doesn't crash and always produce valid programs.
func testBuilding() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
let N = 100
var sumOfProgramSizes = 0
for _ in 0..<100 {
b.build(n: N)
let program = b.finalize()
sumOfProgramSizes += program.size
// Add to corpus since build() does splicing as well
fuzzer.corpus.add(program, ProgramAspects(outcome: .succeeded))
// We'll have generated at least N instructions, probably more.
XCTAssertGreaterThanOrEqual(program.size, N)
}
// On average, we should generate between n and 2x n instructions.
let averageSize = sumOfProgramSizes / 100
XCTAssertLessThanOrEqual(averageSize, 2*N)
}
func testShapeOfGeneratedCode1() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
let simpleGenerator = CodeGenerator("SimpleGenerator") { b in
b.loadInt(Int64.random(in: 0..<100))
}
fuzzer.codeGenerators = WeightedList<CodeGenerator>([
(simpleGenerator, 1),
])
for _ in 0..<10 {
b.build(n: 100, by: .runningGenerators)
let program = b.finalize()
// In this case, the size of the generated program must be exactly the requested size.
XCTAssertEqual(program.size, 100)
}
}
func testShapeOfGeneratedCode2() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.minRecursiveBudgetRelativeToParentBudget = 0.25
b.maxRecursiveBudgetRelativeToParentBudget = 0.25
let simpleGenerator = CodeGenerator("SimpleGenerator") { b in
b.loadInt(Int64.random(in: 0..<100))
}
let recursiveGenerator = RecursiveCodeGenerator("RecursiveGenerator") { b in
b.buildRepeat(n: 5) { _ in
b.buildRecursive()
}
}
fuzzer.codeGenerators = WeightedList<CodeGenerator>([
(simpleGenerator, 3),
(recursiveGenerator, 1),
])
for _ in 0..<10 {
b.build(n: 100, by: .runningGenerators)
let program = b.finalize()
// Uncomment to see the "shape" of generated programs on the console.
//print(FuzzILLifter().lift(program))
// The size may be larger, but only roughly by 100 * 0.25 + 100 * 0.25**2 + 100 * 0.25**3 ... (each block may overshoot its budget by roughly the maximum recursive block size).
XCTAssertLessThan(program.size, 150)
}
}
func testTypeInstantiation() {
let env = JavaScriptEnvironment(additionalBuiltins: [:], additionalObjectGroups: [])
let fuzzer = makeMockFuzzer(environment: env)
let b = fuzzer.makeBuilder()
for _ in 0..<10 {
let t = ProgramTemplate.generateType(forFuzzer: fuzzer)
// generateVariable must be able to generate every type produced by generateType
let _ = b.generateVariable(ofType: t)
}
}
func testVariableReuse() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
let foo = b.loadBuiltin("foo")
let foo2 = b.reuseOrLoadBuiltin("foo")
XCTAssertEqual(foo, foo2)
let bar = b.reuseOrLoadBuiltin("bar")
XCTAssertNotEqual(foo, bar) // Different builtin
b.reassign(foo, to: b.loadBuiltin("baz"))
let foo3 = b.reuseOrLoadBuiltin("foo")
XCTAssertNotEqual(foo, foo3) // Variable was reassigned
let float = b.loadFloat(13.37)
var floatOutOfScope: Variable? = nil
b.buildPlainFunction(with: b.generateFunctionParameters()) { _ in
let int = b.loadInt(42)
let int2 = b.reuseOrLoadInt(42)
XCTAssertEqual(int, int2)
b.unary(.PostInc, int)
let int3 = b.reuseOrLoadInt(42)
XCTAssertNotEqual(int, int3) // Variable was reassigned
let float2 = b.reuseOrLoadFloat(13.37)
XCTAssertEqual(float, float2)
floatOutOfScope = b.loadFloat(4.2)
}
let float3 = b.reuseOrLoadFloat(4.2)
XCTAssertNotEqual(floatOutOfScope!, float3) // Variable went out of scope
}
func testVarRetrievalFromInnermostScope() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.blockStatement {
b.blockStatement {
b.blockStatement {
let innermostVar = b.loadInt(1)
XCTAssertEqual(b.randVar(), innermostVar)
XCTAssertEqual(b.randVarInternal(excludeInnermostScope: true), nil)
}
}
}
}
func testVarRetrievalFromOuterScope() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.blockStatement {
b.blockStatement {
let outerScopeVar = b.loadFloat(13.37)
b.blockStatement {
let _ = b.loadInt(100)
XCTAssertEqual(b.randVar(excludeInnermostScope: true), outerScopeVar)
}
}
}
}
func testRandVarInternal() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.blockStatement {
let var1 = b.loadString("HelloWorld")
XCTAssertEqual(b.randVarInternal(filter: { $0 == var1 }), var1)
b.blockStatement {
let var2 = b.loadFloat(13.37)
XCTAssertEqual(b.randVarInternal(filter: { $0 == var2 }), var2)
b.blockStatement {
let var3 = b.loadInt(100)
XCTAssertEqual(b.randVarInternal(filter: { $0 == var3 }), var3)
}
}
}
}
func testRandVarInternalFromOuterScope() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
let var0 = b.loadInt(1337)
b.blockStatement {
let var1 = b.loadString("HelloWorld")
XCTAssertEqual(b.randVarInternal(filter: { $0 == var0 }, excludeInnermostScope : true), var0)
b.blockStatement {
let var2 = b.loadFloat(13.37)
XCTAssertEqual(b.randVarInternal(filter: { $0 == var1 }, excludeInnermostScope : true), var1)
b.blockStatement {
let _ = b.loadInt(100)
XCTAssertEqual(b.randVarInternal(filter: { $0 == var2 }, excludeInnermostScope : true), var2)
}
}
}
}
func testBasicSplicing1() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let i1 = b.loadInt(0x41)
var i2 = b.loadInt(0x42)
let cond = b.compare(i1, with: i2, using: .lessThan)
b.buildIfElse(cond, ifBody: {
let String = b.loadBuiltin("String")
splicePoint = b.indexOfNextInstruction()
b.callMethod("fromCharCode", on: String, withArgs: [i1])
b.callMethod("fromCharCode", on: String, withArgs: [i2])
}, elseBody: {
b.binary(i1, i2, with: .Add)
})
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
i2 = b.loadInt(0x41)
let String = b.loadBuiltin("String")
b.callMethod("fromCharCode", on: String, withArgs: [i2])
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testBasicSplicing2() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
var i = b.loadInt(42)
b.buildDoWhileLoop(i, .lessThan, b.loadInt(44)) {
b.unary(.PostInc, i)
}
b.loadFloat(13.37)
var arr = b.createArray(with: [i, i, i])
b.loadProperty("length", of: arr)
splicePoint = b.indexOfNextInstruction()
b.callMethod("pop", on: arr, withArgs: [])
let original = b.finalize()
//
// Actual Program (1)
//
b.probabilityOfIncludingAnInstructionThatMayMutateARequiredVariable = 0.0
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual1 = b.finalize()
//
// Expected Program (1)
//
i = b.loadInt(42)
arr = b.createArray(with: [i, i, i])
b.callMethod("pop", on: arr, withArgs: [])
let expected1 = b.finalize()
XCTAssertEqual(expected1, actual1)
//
// Actual Program (2)
//
b.probabilityOfIncludingAnInstructionThatMayMutateARequiredVariable = 1.0
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual2 = b.finalize()
//
// Expected Program (2)
//
i = b.loadInt(42)
b.buildDoWhileLoop(i, .lessThan, b.loadInt(44)) {
b.unary(.PostInc, i)
}
arr = b.createArray(with: [i, i, i])
b.callMethod("pop", on: arr, withArgs: [])
let expected2 = b.finalize()
XCTAssertEqual(expected2, actual2)
}
func testBasicSplicing3() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
var i = b.loadInt(42)
var f = b.loadFloat(13.37)
var f2 = b.loadFloat(133.7)
let o = b.createObject(with: ["f": f])
b.storeProperty(f2, as: "f", on: o)
b.buildWhileLoop(i, .lessThan, b.loadInt(100)) {
b.binary(f, f2, with: .Add)
}
b.loadProperty("f", of: o)
let original = b.finalize()
//
// Actual Program
//
let idx = original.code.lastInstruction.index - 1 // Splice at EndWhileLoop
XCTAssert(original.code[idx].op is EndWhileLoop)
b.splice(from: original, at: idx)
let actual = b.finalize()
//
// Expected Program
//
i = b.loadInt(42)
f = b.loadFloat(13.37)
f2 = b.loadFloat(133.7)
b.buildWhileLoop(i, .lessThan, b.loadInt(100)) {
// If a block is spliced, its entire body is copied as well
b.binary(f, f2, with: .Add)
}
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testBasicSplicing4() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let f1 = b.buildPlainFunction(with: .parameters(n: 1)) { args1 in
let f2 = b.buildPlainFunction(with: .parameters(n: 1)) { args2 in
let s = b.binary(args1[0], args2[0], with: .Add)
b.doReturn(s)
}
let one = b.loadInt(1)
let r = b.callFunction(f2, withArgs: args1 + [one])
b.doReturn(r)
}
let zero = b.loadInt(0)
splicePoint = b.indexOfNextInstruction()
b.callFunction(f1, withArgs: [zero])
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
XCTAssertEqual(original, actual)
}
func testBasicSplicing5() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
// The whole function is included due to the data dependencies on the parameters
let f = b.buildPlainFunction(with: .parameters(n: 3)) { args in
let t1 = b.binary(args[0], args[1], with: .Mul)
let t2 = b.binary(t1, args[2], with: .Add)
let print = b.loadBuiltin("print")
splicePoint = b.indexOfNextInstruction()
b.callFunction(print, withArgs: [t2])
}
let one = b.loadInt(1)
let two = b.loadInt(2)
let three = b.loadInt(3)
b.callFunction(f, withArgs: [one, two, three])
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
b.buildPlainFunction(with: .parameters(n: 3)) { args in
let t1 = b.binary(args[0], args[1], with: .Mul)
let t2 = b.binary(t1, args[2], with: .Add)
let print = b.loadBuiltin("print")
b.callFunction(print, withArgs: [t2])
}
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testBasicSplicing6() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
var n = b.loadInt(10)
var f = Variable(number: 1) // Need to declare this up front as the builder interface doesn't support recursive calls
// The whole function is included due to the recursive call
f = b.buildPlainFunction(with: .parameters(n: 0)) { _ in
b.buildIfElse(n, ifBody: {
b.unary(.PostDec, n)
let r = b.callFunction(f, withArgs: [])
let two = b.loadInt(2)
splicePoint = b.indexOfNextInstruction()
let v = b.binary(r, two, with: .Mul)
b.doReturn(v)
}, elseBody: {
let one = b.loadInt(1)
b.doReturn(one)
})
}
XCTAssertEqual(f.number, 1)
b.callFunction(f, withArgs: [])
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected program
//
n = b.loadInt(10)
f = Variable(number: 1)
f = b.buildPlainFunction(with: .parameters(n: 0)) { _ in
b.buildIfElse(n, ifBody: {
b.unary(.PostDec, n)
let r = b.callFunction(f, withArgs: [])
let two = b.loadInt(2)
splicePoint = b.indexOfNextInstruction()
let v = b.binary(r, two, with: .Mul)
b.doReturn(v)
}, elseBody: {
let one = b.loadInt(1)
b.doReturn(one)
})
}
XCTAssertEqual(f.number, 1)
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testBasicSplicing7() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
b.buildAsyncFunction(with: .parameters(n: 0)) { _ in
let promise = b.loadBuiltin("ThePromise")
splicePoint = b.indexOfNextInstruction()
b.await(promise)
}
let original = b.finalize()
//
// Actual Program
//
// This should fail: we cannot splice the Await as it required .async context.
XCTAssertFalse(b.splice(from: original, at: splicePoint, mergeDataFlow: false))
XCTAssertEqual(b.indexOfNextInstruction(), 0)
b.buildAsyncFunction(with: .parameters(n: 1)) { args in
// This should work however.
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
}
let actual = b.finalize()
//
// Expected Program
//
b.buildAsyncFunction(with: .parameters(n: 1)) { args in
let promise = b.loadBuiltin("ThePromise")
b.await(promise)
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testBasicSplicing8() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let promise = b.loadBuiltin("ThePromise")
let f = b.buildAsyncFunction(with: .parameters(n: 0)) { _ in
let v = b.await(promise)
let zero = b.loadInt(0)
let c = b.compare(v, with: zero, using: .notEqual)
b.buildIfElse(c, ifBody: {
splicePoint = b.indexOfNextInstruction()
b.unary(.PostDec, v)
}, elseBody: {})
}
b.callFunction(f, withArgs: [])
let original = b.finalize()
//
// Actual Program
//
XCTAssertFalse(b.splice(from: original, at: splicePoint, mergeDataFlow: false))
b.buildAsyncFunction(with: .parameters(n: 2)) { _ in
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
}
let actual = b.finalize()
//
// Expected Program
//
b.buildAsyncFunction(with: .parameters(n: 2)) { _ in
let promise = b.loadBuiltin("ThePromise")
let v = b.await(promise)
b.unary(.PostDec, v)
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testBasicSplicing9() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
let s1 = b.loadString("foo")
b.buildTryCatchFinally(tryBody: {
let s2 = b.loadString("bar")
splicePoint = b.indexOfNextInstruction()
let s3 = b.binary(s1, s2, with: .Add)
b.yield(s3)
}, catchBody: { e in
b.yield(e)
})
let s4 = b.loadString("baz")
b.yield(s4)
}
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
let s1 = b.loadString("foo")
let s2 = b.loadString("bar")
b.binary(s1, s2, with: .Add)
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testBasicSplicing10() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let foo = b.loadString("foo")
let bar = b.loadString("bar")
let baz = b.loadString("baz")
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
b.yield(foo)
b.buildTryCatchFinally(tryBody: {
b.throwException(bar)
}, catchBody: { e in
splicePoint = b.indexOfNextInstruction()
b.yield(e)
})
b.yield(baz)
}
let original = b.finalize()
//
// Actual Program
//
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
b.yield(b.loadInt(1337))
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
b.yield(b.loadInt(1338))
}
let actual = b.finalize()
//
// Expected Program
//
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
b.yield(b.loadInt(1337))
let bar = b.loadString("bar")
b.buildTryCatchFinally(tryBody: {
b.throwException(bar)
}, catchBody: { e in
splicePoint = b.indexOfNextInstruction()
b.yield(e)
})
b.yield(b.loadInt(1338))
}
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testBasicSplicing11() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
// This entire function will be included due to data dependencies on its parameter.
b.buildPlainFunction(with: .parameters(n: 1)) { args in
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
let i = b.loadInt(0)
b.buildWhileLoop(i, .lessThan, b.loadInt(100)) {
splicePoint = b.indexOfNextInstruction()
b.buildIfElse(args[0], ifBody: {
b.yield(i)
}, elseBody: {
b.loopContinue()
})
b.unary(.PostInc, i)
}
}
}
let original = b.finalize()
//
// Actual Program
//
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
b.yield(b.loadInt(1337))
let i = b.loadInt(100)
b.buildWhileLoop(i, .greaterThan, b.loadInt(0)) {
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
b.unary(.PostDec, i)
}
b.yield(b.loadInt(1338))
}
let actual = b.finalize()
//
// Expected Program
//
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
b.yield(b.loadInt(1337))
let i = b.loadInt(100)
b.buildWhileLoop(i, .greaterThan, b.loadInt(0)) {
b.buildPlainFunction(with: .parameters(n: 1)) { args in
b.buildGeneratorFunction(with: .parameters(n: 0)) { _ in
let i = b.loadInt(0)
b.buildWhileLoop(i, .lessThan, b.loadInt(100)) {
splicePoint = b.indexOfNextInstruction()
b.buildIfElse(args[0], ifBody: {
b.yield(i)
}, elseBody: {
b.loopContinue()
})
b.unary(.PostInc, i)
}
}
}
b.unary(.PostDec, i)
}
b.yield(b.loadInt(1338))
}
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testDataflowSplicing1() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let p = b.loadBuiltin("ThePromise")
let f = b.buildAsyncFunction(with: .parameters(n: 0)) { args in
let v = b.await(p)
let print = b.loadBuiltin("print")
splicePoint = b.indexOfNextInstruction()
// We can only splice this if we replace |v| with another variable in the host program
b.callFunction(print, withArgs: [v])
}
b.callFunction(f, withArgs: [])
let original = b.finalize()
//
// Result Program
//
b.loadInt(1337)
b.loadString("Foobar")
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
let result = b.finalize()
XCTAssertFalse(result.code.contains(where: { $0.op is Await }))
XCTAssert(result.code.contains(where: { $0.op is CallFunction }))
}
func testDataflowSplicing2() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let f = b.buildPlainFunction(with: .parameters(n: 3)) { args in
let t1 = b.binary(args[0], args[1], with: .Add)
splicePoint = b.indexOfNextInstruction()
let t2 = b.binary(t1, args[2], with: .Add)
b.doReturn(t2)
}
var s1 = b.loadString("Foo")
var s2 = b.loadString("Bar")
var s3 = b.loadString("Baz")
b.callFunction(f, withArgs: [s1, s2, s3])
let original = b.finalize()
//
// Result Program
//
s1 = b.loadString("A")
s2 = b.loadString("B")
s3 = b.loadString("C")
b.splice(from: original, at: splicePoint, mergeDataFlow: true)
let result = b.finalize()
// Either the BeginPlainFunction has been omitted (in which case the parameter usages must have been remapped to an existing variable), or the BeginPlainFunction is included and none of the parameter usages have been remapped.
let didSpliceFunction = result.code.contains(where: { $0.op is BeginPlainFunction })
let existingVariables = [s1, s2, s3]
if didSpliceFunction {
for instr in result.code where instr.op is BinaryOperation {
XCTAssert(instr.inputs.allSatisfy({ !existingVariables.contains($0) }))
}
}
}
func testDataflowSplicing3() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let v = b.loadInt(42)
let name = b.loadString("foo")
let obj = b.createObject(with: [:])
splicePoint = b.indexOfNextInstruction()
b.storeComputedProperty(v, as: name, on: obj)
let original = b.finalize()
// If we set the probability of remapping a variables outputs during splicing to 100% we expect
// the slices to just contain a single instruction.
XCTAssertGreaterThan(b.probabilityOfRemappingAnInstructionsOutputsDuringSplicing, 0.0)
b.probabilityOfRemappingAnInstructionsOutputsDuringSplicing = 1.0
b.loadInt(1337)
b.loadString("bar")
b.createObject(with: [:])
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
let result = b.finalize()
XCTAssertEqual(result.size, 4)
XCTAssert(result.code.lastInstruction.op is StoreComputedProperty)
}
func testDataflowSplicing4() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let f = b.buildPlainFunction(with: .parameters(n: 3)) { args in
let Array = b.loadBuiltin("Array")
splicePoint = b.indexOfNextInstruction()
b.callMethod("of", on: Array, withArgs: args)
}
let i1 = b.loadInt(42)
let i2 = b.loadInt(43)
let i3 = b.loadInt(44)
b.callFunction(f, withArgs: [i1, i2, i3])
let original = b.finalize()
// When splicing from the method call, we expect to omit the function definition in many cases and
// instead remap the parameters to existing variables in the host program. Otherwise, we'd end up
// with a function that's never called.
// To test this reliably, we set the probability of remapping inner outputs to 100% but also check
// that it is reasonably high by default.
XCTAssertGreaterThanOrEqual(b.probabilityOfRemappingAnInstructionsInnerOutputsDuringSplicing, 0.5)
b.probabilityOfRemappingAnInstructionsInnerOutputsDuringSplicing = 1.0
b.loadString("Foo")
b.loadString("Bar")
b.loadString("Baz")
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
let result = b.finalize()
XCTAssert(result.code.contains(where: { $0.op is CallMethod }))
XCTAssertFalse(result.code.contains(where: { $0.op is BeginPlainFunction }))
}
func testDataflowSplicing5() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
var f = Variable(number: 0)
f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let n = args[0]
let zero = b.loadInt(0)
let one = b.loadInt(1)
let c = b.compare(n, with: zero, using: .greaterThan)
b.buildIfElse(c, ifBody: {
let nMinusOne = b.binary(n, one, with: .Sub)
let t = b.callFunction(f, withArgs: [nMinusOne])
splicePoint = b.indexOfNextInstruction()
let r = b.binary(n, t, with: .Mul)
b.doReturn(r)
}, elseBody: {
b.doReturn(one)
})
}
XCTAssertEqual(f.number, 0)
let i = b.loadInt(42)
b.callFunction(f, withArgs: [i])
let original = b.finalize()
//
// Actual Program
//
// Here, even if we replace all parameters of the function, we still include it due to the recursive call.
// In that case, we expect none of the parameter usages to have been replaced as the parameters are available.
b.probabilityOfRemappingAnInstructionsOutputsDuringSplicing = 0.0
b.probabilityOfRemappingAnInstructionsInnerOutputsDuringSplicing = 1.0
b.loadInt(1337)
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
let actual = b.finalize()
//
// Expected Program
//
b.loadInt(1337)
f = Variable(number: 1)
f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let n = args[0]
let zero = b.loadInt(0)
let one = b.loadInt(1)
let c = b.compare(n, with: zero, using: .greaterThan)
b.buildIfElse(c, ifBody: {
let nMinusOne = b.binary(n, one, with: .Sub)
let t = b.callFunction(f, withArgs: [nMinusOne])
splicePoint = b.indexOfNextInstruction()
let r = b.binary(n, t, with: .Mul)
b.doReturn(r)
}, elseBody: {
b.doReturn(one)
})
}
XCTAssertEqual(f.number, 1)
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testDataflowSplicing6() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
var f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let print = b.loadBuiltin("print")
b.callFunction(print, withArgs: args)
}
var n = b.loadInt(1337)
splicePoint = b.indexOfNextInstruction()
b.callFunction(f, withArgs: [n])
let original = b.finalize()
//
// Actual Program
//
b.probabilityOfRemappingAnInstructionsOutputsDuringSplicing = 1.0
b.buildPlainFunction(with: .parameters(n: 1)) { args in
let two = b.loadInt(2)
let r = b.binary(args[0], two, with: .Mul)
b.doReturn(r)
}
b.loadInt(42)
b.splice(from: original, at: splicePoint, mergeDataFlow: true)
let actual = b.finalize()
//
// Expected Program
//
// Variables should be remapped to variables of the same type (unless there are none).
f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let two = b.loadInt(2)
let r = b.binary(args[0], two, with: .Mul)
b.doReturn(r)
}
n = b.loadInt(42)
b.callFunction(f, withArgs: [n])
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testFunctionSplicing1() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
b.loadString("foo")
var i1 = b.loadInt(42)
var f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let i3 = b.binary(i1, args[0], with: .Add)
b.doReturn(i3)
}
b.loadString("bar")
var i2 = b.loadInt(43)
splicePoint = b.indexOfNextInstruction()
b.callFunction(f, withArgs: [i2])
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
i1 = b.loadInt(42)
f = b.buildPlainFunction(with: .parameters(n: 1)) { args in
let i3 = b.binary(i1, args[0], with: .Add)
b.doReturn(i3)
}
i2 = b.loadInt(43)
b.callFunction(f, withArgs: [i2])
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testFunctionSplicing2() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
var f = b.buildPlainFunction(with: .parameters(n: 2)) { args in
let step = b.loadInt(1)
splicePoint = b.indexOfNextInstruction()
b.buildForLoop(args[0], .lessThan, args[1], .Add, step) { _ in
b.loopBreak()
}
}
let arg1 = b.loadInt(42)
let arg2 = b.loadInt(43)
b.callFunction(f, withArgs: [arg1, arg2])
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
f = b.buildPlainFunction(with: .parameters(n: 2)) { args in
let step = b.loadInt(1)
splicePoint = b.indexOfNextInstruction()
b.buildForLoop(args[0], .lessThan, args[1], .Add, step) { _ in
b.loopBreak()
}
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testSplicingOfMutatingOperations() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertGreaterThan(b.probabilityOfIncludingAnInstructionThatMayMutateARequiredVariable, 0.0)
b.probabilityOfIncludingAnInstructionThatMayMutateARequiredVariable = 1.0
//
// Original Program
//
var f2 = b.loadFloat(13.37)
b.buildPlainFunction(with: .parameters(n: 1)) { args in
let i = b.loadInt(42)
let f = b.loadFloat(13.37)
b.reassign(f2, to: b.loadFloat(133.7))
let o = b.createObject(with: ["i": i, "f": f])
let o2 = b.createObject(with: ["i": i, "f": f2])
b.binary(i, args[0], with: .Add)
b.storeProperty(f2, as: "f", on: o)
let object = b.loadBuiltin("Object")
let descriptor = b.createObject(with: ["value": b.loadString("foobar")])
b.callMethod("defineProperty", on: object, withArgs: [o, b.loadString("s"), descriptor])
b.callMethod("defineProperty", on: object, withArgs: [o2, b.loadString("s"), descriptor])
let json = b.loadBuiltin("JSON")
b.callMethod("stringify", on: json, withArgs: [o])
}
let original = b.finalize()
//
// Actual Program
//
let idx = original.code.lastInstruction.index - 1
XCTAssert(original.code[idx].op is CallMethod)
b.splice(from: original, at: idx)
let actual = b.finalize()
//
// Expected Program
//
f2 = b.loadFloat(13.37)
let i = b.loadInt(42)
let f = b.loadFloat(13.37)
b.reassign(f2, to: b.loadFloat(133.7)) // (Possibly) mutating instruction must be included
let o = b.createObject(with: ["i": i, "f": f])
b.storeProperty(f2, as: "f", on: o) // (Possibly) mutating instruction must be included
let object = b.loadBuiltin("Object")
let descriptor = b.createObject(with: ["value": b.loadString("foobar")])
b.callMethod("defineProperty", on: object, withArgs: [o, b.loadString("s"), descriptor]) // (Possibly) mutating instruction must be included
let json = b.loadBuiltin("JSON")
b.callMethod("stringify", on: json, withArgs: [o])
let expected = b.finalize()
XCTAssertEqual(expected, actual)
}
func testClassSplicing() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
// We enable conservative mode to exercise the canMutate checks within the splice loop
b.mode = .conservative
//
// Original Program
//
var superclass = b.buildClass() { cls in
cls.defineConstructor(with: .parameters(n: 1)) { params in
}
cls.defineProperty("a")
cls.defineMethod("f", with: .parameters(n: 1)) { params in
b.doReturn(b.loadString("foobar"))
}
}
let _ = b.buildClass(withSuperclass: superclass) { cls in
cls.defineConstructor(with: .parameters(n: 1)) { params in
let v3 = b.loadInt(0)
let v4 = b.loadInt(2)
let v5 = b.loadInt(1)
b.buildForLoop(v3, .lessThan, v4, .Add, v5) { _ in
let v0 = b.loadInt(42)
let v1 = b.createObject(with: ["foo": v0])
splicePoint = b.indexOfNextInstruction()
b.callSuperConstructor(withArgs: [v1])
}
}
cls.defineProperty("b")
cls.defineMethod("g", with: .parameters(n: 1)) { params in
b.buildPlainFunction(with: .parameters(n: 0)) { _ in
}
}
}
let original = b.finalize()
//
// Actual Program
//
superclass = b.buildClass() { cls in
cls.defineConstructor(with: .parameters(n: 1)) { params in
}
}
b.buildClass(withSuperclass: superclass) { cls in
cls.defineConstructor(with: .parameters(n: 1)) { _ in
// Splicing at CallSuperConstructor
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
}
}
let actual = b.finalize()
//
// Expected Program
//
superclass = b.buildClass() { cls in
cls.defineConstructor(with: .parameters(n: 1)) { params in
}
}
b.buildClass(withSuperclass: superclass) { cls in
cls.defineConstructor(with: .parameters(n: 1)) { _ in
let v0 = b.loadInt(42)
let v1 = b.createObject(with: ["foo": v0])
b.callSuperConstructor(withArgs: [v1])
}
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testAsyncGeneratorSplicing() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
b.buildAsyncGeneratorFunction(with: .parameters(n: 2)) { _ in
let v3 = b.loadInt(0)
let v4 = b.loadInt(2)
let v5 = b.loadInt(1)
b.buildForLoop(v3, .lessThan, v4, .Add, v5) { _ in
let v0 = b.loadInt(42)
let _ = b.createObject(with: ["foo": v0])
splicePoint = b.indexOfNextInstruction()
b.await(v3)
let v8 = b.loadInt(1337)
b.yield(v8)
}
b.doReturn(v4)
}
let original = b.finalize()
//
// Actual Program
//
b.buildAsyncFunction(with: .parameters(n: 1)) { _ in
// Splicing at Await
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
}
let actual = b.finalize()
//
// Expected Program
//
b.buildAsyncFunction(with: .parameters(n: 1)) { _ in
let v0 = b.loadInt(0)
let _ = b.await(v0)
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testLoopSplicing1() {
var splicePoint = -1, invalidSplicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
//
// Original Program
//
let i = b.loadInt(0)
let end = b.loadInt(100)
b.buildWhileLoop(i, .lessThan, end) {
let i2 = b.loadInt(0)
let end2 = b.loadInt(10)
splicePoint = b.indexOfNextInstruction()
b.buildWhileLoop(i2, .lessThan, end2) {
let mid = b.binary(end2, b.loadInt(2), with: .Div)
let cond = b.compare(i2, with: mid, using: .greaterThan)
b.buildIfElse(cond, ifBody: {
b.loopContinue()
}, elseBody: {
invalidSplicePoint = b.indexOfNextInstruction()
b.loopBreak()
})
b.unary(.PostInc, i2)
}
b.unary(.PostInc, i)
}
let original = b.finalize()
//
// Actual Program
//
XCTAssertFalse(b.splice(from: original, at: invalidSplicePoint, mergeDataFlow: false))
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: false))
let actual = b.finalize()
//
// Expected Program
//
let i2 = b.loadInt(0)
let end2 = b.loadInt(10)
b.buildWhileLoop(i2, .lessThan, end2) {
let mid = b.binary(end2, b.loadInt(2), with: .Div)
let cond = b.compare(i2, with: mid, using: .greaterThan)
b.buildIfElse(cond, ifBody: {
b.loopContinue()
}, elseBody: {
b.loopBreak()
})
b.unary(.PostInc, i2)
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testLoopSplicing2() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
let start = b.loadInt(100)
let end = b.loadInt(100)
let i = b.dup(start)
// A loop is considered to mutate its run variable
b.buildWhileLoop(i, .lessThan, end) {
let two = b.loadInt(2)
splicePoint = b.indexOfNextInstruction()
b.binary(i, two, with: .Mod)
b.unary(.PostInc, i)
}
let original = b.finalize()
//
// Actual Program
//
b.probabilityOfIncludingAnInstructionThatMayMutateARequiredVariable = 1.0
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
XCTAssertEqual(actual, original)
}
func testForInSplicing() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
b.loadString("unused")
var i = b.loadInt(10)
var s = b.loadString("Bar")
var f = b.loadFloat(13.37)
var o1 = b.createObject(with: ["foo": i, "bar": s, "baz": f])
b.loadString("unused")
var o2 = b.createObject(with: [:])
b.buildForInLoop(o1) { p in
let i = b.loadInt(1337)
b.loadString("unusedButPartOfBody")
splicePoint = b.indexOfNextInstruction()
b.storeComputedProperty(i, as: p, on: o2)
}
b.loadString("unused")
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
i = b.loadInt(10)
s = b.loadString("Bar")
f = b.loadFloat(13.37)
o1 = b.createObject(with: ["foo": i, "bar": s, "baz": f])
o2 = b.createObject(with: [:])
b.buildForInLoop(o1) { p in
let i = b.loadInt(1337)
b.loadString("unusedButPartOfBody")
b.storeComputedProperty(i, as: p, on: o2)
}
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testTryCatchSplicing() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
let s = b.loadString("foo")
b.buildTryCatchFinally(tryBody: {
let v = b.loadString("bar")
b.throwException(v)
}, catchBody: { e in
splicePoint = b.indexOfNextInstruction()
b.reassign(e, to: s)
})
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
XCTAssertEqual(actual, original)
}
func testCodeStringSplicing() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
let v2 = b.loadInt(0)
let v3 = b.loadInt(10)
let v4 = b.loadInt(20)
b.buildForLoop(v2, .lessThan, v3, .Add, v4) { _ in
b.loadThis()
let code = b.buildCodeString() {
let i = b.loadInt(42)
let o = b.createObject(with: ["i": i])
let json = b.loadBuiltin("JSON")
b.callMethod("stringify", on: json, withArgs: [o])
}
let eval = b.reuseOrLoadBuiltin("eval")
splicePoint = b.indexOfNextInstruction()
b.callFunction(eval, withArgs: [code])
}
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
//
// Expected Program
//
let code = b.buildCodeString() {
let i = b.loadInt(42)
let o = b.createObject(with: ["i": i])
let json = b.loadBuiltin("JSON")
b.callMethod("stringify", on: json, withArgs: [o])
}
let eval = b.reuseOrLoadBuiltin("eval")
b.callFunction(eval, withArgs: [code])
let expected = b.finalize()
XCTAssertEqual(actual, expected)
}
func testSwitchBlockSplicing1() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
let i1 = b.loadInt(1)
let i2 = b.loadInt(2)
let i3 = b.loadInt(3)
let s = b.loadString("Foo")
splicePoint = b.indexOfNextInstruction()
b.buildSwitch(on: i1) { cases in
cases.add(i2) {
b.reassign(s, to: b.loadString("Bar"))
}
cases.add(i3) {
b.reassign(s, to: b.loadString("Baz"))
}
cases.addDefault {
b.reassign(s, to: b.loadString("Bla"))
}
}
let original = b.finalize()
//
// Actual Program
//
b.splice(from: original, at: splicePoint, mergeDataFlow: false)
let actual = b.finalize()
XCTAssertEqual(actual, original)
}
func testSwitchBlockSplicing2() {
var splicePoint = -1
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
b.mode = .conservative
//
// Original Program
//
var i1 = b.loadInt(1)
var i2 = b.loadInt(2)
var i3 = b.loadInt(3)
var s = b.loadString("Foo")
b.buildSwitch(on: i1) { cases in
cases.add(i2) {
b.reassign(s, to: b.loadString("Bar"))
}
cases.add(i3) {
b.reassign(s, to: b.loadString("Baz"))
}
cases.addDefault {
b.reassign(s, to: b.loadString("Bla"))
}
}
let original = b.finalize()
splicePoint = original.code.firstIndex(where: { $0.op is BeginSwitchCase })!
//
// Result Program
//
// Splicing a BeginSwitchCase is not possible here as we don't (yet) have a BeginSwitch.
XCTAssertFalse(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
i1 = b.loadInt(10)
i2 = b.loadInt(20)
i3 = b.loadInt(30)
s = b.loadString("Fizz")
b.buildSwitch(on: i1) { cases in
// Splicing will only be possible if we allow variables from the original program
// to be remapped to variables in the host program, so set mergeDataFlow to true.
XCTAssert(b.splice(from: original, at: splicePoint, mergeDataFlow: true))
XCTAssert(b.splice(from: original, mergeDataFlow: true))
}
let result = b.finalize()
XCTAssert(result.code.contains(where: { $0.op is BeginSwitchCase }))
// We must not splice default cases. Otherwise we may end up with multiple default cases, which is forbidden.
XCTAssertFalse(result.code.contains(where: { $0.op is BeginSwitchDefaultCase }))
}
}
extension ProgramBuilderTests {
static var allTests : [(String, (ProgramBuilderTests) -> () throws -> Void)] {
return [
("testBuilding", testBuilding),
("testShapeOfGeneratedCode1", testShapeOfGeneratedCode1),
("testShapeOfGeneratedCode2", testShapeOfGeneratedCode2),
("testTypeInstantiation", testTypeInstantiation),
("testVariableReuse", testVariableReuse),
("testVarRetrievalFromInnermostScope", testVarRetrievalFromInnermostScope),
("testVarRetrievalFromOuterScope", testVarRetrievalFromOuterScope),
("testRandVarInternal", testRandVarInternal),
("testRandVarInternalFromOuterScope", testRandVarInternalFromOuterScope),
("testBasicSplicing1", testBasicSplicing1),
("testBasicSplicing2", testBasicSplicing2),
("testBasicSplicing3", testBasicSplicing3),
("testBasicSplicing4", testBasicSplicing4),
("testBasicSplicing5", testBasicSplicing5),
("testBasicSplicing6", testBasicSplicing6),
("testBasicSplicing7", testBasicSplicing7),
("testBasicSplicing8", testBasicSplicing8),
("testBasicSplicing9", testBasicSplicing9),
("testBasicSplicing10", testBasicSplicing10),
("testBasicSplicing11", testBasicSplicing11),
("testDataflowSplicing1", testDataflowSplicing1),
("testDataflowSplicing2", testDataflowSplicing2),
("testDataflowSplicing3", testDataflowSplicing3),
("testDataflowSplicing4", testDataflowSplicing4),
("testDataflowSplicing5", testDataflowSplicing5),
("testDataflowSplicing6", testDataflowSplicing6),
("testFunctionSplicing1", testFunctionSplicing1),
("testFunctionSplicing2", testFunctionSplicing2),
("testSplicingOfMutatingOperations", testSplicingOfMutatingOperations),
("testClassSplicing", testClassSplicing),
("testAsyncGeneratorSplicing", testAsyncGeneratorSplicing),
("testLoopSplicing1", testLoopSplicing1),
("testLoopSplicing2", testLoopSplicing2),
("testForInSplicing", testForInSplicing),
("testTryCatchSplicing", testTryCatchSplicing),
("testCodeStringSplicing", testCodeStringSplicing),
("testSwitchBlockSplicing1", testSwitchBlockSplicing1),
("testSwitchBlockSplicing2", testSwitchBlockSplicing2),
]
}
}
| apache-2.0 | 98fa983035ea4cfafca4c9da15f14bee | 32.782886 | 234 | 0.541112 | 3.997884 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureWithdrawalLocks/Sources/FeatureWithdrawalLocksData/Repository/WithdrawalLocksRepository.swift | 1 | 2035 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import Combine
import DIKit
import Errors
import FeatureWithdrawalLocksDomain
import Foundation
final class WithdrawalLocksRepository: WithdrawalLocksRepositoryAPI {
private let client: WithdrawalLocksClientAPI
private let moneyValueFormatter: MoneyValueFormatterAPI
private let decodingDateFormatter = DateFormatter.sessionDateFormat
private let encodingDateFormatter = DateFormatter.long
init(
client: WithdrawalLocksClientAPI = resolve(),
moneyValueFormatter: MoneyValueFormatterAPI = resolve()
) {
self.client = client
self.moneyValueFormatter = moneyValueFormatter
}
func withdrawalLocks(
currencyCode: String
) -> AnyPublisher<WithdrawalLocks, Never> {
client.fetchWithdrawalLocks(currencyCode: currencyCode)
.ignoreFailure()
.map { [encodingDateFormatter, decodingDateFormatter, moneyValueFormatter] withdrawalLocks in
WithdrawalLocks(
items: withdrawalLocks.locks.compactMap { lock in
guard let fromDate = decodingDateFormatter.date(from: lock.expiresAt) else {
return nil
}
return .init(
date: encodingDateFormatter.string(
from: fromDate
),
amount: moneyValueFormatter.formatMoney(
amount: lock.amount.amount,
currency: lock.amount.currency
)
)
},
amount: moneyValueFormatter.formatMoney(
amount: withdrawalLocks.totalLocked.amount,
currency: withdrawalLocks.totalLocked.currency
)
)
}
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | eeb457d23cb016f71a36b2d13736e94e | 35.981818 | 105 | 0.574238 | 6.498403 | false | false | false | false |
bugcoding/macOSCalendar | MacCalendar/CalendarViewController.swift | 1 | 20092 | //
// CalendarViewController.swift
// MacCalendar
//
// Created by bugcode on 16/7/16.
// Copyright © 2016年 bugcode. All rights reserved.
//
import Cocoa
class CalendarViewController: NSWindowController, NSTextFieldDelegate {
// MARK: - Outlets define
// 周末二个标签
@IBOutlet weak var saturdayLabel: NSTextField!
@IBOutlet weak var sundayLabel: NSTextField!
// 右下角生肖图片
@IBOutlet weak var imageView: NSImageView!
@IBOutlet weak var poemLabel: NSTextField!
@IBOutlet weak var nextPoemLabel: NSTextField!
// 设置按钮
@IBOutlet weak var settingBtn: NSButton!
// 年和月上的箭头
@IBOutlet weak var nextYearBtn: NSButton!
@IBOutlet weak var lastYearBtn: NSButton!
@IBOutlet weak var nextMonthBtn: NSButton!
@IBOutlet weak var lastMonthBtn: NSButton!
// 顶部三个label
@IBOutlet weak var yearText: CalendarTextField!
@IBOutlet weak var monthText: CalendarTextField!
// 右侧显示区
@IBOutlet weak var dateDetailLabel: NSTextField!
@IBOutlet weak var dayLabel: NSTextField!
@IBOutlet weak var lunarDateLabel: NSTextField!
@IBOutlet weak var lunarYearLabel: NSTextField!
@IBOutlet weak var holidayLabel: NSTextField!
@IBOutlet weak var pinNote: NSTextField!
// 日历类实例
private var mCalendar: LunarCalendarUtils = LunarCalendarUtils()
private var mPreCalendar: LunarCalendarUtils = LunarCalendarUtils()
private var mNextCalendar: LunarCalendarUtils = LunarCalendarUtils()
private var mCurMonth: Int = 0
private var mCurDay: Int = 0
private var mCurYear: Int = 0
// 每个显示日期的单元格
private var cellBtns = [CalendarCellView]()
private var lastRowNum:Int = 0
private var lastPressBtn: CalendarCellView?
// 下一个节日的名字
@IBOutlet weak var nextHolidayTip: NSTextField!
@IBOutlet weak var nextHolidayDays: NSTextField!
override var windowNibName: NSNib.Name?{
return NSNib.Name("CalendarViewController")
}
// MARK: Button handler
@IBAction func settingHandler(_ sender: NSButton) {
//NSApp.terminate(self)
let menu = SettingMenu()
SettingMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender)
}
@IBAction func lastMonthHandler(_ sender: NSButton) {
var lastMonth = mCurMonth - 1
if lastMonth < 1 {
lastMonth = 12
mCurYear -= 1
}
setDate(year: mCurYear, month: lastMonth)
}
@IBAction func nextMonthHandler(_ sender: NSButton) {
var nextMonth = mCurMonth + 1
if nextMonth > 12 {
nextMonth = 1
mCurYear += 1
}
setDate(year: mCurYear, month: nextMonth)
}
@IBAction func nextYearHandler(_ sender: NSButton) {
let nextYear = mCurYear + 1
setDate(year: nextYear, month: mCurMonth)
}
@IBAction func lastYearHandler(_ sender: NSButton) {
let lastYear = mCurYear - 1
setDate(year: lastYear, month: mCurMonth)
}
@IBAction func returnToday(_ sender: NSButton) {
showToday()
}
// 响应NSTextField的回车事件
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(insertNewline(_:)) {
let inputStr = textView.string
let filterStr = inputStr.trimmingCharacters(in: .decimalDigits)
if filterStr.count > 0 {
// TODO: 提示
// 包含非数字
return false
}
// identifier 已定义在xib中
if control.identifier!.rawValue == "monthField" {
//print("month = \(inputStr)")
let monthNum = Int(inputStr)!
if monthNum < 1 || monthNum > 12 {
// TODO: 提示
return false
}
setDate(year: mCurYear, month: monthNum)
} else if control.identifier!.rawValue == "yearField" {
//print("year = \(textView.string!)")
let yearNum = Int(inputStr)!
if yearNum < CalendarConstant.GREGORIAN_CALENDAR_OPEN_YEAR || yearNum > 10000 {
// TODO: 提示
return false
}
setDate(year: yearNum, month: mCurMonth)
}
return true
}
return false
}
func getLunarDayName(dayInfo: DAY_INFO, cal: LunarCalendarUtils) -> String {
var lunarDayName = ""
if dayInfo.st != -1 {
lunarDayName = CalendarConstant.nameOfJieQi[dayInfo.st]
} else if dayInfo.mdayNo == 0 {
let chnMonthInfo = cal.getChnMonthInfo(month: dayInfo.mmonth)
if chnMonthInfo.isLeapMonth() {
lunarDayName += CalendarConstant.LEAP_YEAR_PREFIX
}
lunarDayName += CalendarConstant.nameOfChnMonth[chnMonthInfo.mInfo.mname - 1]
lunarDayName += (chnMonthInfo.mInfo.mdays == CalendarConstant.CHINESE_L_MONTH_DAYS) ? CalendarConstant.MONTH_NAME_1 : CalendarConstant.MONTH_NAME_2
} else {
lunarDayName += CalendarConstant.nameOfChnDay[dayInfo.mdayNo]
}
return lunarDayName
}
func showMonthPanel() {
let year = mCurYear
let month = mCurMonth
let utils = CalendarUtils.sharedInstance
let mi = mCalendar.getMonthInfo(month: mCurMonth)
// 根据日期字符串获取当前月共有多少天
let monthDays = mi.mInfo.days
// 显示上方二个区域的年份与月份信息
yearText.stringValue = String(mCurYear)
monthText.stringValue = String(mCurMonth)
// 上个月有多少天
var lastMonthDays = 0
if month == 1 {
lastMonthDays = utils.getDaysBy(year: year - 1, month: 12)
} else {
lastMonthDays = utils.getDaysBy(year: year, month: month - 1)
}
// 本月第一天与最后一天是周几
let weekDayOf1stDay = mi.mInfo.weekOf1stDay
//print("dateString = \(year)-\(month) weekOf1stDay = \(weekDayOf1stDay) weekOfLastDay = \(weekDayOfLastDay) monthDays = \(monthDays) ")
// 读取本地存储的颜色
var festivalColor = NSColor.black
if let data = UserDefaults.standard.value(forKey: SettingWindowController.FESTIVAL_COLOR_TAG) {
festivalColor = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! NSColor
}
// 读取本地记录的颜色信息
var holidayColor = NSColor.red
if let data = UserDefaults.standard.value(forKey: SettingWindowController.HOLIDAY_COLOR_TAG) {
holidayColor = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! NSColor
}
// 把空余不的cell行不显示,非本月天置灰
for (index, btn) in cellBtns.enumerated() {
btn.setBackGroundColor(bgColor: .white)
btn.isEnabled = true
btn.isHidden = false
if index < weekDayOf1stDay || index >= monthDays + weekDayOf1stDay {
// 前后二个月置灰,不可点击
btn.isEnabled = false
// 处理前后二个月的显示日期 (灰置部分)
if index < weekDayOf1stDay {
let day = lastMonthDays - weekDayOf1stDay + index + 1
var lastMonth = mCurMonth - 1
var calendar = mCalendar
if lastMonth < 1 {
lastMonth = 12
calendar = mPreCalendar
}
let (dayName, isFestival) = getMaxPriorityHolidayBy(month: lastMonth, day: day, cal: calendar)
var color = NSColor.black
if isFestival {
color = festivalColor
}
btn.setString(wzTime: CalendarUtils.WZDayTime(calendar.getCurrentYear(), lastMonth, day), topColor: NSColor.black.withAlphaComponent(0.5), bottomText: dayName, bottomColor: color.withAlphaComponent(0.5))
} else {
let day = index - monthDays - weekDayOf1stDay + 1
var nextMonth = mCurMonth + 1
var calendar = mCalendar
if nextMonth > 12 {
nextMonth = 1
calendar = mNextCalendar
}
let (dayName, isFestival) = getMaxPriorityHolidayBy(month: nextMonth, day: day, cal: calendar)
var color = NSColor.black
if isFestival {
color = festivalColor
}
btn.setString(wzTime: CalendarUtils.WZDayTime(calendar.getCurrentYear(), nextMonth, day), topColor: NSColor.black.withAlphaComponent(0.5), bottomText: dayName, bottomColor: color.withAlphaComponent(0.5))
}
} else {
if index == monthDays + weekDayOf1stDay - 1 {
// 当前cell在第几行
lastRowNum = Int((btn.mCellID - 1) / 7) + 1
}
let day = index - weekDayOf1stDay + 1
//btn.title = "\(index - weekDayOf1stDay + 1)"
let (dayName, isFestival) = getMaxPriorityHolidayBy(month: mCurMonth, day: day, cal: mCalendar)
let today = utils.getYMDTuppleBy(utils.getDateStringOfToday())
if today.day == day && today.month == mCurMonth && today.year == mCurYear {
btn.setBackGroundColor(bgColor: CalendarConstant.selectedDateColor)
lastPressBtn = btn
}
var color = NSColor.black
if isFestival {
color = festivalColor
}
btn.setString(wzTime: CalendarUtils.WZDayTime(mCurYear, mCurMonth, day), topColor: .black, bottomText: dayName, bottomColor: color)
// 处理周六日的日期颜色
if index % 7 == 6 || index % 7 == 0 {
if isFestival {
btn.setString(wzTime: CalendarUtils.WZDayTime(mCurYear, mCurMonth, day), topColor: holidayColor, bottomText: dayName, bottomColor: color)
} else {
btn.setString(wzTime: CalendarUtils.WZDayTime(mCurYear, mCurMonth, day), topColor: holidayColor, bottomText: dayName, bottomColor: holidayColor)
}
}
}
}
}
// 根据xib中的identifier获取对应的cell
func getButtonByIdentifier(_ id:String) -> NSView? {
for subView in (self.window?.contentView?.subviews[0].subviews)! {
if subView.identifier!.rawValue == id {
return subView
}
}
return nil
}
@objc func dateButtonHandler(_ sender:CalendarCellView){
// 245 173 108 浅绿色
if let tmp = lastPressBtn {
tmp.setBackGroundColor(bgColor: .white)
}
sender.setBackGroundColor(bgColor: CalendarConstant.selectedDateColor)
lastPressBtn = sender
mCurDay = sender.wzDay.day
showRightDetailInfo(wzTime: sender.wzDay)
}
func showHolidayCountDown(wzTime: CalendarUtils.WZDayTime){
let (holidayName, days) = CalendarUtils.sharedInstance.getNextHolidayBy(wzTime: wzTime)
nextHolidayTip.stringValue = "距离\(holidayName)"
nextHolidayDays.stringValue = "\(days)"
}
// 显示日历面板右侧详情
func showRightDetailInfo(wzTime: CalendarUtils.WZDayTime) {
// 获取每月第一天是周几
let curWeekDay = CalendarUtils.sharedInstance.getWeekDayBy(mCurYear, month: mCurMonth, day: mCurDay)
dateDetailLabel.stringValue = String(mCurYear) + "年" + String(mCurMonth) + "月" + String(mCurDay) + "日 星期" + CalendarConstant.WEEK_NAME_OF_CHINESE[curWeekDay]
dayLabel.stringValue = String(mCurDay)
// 右侧农历详情
showLunar()
// 显示假日信息
showHolidayInfo()
// 显示倒日
showHolidayCountDown(wzTime: wzTime)
// 当前日期如果有备注显示备注信息
let info = LocalDataManager.sharedInstance.getCurDateFlag(wzDay: wzTime)
showPinNote(info: info)
}
// 显示便签
func showPinNote(info: String) {
pinNote.isHidden = true
if info != "" {
pinNote.isHidden = false
pinNote.stringValue = info
}
}
func showLunar() {
var stems: Int = 0, branches: Int = 0, sbMonth:Int = 0, sbDay:Int = 0
let year = mCalendar.getCurrentYear()
mCalendar.getSpringBeginDay(month: &sbMonth, day: &sbDay)
let util = CalendarUtils.sharedInstance
var y = year
if mCurMonth < sbMonth {
y = year - 1
} else {
if mCurMonth == sbMonth && mCurDay < sbDay {
y = year - 1
}
}
util.calculateStemsBranches(year: y, stems: &stems, branches: &branches)
branches -= 1
let monthHeavenEarthy = util.getLunarMonthNameBy(calendar: mCalendar, month: mCurMonth, day: mCurDay)
let dayHeavenEarthy = util.getLunarDayNameBy(year: mCurYear, month: mCurMonth, day: mCurDay)
// 当前的农历年份
let lunarStr = "\(CalendarConstant.HEAVENLY_STEMS_NAME[stems - 1])\(CalendarConstant.EARTHY_BRANCHES_NAME[branches])【\(CalendarConstant.CHINESE_ZODIC_NAME[branches])】年"
lunarYearLabel.stringValue = lunarStr + monthHeavenEarthy.heaven + monthHeavenEarthy.earthy + "月" + dayHeavenEarthy.heaven + dayHeavenEarthy.earthy + "日"
imageView.image = NSImage(named: NSImage.Name(rawValue: CalendarConstant.CHINESE_ZODIC_PNG_NAME[branches]))
// poemLabel.stringValue = CalendarConstant.LAST_POEM[branches - 1]
// nextPoemLabel.stringValue = CalendarConstant.NEXT_POEM[branches - 1]
// 当前的农历日期
let mi = mCalendar.getMonthInfo(month: mCurMonth)
let dayInfo = mi.getDayInfo(day: mCurDay)
let chnMonthInfo = mCalendar.getChnMonthInfo(month: dayInfo.mmonth)
var lunarDayName = CalendarConstant.nameOfChnMonth[chnMonthInfo.mInfo.mname - 1] + "月"
if chnMonthInfo.isLeapMonth() {
lunarDayName = CalendarConstant.LEAP_YEAR_PREFIX + lunarDayName
}
let dayName = CalendarConstant.nameOfChnDay[dayInfo.mdayNo]
lunarDateLabel.stringValue = lunarDayName + dayName
}
// 显示节日信息
func showHolidayInfo(){
let holidayName = CalendarUtils.sharedInstance.getHolidayNameBy(month: mCurMonth, day: mCurDay)
holidayLabel.stringValue = holidayName
//农历节日
let mi = mCalendar.getMonthInfo(month: mCurMonth)
let dayInfo = mi.getDayInfo(day: mCurDay)
let chnMonthInfo = mCalendar.getChnMonthInfo(month: dayInfo.mmonth)
let festivalName = CalendarUtils.sharedInstance.getLunarFestivalNameBy(month: chnMonthInfo.mInfo.mname, day: dayInfo.mdayNo + 1)
var jieQiName = ""
if dayInfo.st != -1 {
jieQiName = CalendarConstant.nameOfJieQi[dayInfo.st]
}
holidayLabel.stringValue = jieQiName + " " + festivalName + " " + holidayName
}
// 获取当前日期的节日信息并返回优先在cell中显示的节日信息
func getMaxPriorityHolidayBy(month: Int, day: Int, cal: LunarCalendarUtils) -> (String, Bool){
var maxPriorityHolidayName = ""
var isFestvial = false
// 依次是 农历日期/节气,公历节日,农历节日
let mi = cal.getMonthInfo(month: month)
let dayInfo = mi.getDayInfo(day: day)
let chnMonthInfo = cal.getChnMonthInfo(month: dayInfo.mmonth)
// 农历日期/节气
maxPriorityHolidayName = getLunarDayName(dayInfo: dayInfo, cal: cal)
if dayInfo.st != -1 {
isFestvial = true
}
// 公历节日
let holidayName = CalendarUtils.sharedInstance.getHolidayNameBy(month: month, day: day)
if holidayName != "" && holidayName.count <= 4 {
maxPriorityHolidayName = holidayName
isFestvial = true
}
// 农历节日
let festivalName = CalendarUtils.sharedInstance.getLunarFestivalNameBy(month: chnMonthInfo.mInfo.mname, day: dayInfo.mdayNo + 1)
if festivalName != "" {
maxPriorityHolidayName = festivalName
isFestvial = true
}
return (maxPriorityHolidayName, isFestvial)
}
func setCurrenMonth(month: Int) {
if month >= 1 && month <= CalendarConstant.MONTHES_FOR_YEAR {
mCurMonth = month
showMonthPanel()
}
}
func setDate(year: Int, month: Int) {
mCurYear = year
let _ = mPreCalendar.setGeriYear(year: mCurYear - 1)
let _ = mNextCalendar.setGeriYear(year: mCurYear + 1)
if mCalendar.setGeriYear(year: year) {
setCurrenMonth(month: month)
}
}
// 显示今天
func showToday() {
let date = CalendarUtils.sharedInstance.getDateStringOfToday()
let dateTupple = CalendarUtils.sharedInstance.getYMDTuppleBy(date)
mCurDay = dateTupple.day
mCurYear = dateTupple.year
let _ = mPreCalendar.setGeriYear(year: mCurYear - 1)
let _ = mNextCalendar.setGeriYear(year: mCurYear + 1)
if mCalendar.setGeriYear(year: mCurYear) {
setCurrenMonth(month: dateTupple.month)
showRightDetailInfo(wzTime: CalendarUtils.WZDayTime(mCurYear, mCurMonth, mCurDay))
}
}
// 设置周六周日字的颜色
func setWeekendLabelColor() {
// 读取本地记录的颜色信息
var color = NSColor.red
if let data = UserDefaults.standard.value(forKey: SettingWindowController.HOLIDAY_COLOR_TAG) {
color = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! NSColor
}
saturdayLabel.textColor = color
sundayLabel.textColor = color
}
override func windowDidLoad() {
super.windowDidLoad()
LocalDataManager.sharedInstance.parseHoliday()
pinNote.layer?.cornerRadius = 5.5
pinNote.layer?.masksToBounds = true
// 背景透明,使用view设置圆角矩形
self.window?.backgroundColor = NSColor.clear
//self.blur(view: self.backView)
// 将所有cell加入数组管理,并加入回调逻辑
for i in 0 ... 5 {
for j in 0 ... 6 {
let intValue = (i * 7 + j + 1)
let id = "cell\(intValue)"
if let btn = self.getButtonByIdentifier(id) {
let cellBtn = btn as! CalendarCellView
cellBtn.target = self
cellBtn.action = #selector(CalendarViewController.dateButtonHandler(_:))
cellBtn.mCellID = intValue
cellBtns.append(cellBtn)
}
}
}
// 加载完窗口显示默认
showToday()
setWeekendLabelColor()
}
}
| gpl-2.0 | 42c02f4fdcfcbfa818a8adfa7fec3ff9 | 35.948077 | 223 | 0.57815 | 4.231006 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Utility/Kanvas/KanvasCameraCustomUI.swift | 1 | 9783 | import Foundation
import Kanvas
/// Contains custom colors and fonts for the KanvasCamera framework
public class KanvasCustomUI {
public static let shared = KanvasCustomUI()
private static let brightBlue = UIColor.muriel(color: MurielColor(name: .blue)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightPurple = UIColor.muriel(color: MurielColor(name: .purple)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightPink = UIColor.muriel(color: MurielColor(name: .pink)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightYellow = UIColor.muriel(color: MurielColor(name: .yellow)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightGreen = UIColor.muriel(color: MurielColor(name: .green)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightRed = UIColor.muriel(color: MurielColor(name: .red)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let brightOrange = UIColor.muriel(color: MurielColor(name: .orange)).color(for: UITraitCollection(userInterfaceStyle: .dark))
private static let white = UIColor.white
static private var firstPrimary: UIColor {
return KanvasCustomUI.primaryColors.first ?? UIColor.blue
}
static private var lastPrimary: UIColor {
return KanvasCustomUI.primaryColors.last ?? UIColor.green
}
private let pickerColors: [UIColor] = [KanvasCustomUI.firstPrimary] + KanvasCustomUI.primaryColors + [KanvasCustomUI.lastPrimary]
private let segmentColors: [UIColor] = KanvasCustomUI.primaryColors + KanvasCustomUI.primaryColors + [KanvasCustomUI.firstPrimary]
static private let primaryColors: [UIColor] = [.blue,
.purple,
.magenta,
.red,
.yellow,
.green]
private let backgroundColorCollection: [UIColor] = KanvasCustomUI.primaryColors
private let mangaColor: UIColor = brightPink
private let toonColor: UIColor = brightOrange
private let selectedColor = brightBlue // ColorPickerController:29
private let black25 = UIColor(white: 0, alpha: 0.25)
func cameraColors() -> KanvasColors {
let firstPrimary = KanvasCustomUI.primaryColors.first ?? .blue
return KanvasColors(
drawingDefaultColor: firstPrimary,
colorPickerColors: pickerColors,
selectedPickerColor: selectedColor,
timeSegmentColors: segmentColors,
backgroundColors: backgroundColorCollection,
strokeColor: firstPrimary,
sliderActiveColor: firstPrimary,
sliderOuterCircleColor: firstPrimary,
trimBackgroundColor: firstPrimary,
trashColor: Self.brightRed,
tooltipBackgroundColor: .systemRed,
closeButtonColor: black25,
primaryButtonBackgroundColor: Self.brightRed,
permissionsButtonColor: Self.brightBlue,
permissionsButtonAcceptedBackgroundColor: UIColor.muriel(color: MurielColor(name: .green, shade: .shade20)),
overlayColor: UIColor.muriel(color: MurielColor.gray),
filterColors: [
.manga: mangaColor,
.toon: toonColor,
])
}
private static let cameraPermissions = KanvasFonts.CameraPermissions(titleFont: UIFont.systemFont(ofSize: 26, weight: .medium), descriptionFont: UIFont.systemFont(ofSize: 16), buttonFont: UIFont.systemFont(ofSize: 16, weight: .medium))
private static let drawer = KanvasFonts.Drawer(textSelectedFont: UIFont.systemFont(ofSize: 14, weight: .medium), textUnselectedFont: UIFont.systemFont(ofSize: 14))
func cameraFonts() -> KanvasFonts {
let paddingAdjustment: (UIFont) -> KanvasFonts.Padding? = { font in
if font == UIFont.systemFont(ofSize: font.pointSize) {
return KanvasFonts.Padding(topMargin: 8.0,
leftMargin: 5.7,
extraVerticalPadding: 0.125 * font.pointSize,
extraHorizontalPadding: 0)
}
else {
return nil
}
}
let editorFonts: [UIFont] = [.libreBaskerville(fontSize: 20), .nunitoBold(fontSize: 24), .pacifico(fontSize: 24), .shrikhand(fontSize: 22), .spaceMonoBold(fontSize: 20), .oswaldUpper(fontSize: 22)]
return KanvasFonts(permissions: Self.cameraPermissions,
drawer: Self.drawer,
editorFonts: editorFonts,
optionSelectorCellFont: UIFont.systemFont(ofSize: 16, weight: .medium),
mediaClipsFont: UIFont.systemFont(ofSize: 9.5),
mediaClipsSmallFont: UIFont.systemFont(ofSize: 8),
modeButtonFont: UIFont.systemFont(ofSize: 18.5),
speedLabelFont: UIFont.systemFont(ofSize: 16, weight: .medium),
timeIndicatorFont: UIFont.systemFont(ofSize: 16, weight: .medium),
colorSelectorTooltipFont:
UIFont.systemFont(ofSize: 14),
modeSelectorTooltipFont: UIFont.systemFont(ofSize: 15),
postLabelFont: UIFont.systemFont(ofSize: 14, weight: .medium),
gifMakerRevertButtonFont: UIFont.systemFont(ofSize: 15, weight: .bold),
paddingAdjustment: paddingAdjustment
)
}
func cameraImages() -> KanvasImages {
return KanvasImages(confirmImage: UIImage(named: "stories-confirm-button"), editorConfirmImage: UIImage(named: "stories-confirm-button"), nextImage: UIImage(named: "stories-next-button"))
}
}
enum CustomKanvasFonts: CaseIterable {
case libreBaskerville
case nunitoBold
case pacifico
case oswaldUpper
case shrikhand
case spaceMonoBold
struct Shadow {
let radius: CGFloat
let offset: CGPoint
let color: UIColor
}
var name: String {
switch self {
case .libreBaskerville:
return "LibreBaskerville-Regular"
case .nunitoBold:
return "Nunito-Bold"
case .pacifico:
return "Pacifico-Regular"
case .oswaldUpper:
return "Oswald-Regular"
case .shrikhand:
return "Shrikhand-Regular"
case .spaceMonoBold:
return "SpaceMono-Bold"
}
}
var size: Int {
switch self {
case .libreBaskerville:
return 20
case .nunitoBold:
return 24
case .pacifico:
return 24
case .oswaldUpper:
return 22
case .shrikhand:
return 22
case .spaceMonoBold:
return 20
}
}
var shadow: Shadow? {
switch self {
case .libreBaskerville:
return nil
case .nunitoBold:
return Shadow(radius: 1, offset: CGPoint(x: 0, y: 2), color: UIColor.black.withAlphaComponent(75))
case .pacifico:
return Shadow(radius: 5, offset: .zero, color: UIColor.white.withAlphaComponent(50))
case .oswaldUpper:
return nil
case .shrikhand:
return Shadow(radius: 1, offset: CGPoint(x: 1, y: 2), color: UIColor.black.withAlphaComponent(75))
case .spaceMonoBold:
return nil
}
}
}
extension UIFont {
static func libreBaskerville(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "LibreBaskerville-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func nunitoBold(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Nunito-Bold", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func pacifico(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Pacifico-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func oswaldUpper(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Oswald-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func shrikhand(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "Shrikhand-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
static func spaceMonoBold(fontSize: CGFloat) -> UIFont {
let font = UIFont(name: "SpaceMono-Bold", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
return UIFontMetrics.default.scaledFont(for: font)
}
@objc func fontByAddingSymbolicTrait(_ trait: UIFontDescriptor.SymbolicTraits) -> UIFont {
let modifiedTraits = fontDescriptor.symbolicTraits.union(trait)
guard let modifiedDescriptor = fontDescriptor.withSymbolicTraits(modifiedTraits) else {
assertionFailure("Unable to created modified font descriptor by adding a symbolic trait.")
return self
}
return UIFont(descriptor: modifiedDescriptor, size: pointSize)
}
}
| gpl-2.0 | 8188c18f8f32e590d58cb6b5d6331c55 | 44.502326 | 239 | 0.630073 | 4.689837 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Extensions/NSAttributedStringKey+Conversion.swift | 2 | 1095 | import Foundation
import UIKit
// MARK: - NSAttributedStringKey Helpers
//
extension NSAttributedString.Key {
/// Converts a collection of NSAttributedString Attributes, with 'NSAttributedStringKey' instances as 'Keys', into an
/// equivalent collection that uses regular 'String' instances as keys.
///
static func convertToRaw(attributes: [NSAttributedString.Key: Any]) -> [String: Any] {
var output = [String: Any]()
for (key, value) in attributes {
output[key.rawValue] = value
}
return output
}
/// Converts a collection of NSAttributedString Attributes, with 'String' instances as 'Keys', into an equivalent
/// collection that uses the new 'NSAttributedStringKey' enum as keys.
///
static func convertFromRaw(attributes: [String: Any]) -> [NSAttributedString.Key: Any] {
var output = [NSAttributedString.Key: Any]()
for (key, value) in attributes {
let wrappedKey = NSAttributedString.Key(key)
output[wrappedKey] = value
}
return output
}
}
| gpl-2.0 | c01334630ad6a7823a9b3ddf5203fb5d | 31.205882 | 121 | 0.655708 | 4.910314 | false | false | false | false |
Poligun/NihonngoSwift | Nihonngo/SwipeableCell.swift | 1 | 3965 | //
// SwipeableCell.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/9.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class SwipeableCell: BaseCell {
var rightButtonWidth: CGFloat = 60.0
var swipeableContentView: UIView!
private var rightButtons = [UIButton]()
private var leadingConstraint: NSLayoutConstraint!
private var trailingConstraint: NSLayoutConstraint!
override class var defaultReuseIdentifier: String {
return "SwipeableCell"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
swipeableContentView = UIView(frame: CGRectMake(0, 0, 320, 80))
swipeableContentView.setTranslatesAutoresizingMaskIntoConstraints(false)
swipeableContentView.backgroundColor = UIColor.lightGrayColor()
contentView.addSubview(swipeableContentView)
leadingConstraint = NSLayoutConstraint(item: swipeableContentView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0)
trailingConstraint = NSLayoutConstraint(item: swipeableContentView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0)
contentView.addConstraint(leadingConstraint)
contentView.addConstraint(trailingConstraint)
contentView.addConstraint(NSLayoutConstraint(item: swipeableContentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: swipeableContentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "onPanGesture:")
panGestureRecognizer.cancelsTouchesInView = false
swipeableContentView.addGestureRecognizer(panGestureRecognizer)
addButton(title: "Delete", backgroundColor: UIColor.redColor(), action: nil)
}
func addButton(#title: String, backgroundColor: UIColor = UIColor.clearColor(), action: ((sender: AnyObject) -> Void)?) {
let button = UIButton()
button.titleLabel?.text = title
button.titleLabel?.textColor = UIColor.whiteColor()
button.backgroundColor = backgroundColor
button.addTarget(self, action: "", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(button)
contentView.addConstraints(NSLayoutConstraint.constraints(views: ["swipeable": swipeableContentView, "button": button], formats: "H:[swipeable]-[button(\(rightButtonWidth))]", "V:|-0-[button]-0-|"))
}
private var panStartingX: CGFloat = 0.0
func onPanGesture(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Began:
panStartingX = recognizer.translationInView(swipeableContentView).x
println("Starting: \(panStartingX)")
case .Changed:
let delta = panStartingX - recognizer.translationInView(swipeableContentView).x as CGFloat
println("Moved: \(delta)")
trailingConstraint.constant = recognizer.translationInView(swipeableContentView).x
recognizer.setTranslation(CGPointZero, inView: swipeableContentView)
case .Ended:
let endingX = recognizer.translationInView(swipeableContentView).x
println("Ending: \(endingX)")
default:
break
}
}
}
| mit | adebbe73ab2fe0dba5856706044285b7 | 46.178571 | 243 | 0.715367 | 5.428767 | false | false | false | false |
kasei/kineo | Tests/KineoTests/TurtleSerialization.swift | 1 | 5065 | import XCTest
import Kineo
import SPARQLSyntax
#if os(Linux)
extension TurtleSerializationTest {
static var allTests : [(String, (TurtleSerializationTest) -> () throws -> Void)] {
return [
("testTriples", testTriples),
("testTriplesOutputStream", testTriplesOutputStream),
("testTriplesResult", testTriplesResult),
("testEscaping", testEscaping),
("testGrouping", testGrouping),
]
}
}
#endif
class TurtleSerializationTest: XCTestCase {
var serializer : TurtleSerializer!
override func setUp() {
serializer = TurtleSerializer()
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 testTriples() {
let i = Term(iri: "http://example.org/食べる")
let b = Term(value: "b1", type: .blank)
let l = Term(value: "foo", type: .language("en-US"))
let d = Term(integer: 7)
let triple1 = Triple(subject: b, predicate: i, object: l)
let triple2 = Triple(subject: b, predicate: i, object: d)
guard let data = try? serializer.serialize([triple1, triple2]) else { XCTFail(); return }
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "_:b1 <http://example.org/食べる> \"foo\"@en-US, 7 .\n")
XCTAssert(true)
}
func testTriplesOutputStream() {
serializer.add(name: "食", for: "http://example.org/")
let i = Term(iri: "http://example.org/食べる")
let b = Term(value: "b1", type: .blank)
let l = Term(value: "foo", type: .language("en-US"))
let d = Term(integer: 7)
let triple1 = Triple(subject: b, predicate: i, object: l)
let triple2 = Triple(subject: b, predicate: i, object: d)
var string = ""
do {
try serializer.serialize([triple1, triple2], to: &string)
} catch {
XCTFail()
return
}
XCTAssertEqual(string, "@prefix 食: <http://example.org/> .\n\n_:b1 食:食べる \"foo\"@en-US, 7 .\n\n")
XCTAssert(true)
}
func testTriplesResult() {
let i = Term(iri: "http://example.org/食べる")
let b = Term(value: "b1", type: .blank)
let l = Term(value: "foo", type: .language("en-US"))
let d = Term(integer: 7)
let triple1 = Triple(subject: b, predicate: i, object: l)
let triple2 = Triple(subject: b, predicate: i, object: d)
let result : QueryResult<[SPARQLResultSolution<Term>], [Triple]> = .triples([triple1, triple2])
guard let data = try? serializer.serialize(result) else { XCTFail(); return }
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "_:b1 <http://example.org/食べる> \"foo\"@en-US, 7 .\n")
XCTAssert(true)
}
func testEscaping() {
let b = Term(value: "b1", type: .blank)
let i = Term(iri: "http://example.org/^foo")
let l = Term(string: "\n\"")
let triple = Triple(subject: b, predicate: i, object: l)
guard let data = try? serializer.serialize([triple]) else { XCTFail(); return }
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "_:b1 <http://example.org/\\u005Efoo> \"\\n\\\"\" .\n")
XCTAssert(true)
}
func testGrouping() {
let i1 = Term(iri: "http://example.org/i1")
let i2 = Term(iri: "http://example.org/i2")
let b = Term(value: "b1", type: .blank)
let d1 = Term(integer: 1)
let d2 = Term(integer: 2)
let triple1 = Triple(subject: b, predicate: i1, object: d1)
let triple2 = Triple(subject: b, predicate: i1, object: d2)
let triple3 = Triple(subject: b, predicate: i2, object: d1)
let triple4 = Triple(subject: b, predicate: i2, object: d2)
guard let data = try? serializer.serialize([triple1, triple4, triple2, triple3]) else { XCTFail(); return }
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "_:b1 <http://example.org/i1> 1, 2 ;\n\t<http://example.org/i2> 1, 2 .\n")
XCTAssert(true)
}
func testPrefixes() {
serializer.add(name: "ex", for: "http://example.org/")
let i1 = Term(iri: "http://example.org/i1")
let i2 = Term(iri: "http://example.org/foo/bar/123")
let b = Term(value: "b1", type: .blank)
let triple1 = Triple(subject: b, predicate: i1, object: i2)
guard let data = try? serializer.serialize([triple1]) else { XCTFail(); return }
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "@prefix ex: <http://example.org/> .\n\n_:b1 ex:i1 <http://example.org/foo/bar/123> .\n")
XCTAssert(true)
}
}
| mit | b57e7a7607524240af4e581af06e0119 | 40.172131 | 120 | 0.579733 | 3.547316 | false | true | false | false |
vashimbogom/ghrFinder | GithubLangF/app/Models/GitRepoIssue.swift | 1 | 2707 | //
// GitRepoIssue.swift
// GithubLangF
//
// Created by Jose Lopez on 2/17/16.
// Copyright © 2016 Jose Lopez. All rights reserved.
//
import UIKit
final class GitRepoIssue: ResponseObjectSerializable, ResponseCollectionSerializable {
let title: String
let userLogin: String
let user_avatar_url: String
let state: String
let issueId: UInt
let issueUrl: String
let number: UInt
let createdAt: NSDate
init?(response: NSHTTPURLResponse, representation: AnyObject) {
if let d = representation.valueForKeyPath("title") as? String {
self.title = d
} else {
self.title = ""
}
if let d = representation.valueForKeyPath("user.login") as? String {
self.userLogin = d
} else {
self.userLogin = ""
}
if let d = representation.valueForKeyPath("user.avatar_url") as? String {
self.user_avatar_url = d
} else {
self.user_avatar_url = ""
}
if let d = representation.valueForKeyPath("state") as? String {
self.state = d
} else {
self.state = ""
}
if let d = representation.valueForKeyPath("id") as? UInt {
self.issueId = d
} else {
self.issueId = 0
}
if let d = representation.valueForKeyPath("number") as? UInt {
self.number = d
} else {
self.number = 0
}
if let d = representation.valueForKeyPath("html_url") as? String {
self.issueUrl = d
} else {
self.issueUrl = ""
}
if let d = representation.valueForKeyPath("created_at") as? String {
let formater = NSDateFormatter()
formater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let date = formater.dateFromString(d) {
self.createdAt = date
}else {
self.createdAt = NSDate()
}
} else {
self.createdAt = NSDate()
}
}
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [GitRepoIssue] {
var issues: [GitRepoIssue] = []
if let representation = representation.valueForKeyPath("items") as? [[String: AnyObject]] {
for issueRepresentation in representation {
if let issue = GitRepoIssue(response: response, representation: issueRepresentation) {
issues.append(issue)
}
}
}
return issues
}
}
| mit | 1f18509c279df4001bb2977f962c8218 | 27.787234 | 111 | 0.528455 | 4.849462 | false | false | false | false |
wagnersouz4/replay | Replay/Replay/Source/ViewControllers/Movies/Details/MovieDetailsTableViewDelegateDataSource.swift | 1 | 3961 | //
// MovieDetailsTableDelegateDataSource.swift
// Replay
//
// Created by Wagner Souza on 6/05/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import UIKit
class MovieDetailsTableDelegateDataSource: NSObject {
fileprivate var movie: Movie?
fileprivate let view: UIView
fileprivate var collectionDelegateDataSource: MovieDetailsCollectionDelegateDataSource?
init(view: UIView) {
self.view = view
collectionDelegateDataSource = MovieDetailsCollectionDelegateDataSource(view: view)
}
func setMovie(_ movie: Movie) {
self.movie = movie
collectionDelegateDataSource?.setMovie(movie)
}
fileprivate var movieSubtitle: String {
guard let movie = movie else { return "" }
return MovieHelper.createSubtitleFor(movie)
}
}
extension MovieDetailsTableDelegateDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return (section == 3) ? "Videos" : nil
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (movie == nil) ? 0 : 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let movie = movie else { fatalError("Movie has not been initialized") }
switch indexPath.section {
/// Movie's Title
case 0:
let titleSubtitleCell: TitleSubTitleTableViewCell = tableView.dequeueReusableCell(
withIdentifier: TitleSubTitleTableViewCell.identifier, for: indexPath)
titleSubtitleCell.setup(title: movie.title, subtitle: movieSubtitle)
return titleSubtitleCell
/// Movie's backdrops
case 1:
let cell = GridTableViewCell(reuseIdentifier: GridTableViewCell.identifier, orientation: .landscape)
return cell
/// Movie's Overview
case 2:
let titleTextCell: TitleTextTableViewCell = tableView.dequeueReusableCell(
withIdentifier: TitleTextTableViewCell.identifier, for: indexPath)
titleTextCell.setup(title: "Overview", text: movie.overview)
return titleTextCell
/// Movie's Videos
case 3:
let cell = GridTableViewCell(reuseIdentifier: GridTableViewCell.identifier, orientation: .landscape)
return cell
default:
return UITableViewCell()
}
}
}
extension MovieDetailsTableDelegateDataSource: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
switch indexPath.section {
case 1, 3:
let gridCell = cell.asGridTableViewCell()
if let delegateDataSource = collectionDelegateDataSource {
gridCell.setCollectionView(dataSource: delegateDataSource,
delegate: delegateDataSource,
section: indexPath.section)
}
default:
break
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 1, 3:
return GridHelper(view).landscapeLayout.tableViewHeight
default:
return UITableViewAutomaticDimension
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return GridHelper(view).landscapeLayout.tableViewHeight
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if section == 3, let headerView = view as? UITableViewHeaderFooterView {
headerView.setupWithDefaults()
}
}
}
| mit | bf9963e4b001c4ac7cbf8418eef31ca1 | 34.044248 | 112 | 0.657576 | 5.633001 | false | false | false | false |
menlatin/jalapeno | digeocache/mobile/iOS/diGeo/diGeo/DrawerController/DrawerController.swift | 1 | 74238 | // Copyright (c) 2014 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension UIViewController {
var evo_drawerController: DrawerController? {
var parentViewController = self.parentViewController
while parentViewController != nil {
if parentViewController!.isKindOfClass(DrawerController) {
return parentViewController as? DrawerController
}
parentViewController = parentViewController!.parentViewController
}
return nil
}
var evo_visibleDrawerFrame: CGRect {
if let drawerController = self.evo_drawerController {
if drawerController.leftDrawerViewController != nil {
if self == drawerController.leftDrawerViewController || self.navigationController == drawerController.leftDrawerViewController {
var rect = drawerController.view.bounds
rect.size.width = drawerController.maximumLeftDrawerWidth
return rect
}
}
if drawerController.rightDrawerViewController != nil {
if self == drawerController.rightDrawerViewController || self.navigationController == drawerController.rightDrawerViewController {
var rect = drawerController.view.bounds
rect.size.width = drawerController.maximumRightDrawerWidth
rect.origin.x = CGRectGetWidth(drawerController.view.bounds) - rect.size.width
return rect
}
}
}
return CGRectNull
}
}
private func bounceKeyFrameAnimationForDistanceOnView(distance: CGFloat, view: UIView) -> CAKeyframeAnimation {
let factors: [CGFloat] = [0, 32, 60, 83, 100, 114, 124, 128, 128, 124, 114, 100, 83, 60, 32, 0, 24, 42, 54, 62, 64, 62, 54, 42, 24, 0, 18, 28, 32, 28, 18, 0]
let values = factors.map({ x in
NSNumber(float: Float(x / 128 * distance + CGRectGetMidX(view.bounds)))
})
let animation = CAKeyframeAnimation(keyPath: "position.x")
animation.repeatCount = 1
animation.duration = 0.8
animation.fillMode = kCAFillModeForwards
animation.values = values
animation.removedOnCompletion = true
animation.autoreverses = false
return animation
}
public enum DrawerSide: Int {
case None
case Left
case Right
}
public struct OpenDrawerGestureMode : RawOptionSetType, BooleanType {
private var value: UInt = 0
public init(nilLiteral: ()) { self.value = 0 }
public init(rawValue: UInt) { self.value = rawValue }
public var boolValue: Bool { return value != 0 }
public static func fromMask(raw: UInt) -> OpenDrawerGestureMode { return self(rawValue: raw) }
public static func fromRaw(raw: UInt) -> OpenDrawerGestureMode? { return self(rawValue: raw) }
public var rawValue: UInt { return self.value }
public static var allZeros: OpenDrawerGestureMode { return self(rawValue: 0) }
public static func convertFromNilLiteral() -> OpenDrawerGestureMode { return self(rawValue: 0) }
static var None: OpenDrawerGestureMode { return self(rawValue: 0b0000) }
static var PanningNavigationBar: OpenDrawerGestureMode { return self(rawValue: 0b0001) }
static var PanningCenterView: OpenDrawerGestureMode { return self(rawValue: 0b0010) }
static var BezelPanningCenterView: OpenDrawerGestureMode { return self(rawValue: 0b0100) }
static var Custom: OpenDrawerGestureMode { return self(rawValue: 0b1000) }
static var All: OpenDrawerGestureMode { return self(rawValue: 0b1111) }
}
public struct CloseDrawerGestureMode : RawOptionSetType, BooleanType {
private var value: UInt = 0
public init(nilLiteral: ()) { self.value = 0 }
public init(rawValue: UInt) { self.value = rawValue }
public var boolValue: Bool { return value != 0 }
public static func fromMask(raw: UInt) -> CloseDrawerGestureMode { return self(rawValue: raw) }
public static func fromRaw(raw: UInt) -> CloseDrawerGestureMode? { return self(rawValue: raw) }
public var rawValue: UInt { return self.value }
public static var allZeros: CloseDrawerGestureMode { return self(rawValue: 0) }
public static func convertFromNilLiteral() -> CloseDrawerGestureMode { return self(rawValue: 0) }
static var None: CloseDrawerGestureMode { return self(rawValue: 0b0000000) }
static var PanningNavigationBar: CloseDrawerGestureMode { return self(rawValue: 0b0000001) }
static var PanningCenterView: CloseDrawerGestureMode { return self(rawValue: 0b0000010) }
static var BezelPanningCenterView: CloseDrawerGestureMode { return self(rawValue: 0b0000100) }
static var TapNavigationBar: CloseDrawerGestureMode { return self(rawValue: 0b0001000) }
static var TapCenterView: CloseDrawerGestureMode { return self(rawValue: 0b0010000) }
static var PanningDrawerView: CloseDrawerGestureMode { return self(rawValue: 0b0100000) }
static var Custom: CloseDrawerGestureMode { return self(rawValue: 0b1000000) }
static var All: CloseDrawerGestureMode { return self(rawValue: 0b1111111) }
}
public enum DrawerOpenCenterInteractionMode: Int {
case None
case Full
case NavigationBarOnly
}
private let DrawerDefaultWidth: CGFloat = 280.0
private let DrawerDefaultAnimationVelocity: CGFloat = 840.0
private let DrawerDefaultFullAnimationDelay: NSTimeInterval = 0.10
private let DrawerDefaultBounceDistance: CGFloat = 50.0
private let DrawerMinimumAnimationDuration: CGFloat = 0.15
private let DrawerDefaultDampingFactor: CGFloat = 1.0
private let DrawerDefaultShadowRadius: CGFloat = 10.0
private let DrawerDefaultShadowOpacity: Float = 0.8
private let DrawerPanVelocityXAnimationThreshold: CGFloat = 200.0
/** The amount of overshoot that is panned linearly. The remaining percentage nonlinearly asymptotes to the max percentage. */
private let DrawerOvershootLinearRangePercentage: CGFloat = 0.75
/** The percent of the possible overshoot width to use as the actual overshoot percentage. */
private let DrawerOvershootPercentage: CGFloat = 0.1
private let DrawerBezelRange: CGFloat = 20.0
private let DrawerLeftDrawerKey = "DrawerLeftDrawer"
private let DrawerRightDrawerKey = "DrawerRightDrawer"
private let DrawerCenterKey = "DrawerCenter"
private let DrawerOpenSideKey = "DrawerOpenSide"
public typealias DrawerGestureShouldRecognizeTouchBlock = (DrawerController, UIGestureRecognizer, UITouch) -> Bool
public typealias DrawerGestureCompletionBlock = (DrawerController, UIGestureRecognizer) -> Void
public typealias DrawerControllerDrawerVisualStateBlock = (DrawerController, DrawerSide, CGFloat) -> Void
private class DrawerCenterContainerView: UIView {
private var openSide: DrawerSide = .None
var centerInteractionMode: DrawerOpenCenterInteractionMode = .None
private override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
var hitView = super.hitTest(point, withEvent: event)
if hitView != nil && self.openSide != .None {
let navBar = self.navigationBarContainedWithinSubviewsOfView(self)
if navBar != nil {
let navBarFrame = navBar!.convertRect(navBar!.bounds, toView: self)
if (self.centerInteractionMode == .NavigationBarOnly && CGRectContainsPoint(navBarFrame, point) == false) || (self.centerInteractionMode == .None) {
hitView = nil
}
}
}
return hitView
}
private func navigationBarContainedWithinSubviewsOfView(view: UIView) -> UINavigationBar? {
var navBar: UINavigationBar?
for subview in view.subviews as [UIView] {
if view.isKindOfClass(UINavigationBar) {
navBar = view as? UINavigationBar
break
} else {
navBar = self.navigationBarContainedWithinSubviewsOfView(subview)
if navBar != nil {
break
}
}
}
return navBar
}
}
public class DrawerController: UIViewController, UIGestureRecognizerDelegate {
private var _centerViewController: UIViewController?
private var _leftDrawerViewController: UIViewController?
private var _rightDrawerViewController: UIViewController?
private var _maximumLeftDrawerWidth = DrawerDefaultWidth
private var _maximumRightDrawerWidth = DrawerDefaultWidth
/**
The center view controller.
This can only be set via the init methods, as well as the `setNewCenterViewController:...` methods. The size of this view controller will automatically be set to the size of the drawer container view controller, and it's position is modified from within this class. Do not modify the frame externally.
*/
public var centerViewController: UIViewController? {
get {
return self._centerViewController
}
set {
self.setCenterViewController(newValue, animated: false)
}
}
/**
The left drawer view controller.
The size of this view controller is managed within this class, and is automatically set to the appropriate size based on the `maximumLeftDrawerWidth`. Do not modify the frame externally.
*/
public var leftDrawerViewController: UIViewController? {
get {
return self._leftDrawerViewController
}
set {
self.setDrawerViewController(newValue, forSide: .Left)
}
}
/**
The right drawer view controller.
The size of this view controller is managed within this class, and is automatically set to the appropriate size based on the `maximumRightDrawerWidth`. Do not modify the frame externally.
*/
public var rightDrawerViewController: UIViewController? {
get {
return self._rightDrawerViewController
}
set {
self.setDrawerViewController(newValue, forSide: .Right)
}
}
/**
The maximum width of the `leftDrawerViewController`.
By default, this is set to 280. If the `leftDrawerViewController` is nil, this property will return 0.0;
*/
public var maximumLeftDrawerWidth: CGFloat {
get {
if self.leftDrawerViewController != nil {
return self._maximumLeftDrawerWidth
} else {
return 0.0
}
}
set {
self.setMaximumLeftDrawerWidth(newValue, animated: false, completion: nil)
}
}
/**
The maximum width of the `rightDrawerViewController`.
By default, this is set to 280. If the `rightDrawerViewController` is nil, this property will return 0.0;
*/
public var maximumRightDrawerWidth: CGFloat {
get {
if self.rightDrawerViewController != nil {
return self._maximumRightDrawerWidth
} else {
return 0.0
}
}
set {
self.setMaximumRightDrawerWidth(newValue, animated: false, completion: nil)
}
}
/**
The visible width of the `leftDrawerViewController`.
Note this value can be greater than `maximumLeftDrawerWidth` during the full close animation when setting a new center view controller;
*/
public var visibleLeftDrawerWidth: CGFloat {
get {
return max(0.0, CGRectGetMinX(self.centerContainerView.frame))
}
}
/**
The visible width of the `rightDrawerViewController`.
Note this value can be greater than `maximumRightDrawerWidth` during the full close animation when setting a new center view controller;
*/
public var visibleRightDrawerWidth: CGFloat {
get {
if CGRectGetMinX(self.centerContainerView.frame) < 0 {
return CGRectGetWidth(self.childControllerContainerView.bounds) - CGRectGetMaxX(self.centerContainerView.frame)
} else {
return 0.0
}
}
}
/**
A boolean that determines whether or not the panning gesture will "hard-stop" at the maximum width for a given drawer side.
By default, this value is set to YES. Enabling `shouldStretchDrawer` will give the pan a gradual asymptotic stopping point much like `UIScrollView` behaves. Note that if this value is set to YES, the `drawerVisualStateBlock` can be passed a `percentVisible` greater than 1.0, so be sure to handle that case appropriately.
*/
public var shouldStretchDrawer = true
public var drawerDampingFactor = DrawerDefaultDampingFactor
/**
The flag determining if a shadow should be drawn off of `centerViewController` when a drawer is open.
By default, this is set to YES.
*/
public var showsShadows: Bool = true {
didSet {
self.updateShadowForCenterView()
}
}
public var animationVelocity = DrawerDefaultAnimationVelocity
private var animatingDrawer: Bool = false {
didSet {
self.view.userInteractionEnabled = !self.animatingDrawer
}
}
private lazy var childControllerContainerView: UIView = {
let childContainerViewFrame = self.view.bounds
let childControllerContainerView = UIView(frame: childContainerViewFrame)
childControllerContainerView.backgroundColor = UIColor.clearColor()
childControllerContainerView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
self.view.addSubview(childControllerContainerView)
return childControllerContainerView
}()
private lazy var centerContainerView: DrawerCenterContainerView = {
let centerFrame = self.childControllerContainerView.bounds
let centerContainerView = DrawerCenterContainerView(frame: centerFrame)
centerContainerView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
centerContainerView.backgroundColor = UIColor.clearColor()
centerContainerView.openSide = self.openSide
centerContainerView.centerInteractionMode = self.centerHiddenInteractionMode
self.childControllerContainerView.addSubview(centerContainerView)
return centerContainerView
}()
/**
The current open side of the drawer.
Note this value will change as soon as a pan gesture opens a drawer, or when a open/close animation is finished.
*/
public private(set) var openSide: DrawerSide = .None {
didSet {
self.centerContainerView.openSide = self.openSide
if self.openSide == .None {
self.leftDrawerViewController?.view.hidden = true
self.rightDrawerViewController?.view.hidden = true
}
self.setNeedsStatusBarAppearanceUpdate()
}
}
private var startingPanRect: CGRect = CGRectNull
/**
Sets a callback to be called when a gesture has been completed.
This block is called when a gesture action has been completed. You can query the `openSide` of the `drawerController` to determine what the new state of the drawer is.
:param: gestureCompletionBlock A block object to be called that allows the implementer be notified when a gesture action has been completed.
*/
public var gestureCompletionBlock: DrawerGestureCompletionBlock?
/**
Sets a callback to be called when a drawer visual state needs to be updated.
This block is responsible for updating the drawer's view state, and the drawer controller will handle animating to that state from the current state. This block will be called when the drawer is opened or closed, as well when the user is panning the drawer. This block is not responsible for doing animations directly, but instead just updating the state of the properies (such as alpha, anchor point, transform, etc). Note that if `shouldStretchDrawer` is set to YES, it is possible for `percentVisible` to be greater than 1.0. If `shouldStretchDrawer` is set to NO, `percentVisible` will never be greater than 1.0.
Note that when the drawer is finished opening or closing, the side drawer controller view will be reset with the following properies:
- alpha: 1.0
- transform: CATransform3DIdentity
- anchorPoint: (0.5,0.5)
:param: drawerVisualStateBlock A block object to be called that allows the implementer to update visual state properties on the drawer. `percentVisible` represents the amount of the drawer space that is current visible, with drawer space being defined as the edge of the screen to the maxmimum drawer width. Note that you do have access to the drawerController, which will allow you to update things like the anchor point of the side drawer layer.
*/
public var drawerVisualStateBlock: DrawerControllerDrawerVisualStateBlock?
/**
Sets a callback to be called to determine if a UIGestureRecognizer should recieve the given UITouch.
This block provides a way to allow a gesture to be recognized with custom logic. For example, you may have a certain part of your view that should accept a pan gesture recognizer to open the drawer, but not another a part. If you return YES, the gesture is recognized and the appropriate action is taken. This provides similar support to how Facebook allows you to pan on the background view of the main table view, but not the content itself. You can inspect the `openSide` property of the `drawerController` to determine the current state of the drawer, and apply the appropriate logic within your block.
Note that either `openDrawerGestureModeMask` must contain `OpenDrawerGestureModeCustom`, or `closeDrawerGestureModeMask` must contain `CloseDrawerGestureModeCustom` for this block to be consulted.
:param: gestureShouldRecognizeTouchBlock A block object to be called to determine if the given `touch` should be recognized by the given gesture.
*/
public var gestureShouldRecognizeTouchBlock: DrawerGestureShouldRecognizeTouchBlock?
/**
How a user is allowed to open a drawer using gestures.
By default, this is set to `OpenDrawerGestureModeNone`. Note these gestures may affect user interaction with the `centerViewController`, so be sure to use appropriately.
*/
public var openDrawerGestureModeMask: OpenDrawerGestureMode = .None
/**
How a user is allowed to close a drawer.
By default, this is set to `CloseDrawerGestureModeNone`. Note these gestures may affect user interaction with the `centerViewController`, so be sure to use appropriately.
*/
public var closeDrawerGestureModeMask: CloseDrawerGestureMode = .None
/**
The value determining if the user can interact with the `centerViewController` when a side drawer is open.
By default, it is `DrawerOpenCenterInteractionModeNavigationBarOnly`, meaning that the user can only interact with the buttons on the `UINavigationBar`, if the center view controller is a `UINavigationController`. Otherwise, the user cannot interact with any other center view controller elements.
*/
public var centerHiddenInteractionMode: DrawerOpenCenterInteractionMode = .NavigationBarOnly {
didSet {
self.centerContainerView.centerInteractionMode = self.centerHiddenInteractionMode
}
}
// MARK: - Initializers
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
Creates and initializes an `DrawerController` object with the specified center view controller, left drawer view controller, and right drawer view controller.
:param: centerViewController The center view controller. This argument must not be `nil`.
:param: leftDrawerViewController The left drawer view controller.
:param: rightDrawerViewController The right drawer controller.
:returns: The newly-initialized drawer container view controller.
*/
public init(centerViewController: UIViewController, leftDrawerViewController: UIViewController?, rightDrawerViewController: UIViewController?) {
super.init()
self.centerViewController = centerViewController
self.leftDrawerViewController = leftDrawerViewController
self.rightDrawerViewController = rightDrawerViewController
}
/**
Creates and initializes an `DrawerController` object with the specified center view controller, left drawer view controller.
:param: centerViewController The center view controller. This argument must not be `nil`.
:param: leftDrawerViewController The left drawer view controller.
:returns: The newly-initialized drawer container view controller.
*/
public convenience init(centerViewController: UIViewController, leftDrawerViewController: UIViewController?) {
self.init(centerViewController: centerViewController, leftDrawerViewController: leftDrawerViewController, rightDrawerViewController: nil)
}
/**
Creates and initializes an `DrawerController` object with the specified center view controller, right drawer view controller.
:param: centerViewController The center view controller. This argument must not be `nil`.
:param: rightDrawerViewController The right drawer controller.
:returns: The newly-initialized drawer container view controller.
*/
public convenience init(centerViewController: UIViewController, rightDrawerViewController: UIViewController?) {
self.init(centerViewController: centerViewController, leftDrawerViewController: nil, rightDrawerViewController: rightDrawerViewController)
}
// MARK: - State Restoration
public override func encodeRestorableStateWithCoder(coder: NSCoder) {
super.encodeRestorableStateWithCoder(coder)
if let leftDrawerViewController = self.leftDrawerViewController {
coder.encodeObject(leftDrawerViewController, forKey: DrawerLeftDrawerKey)
}
if let rightDrawerViewController = self.rightDrawerViewController {
coder.encodeObject(rightDrawerViewController, forKey: DrawerRightDrawerKey)
}
if let centerViewController = self.centerViewController {
coder.encodeObject(centerViewController, forKey: DrawerCenterKey)
}
coder.encodeInteger(self.openSide.rawValue, forKey: DrawerOpenSideKey)
}
public override func decodeRestorableStateWithCoder(coder: NSCoder) {
super.decodeRestorableStateWithCoder(coder)
if let leftDrawerViewController: AnyObject = coder.decodeObjectForKey(DrawerLeftDrawerKey) {
self.leftDrawerViewController = leftDrawerViewController as? UIViewController
}
if let rightDrawerViewController: AnyObject = coder.decodeObjectForKey(DrawerRightDrawerKey) {
self.rightDrawerViewController = rightDrawerViewController as? UIViewController
}
if let centerViewController: AnyObject = coder.decodeObjectForKey(DrawerCenterKey) {
self.centerViewController = centerViewController as? UIViewController
}
if let openSide = DrawerSide(rawValue: coder.decodeIntegerForKey(DrawerOpenSideKey)) {
self.openSide = openSide
}
}
// MARK: - UIViewController Containment
override public func childViewControllerForStatusBarHidden() -> UIViewController? {
return self.childViewControllerForSide(self.openSide)
}
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
return self.childViewControllerForSide(self.openSide)
}
// MARK: - Animation helpers
private func finishAnimationForPanGestureWithXVelocity(xVelocity: CGFloat, completion: ((Bool) -> Void)?) {
var currentOriginX = CGRectGetMinX(self.centerContainerView.frame)
let animationVelocity = max(abs(xVelocity), DrawerPanVelocityXAnimationThreshold * 2)
if self.openSide == .Left {
let midPoint = self.maximumLeftDrawerWidth / 2.0
if xVelocity > DrawerPanVelocityXAnimationThreshold {
self.openDrawerSide(.Left, animated: true, velocity: animationVelocity, animationOptions: nil, completion: completion)
} else if xVelocity < -DrawerPanVelocityXAnimationThreshold {
self.closeDrawerAnimated(true, velocity: animationVelocity, animationOptions: nil, completion: completion)
} else if currentOriginX < midPoint {
self.closeDrawerAnimated(true, completion: completion)
} else {
self.openDrawerSide(.Left, animated: true, completion: completion)
}
} else if self.openSide == .Right {
currentOriginX = CGRectGetMaxX(self.centerContainerView.frame)
let midPoint = (CGRectGetWidth(self.childControllerContainerView.bounds) - self.maximumRightDrawerWidth) + (self.maximumRightDrawerWidth / 2.0)
if xVelocity > DrawerPanVelocityXAnimationThreshold {
self.closeDrawerAnimated(true, velocity: animationVelocity, animationOptions: nil, completion: completion)
} else if xVelocity < -DrawerPanVelocityXAnimationThreshold {
self.openDrawerSide(.Right, animated: true, velocity: animationVelocity, animationOptions: nil, completion: completion)
} else if currentOriginX > midPoint {
self.closeDrawerAnimated(true, completion: completion)
} else {
self.openDrawerSide(.Right, animated: true, completion: completion)
}
} else {
completion?(false)
}
}
private func updateDrawerVisualStateForDrawerSide(drawerSide: DrawerSide, percentVisible: CGFloat) {
if let drawerVisualState = self.drawerVisualStateBlock {
drawerVisualState(self, drawerSide, percentVisible)
} else if self.shouldStretchDrawer {
self.applyOvershootScaleTransformForDrawerSide(drawerSide, percentVisible: percentVisible)
}
}
private func applyOvershootScaleTransformForDrawerSide(drawerSide: DrawerSide, percentVisible: CGFloat) {
if percentVisible >= 1.0 {
var transform = CATransform3DIdentity
if let sideDrawerViewController = self.sideDrawerViewControllerForSide(drawerSide) {
if drawerSide == .Left {
transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0)
transform = CATransform3DTranslate(transform, self._maximumLeftDrawerWidth * (percentVisible - 1.0) / 2, 0, 0)
} else if drawerSide == .Right {
transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0)
transform = CATransform3DTranslate(transform, -self._maximumRightDrawerWidth * (percentVisible - 1.0) / 2, 0, 0)
}
sideDrawerViewController.view.layer.transform = transform
}
}
}
private func resetDrawerVisualStateForDrawerSide(drawerSide: DrawerSide) {
if let sideDrawerViewController = self.sideDrawerViewControllerForSide(drawerSide) {
sideDrawerViewController.view.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
sideDrawerViewController.view.layer.transform = CATransform3DIdentity
sideDrawerViewController.view.alpha = 1.0
}
}
private func roundedOriginXForDrawerConstraints(originX: CGFloat) -> CGFloat {
if originX < -self.maximumRightDrawerWidth {
if self.shouldStretchDrawer && self.rightDrawerViewController != nil {
let maxOvershoot: CGFloat = (CGRectGetWidth(self.centerContainerView.frame) - self.maximumRightDrawerWidth) * DrawerOvershootPercentage
return self.originXForDrawerOriginAndTargetOriginOffset(originX, targetOffset: -self.maximumRightDrawerWidth, maxOvershoot: maxOvershoot)
} else {
return -self.maximumRightDrawerWidth
}
} else if originX > self.maximumLeftDrawerWidth {
if self.shouldStretchDrawer && self.leftDrawerViewController != nil {
let maxOvershoot = (CGRectGetWidth(self.centerContainerView.frame) - self.maximumLeftDrawerWidth) * DrawerOvershootPercentage;
return self.originXForDrawerOriginAndTargetOriginOffset(originX, targetOffset: self.maximumLeftDrawerWidth, maxOvershoot: maxOvershoot)
} else {
return self.maximumLeftDrawerWidth
}
}
return originX
}
private func originXForDrawerOriginAndTargetOriginOffset(originX: CGFloat, targetOffset: CGFloat, maxOvershoot: CGFloat) -> CGFloat {
let delta: CGFloat = abs(originX - targetOffset)
let maxLinearPercentage = DrawerOvershootLinearRangePercentage
let nonLinearRange = maxOvershoot * maxLinearPercentage
let nonLinearScalingDelta = delta - nonLinearRange
let overshoot = nonLinearRange + nonLinearScalingDelta * nonLinearRange / sqrt(pow(nonLinearScalingDelta, 2.0) + 15000)
if delta < nonLinearRange {
return originX
} else if targetOffset < 0 {
return targetOffset - round(overshoot)
} else {
return targetOffset + round(overshoot)
}
}
// MARK: - Helpers
private func setupGestureRecognizers() {
let pan = UIPanGestureRecognizer(target: self, action: "panGestureCallback:")
pan.delegate = self
self.view.addGestureRecognizer(pan)
let tap = UITapGestureRecognizer(target: self, action: "tapGestureCallback:")
tap.delegate = self
self.view.addGestureRecognizer(tap)
}
private func childViewControllerForSide(drawerSide: DrawerSide) -> UIViewController? {
var childViewController: UIViewController?
switch drawerSide {
case .Left:
childViewController = self.leftDrawerViewController
case .Right:
childViewController = self.rightDrawerViewController
case .None:
childViewController = self.centerViewController
}
return childViewController
}
private func sideDrawerViewControllerForSide(drawerSide: DrawerSide) -> UIViewController? {
var sideDrawerViewController: UIViewController?
if drawerSide != .None {
sideDrawerViewController = self.childViewControllerForSide(drawerSide)
}
return sideDrawerViewController
}
private func prepareToPresentDrawer(drawer: DrawerSide, animated: Bool) {
var drawerToHide: DrawerSide = .None
if drawer == .Left {
drawerToHide = .Right
} else if drawer == .Right {
drawerToHide = .Left
}
if let sideDrawerViewControllerToHide = self.sideDrawerViewControllerForSide(drawerToHide) {
self.childControllerContainerView.sendSubviewToBack(sideDrawerViewControllerToHide.view)
sideDrawerViewControllerToHide.view.hidden = true
}
if let sideDrawerViewControllerToPresent = self.sideDrawerViewControllerForSide(drawer) {
sideDrawerViewControllerToPresent.view.hidden = false
self.resetDrawerVisualStateForDrawerSide(drawer)
sideDrawerViewControllerToPresent.view.frame = sideDrawerViewControllerToPresent.evo_visibleDrawerFrame
self.updateDrawerVisualStateForDrawerSide(drawer, percentVisible: 0.0)
sideDrawerViewControllerToPresent.beginAppearanceTransition(true, animated: animated)
}
}
private func updateShadowForCenterView() {
if self.showsShadows {
self.centerContainerView.layer.masksToBounds = false
self.centerContainerView.layer.shadowRadius = DrawerDefaultShadowRadius
self.centerContainerView.layer.shadowOpacity = DrawerDefaultShadowOpacity
/** In the event this gets called a lot, we won't update the shadowPath
unless it needs to be updated (like during rotation) */
if self.centerContainerView.layer.shadowPath == nil {
self.centerContainerView.layer.shadowPath = UIBezierPath(rect: self.centerContainerView.bounds).CGPath
} else {
var currentPath = CGPathGetPathBoundingBox(self.centerContainerView.layer.shadowPath)
if CGRectEqualToRect(currentPath, self.centerContainerView.bounds) == false {
self.centerContainerView.layer.shadowPath = UIBezierPath(rect: self.centerContainerView.bounds).CGPath
}
}
} else if (self.centerContainerView.layer.shadowPath != nil) {
self.centerContainerView.layer.shadowRadius = 0.0
self.centerContainerView.layer.shadowOpacity = 0.0
self.centerContainerView.layer.shadowPath = nil
self.centerContainerView.layer.masksToBounds = true
}
}
private func animationDurationForAnimationDistance(distance: CGFloat) -> NSTimeInterval {
return NSTimeInterval(max(distance / self.animationVelocity, DrawerMinimumAnimationDuration))
}
// MARK: - Size Methods
/**
Sets the maximum width of the left drawer view controller.
If the drawer is open, and `animated` is YES, it will animate the drawer frame as well as adjust the center view controller. If the drawer is not open, this change will take place immediately.
:param: width The new width of left drawer view controller. This must be greater than zero.
:param: animated Determines whether the drawer should be adjusted with an animation.
:param: completion The block called when the animation is finished.
*/
public func setMaximumLeftDrawerWidth(width: CGFloat, animated: Bool, completion: ((Bool) -> Void)?) {
self.setMaximumDrawerWidth(width, forSide: .Left, animated: animated, completion: completion)
}
/**
Sets the maximum width of the right drawer view controller.
If the drawer is open, and `animated` is YES, it will animate the drawer frame as well as adjust the center view controller. If the drawer is not open, this change will take place immediately.
:param: width The new width of right drawer view controller. This must be greater than zero.
:param: animated Determines whether the drawer should be adjusted with an animation.
:param: completion The block called when the animation is finished.
*/
public func setMaximumRightDrawerWidth(width: CGFloat, animated: Bool, completion: ((Bool) -> Void)?) {
self.setMaximumDrawerWidth(width, forSide: .Right, animated: animated, completion: completion)
}
private func setMaximumDrawerWidth(width: CGFloat, forSide drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return width > 0
}(), "width must be greater than 0")
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
if let sideDrawerViewController = self.sideDrawerViewControllerForSide(drawerSide) {
var oldWidth: CGFloat = 0.0
var drawerSideOriginCorrection: NSInteger = 1
if drawerSide == .Left {
oldWidth = self._maximumLeftDrawerWidth
self._maximumLeftDrawerWidth = width
} else if (drawerSide == .Right) {
oldWidth = self._maximumRightDrawerWidth
self._maximumRightDrawerWidth = width
drawerSideOriginCorrection = -1
}
let distance: CGFloat = abs(width - oldWidth)
let duration: NSTimeInterval = animated ? self.animationDurationForAnimationDistance(distance) : 0.0
if self.openSide == drawerSide {
var newCenterRect = self.centerContainerView.frame
newCenterRect.origin.x = CGFloat(drawerSideOriginCorrection) * width
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: self.animationVelocity / distance, options: nil, animations: { () -> Void in
self.centerContainerView.frame = newCenterRect
sideDrawerViewController.view.frame = sideDrawerViewController.evo_visibleDrawerFrame
}, completion: { (finished) -> Void in
completion?(finished)
return
})
} else {
sideDrawerViewController.view.frame = sideDrawerViewController.evo_visibleDrawerFrame
completion?(true)
}
}
}
// MARK: - Setters
private func setRightDrawerViewController(rightDrawerViewController: UIViewController?) {
self.setDrawerViewController(rightDrawerViewController, forSide: .Right)
}
private func setLeftDrawerViewController(leftDrawerViewController: UIViewController?) {
self.setDrawerViewController(leftDrawerViewController, forSide: .Left)
}
private func setDrawerViewController(viewController: UIViewController?, forSide drawerSide: DrawerSide) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
let currentSideViewController = self.sideDrawerViewControllerForSide(drawerSide)
if currentSideViewController == viewController {
return
}
if currentSideViewController != nil {
currentSideViewController!.beginAppearanceTransition(false, animated: false)
currentSideViewController!.view.removeFromSuperview()
currentSideViewController!.endAppearanceTransition()
currentSideViewController!.willMoveToParentViewController(nil)
currentSideViewController!.removeFromParentViewController()
}
var autoResizingMask = UIViewAutoresizing()
if drawerSide == .Left {
self._leftDrawerViewController = viewController
autoResizingMask = .FlexibleRightMargin | .FlexibleHeight
} else if drawerSide == .Right {
self._rightDrawerViewController = viewController
autoResizingMask = .FlexibleLeftMargin | .FlexibleHeight
}
if viewController != nil {
self.addChildViewController(viewController!)
if (self.openSide == drawerSide) && (self.childControllerContainerView.subviews as NSArray).containsObject(self.centerContainerView) {
self.childControllerContainerView.insertSubview(viewController!.view, belowSubview: self.centerContainerView)
viewController!.beginAppearanceTransition(true, animated: false)
viewController!.endAppearanceTransition()
} else {
self.childControllerContainerView.addSubview(viewController!.view)
self.childControllerContainerView.sendSubviewToBack(viewController!.view)
viewController!.view.hidden = true
}
viewController!.didMoveToParentViewController(self)
viewController!.view.autoresizingMask = autoResizingMask
viewController!.view.frame = viewController!.evo_visibleDrawerFrame
}
}
// MARK: - Updating the Center View Controller
private func setCenterViewController(centerViewController: UIViewController?, animated: Bool) {
if self._centerViewController == centerViewController {
return
}
if let oldCenterViewController = self._centerViewController {
oldCenterViewController.willMoveToParentViewController(nil)
if animated == false {
oldCenterViewController.beginAppearanceTransition(false, animated: false)
}
oldCenterViewController.removeFromParentViewController()
oldCenterViewController.view.removeFromSuperview()
if animated == false {
oldCenterViewController.endAppearanceTransition()
}
}
self._centerViewController = centerViewController
if self._centerViewController != nil {
self.addChildViewController(self._centerViewController!)
self._centerViewController!.view.frame = self.childControllerContainerView.bounds
self.centerContainerView.addSubview(self._centerViewController!.view)
self.childControllerContainerView.bringSubviewToFront(self.centerContainerView)
self._centerViewController!.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight
self.updateShadowForCenterView()
if animated == false {
// If drawer is offscreen, then viewWillAppear: will take care of this
if self.view.window != nil {
self._centerViewController!.beginAppearanceTransition(true, animated: false)
self._centerViewController!.endAppearanceTransition()
}
self._centerViewController!.didMoveToParentViewController(self)
}
}
}
/**
Sets the new `centerViewController`.
This sets the view controller and will automatically adjust the frame based on the current state of the drawer controller. If `closeAnimated` is YES, it will immediately change the center view controller, and close the drawer from its current position.
:param: centerViewController The new `centerViewController`.
:param: closeAnimated Determines whether the drawer should be closed with an animation.
:param: completion The block called when the animation is finsihed.
*/
public func setCenterViewController(newCenterViewController: UIViewController, var withCloseAnimation animated: Bool, completion: ((Bool) -> Void)?) {
if self.openSide == .None {
// If a side drawer isn't open, there is nothing to animate
animated = false
}
let forwardAppearanceMethodsToCenterViewController = (self.centerViewController! == newCenterViewController) == false
self.setCenterViewController(newCenterViewController, animated: animated)
if animated {
self.updateDrawerVisualStateForDrawerSide(self.openSide, percentVisible: 1.0)
if forwardAppearanceMethodsToCenterViewController {
self.centerViewController!.beginAppearanceTransition(true, animated: animated)
}
self.closeDrawerAnimated(animated, completion: { (finished) in
if forwardAppearanceMethodsToCenterViewController {
self.centerViewController!.endAppearanceTransition()
self.centerViewController!.didMoveToParentViewController(self)
}
completion?(finished)
})
} else {
completion?(true)
}
}
/**
Sets the new `centerViewController`.
This sets the view controller and will automatically adjust the frame based on the current state of the drawer controller. If `closeFullAnimated` is YES, the current center view controller will animate off the screen, the new center view controller will then be set, followed by the drawer closing across the full width of the screen.
:param: newCenterViewController The new `centerViewController`.
:param: fullCloseAnimated Determines whether the drawer should be closed with an animation.
:param: completion The block called when the animation is finsihed.
*/
public func setCenterViewController(newCenterViewController: UIViewController, withFullCloseAnimation animated: Bool, completion: ((Bool) -> Void)?) {
if self.openSide != .None && animated {
let forwardAppearanceMethodsToCenterViewController = (self.centerViewController! == newCenterViewController) == false
let sideDrawerViewController = self.sideDrawerViewControllerForSide(self.openSide)
var targetClosePoint: CGFloat = 0.0
if self.openSide == .Right {
targetClosePoint = -CGRectGetWidth(self.childControllerContainerView.bounds)
} else if self.openSide == .Left {
targetClosePoint = CGRectGetWidth(self.childControllerContainerView.bounds)
}
let distance: CGFloat = abs(self.centerContainerView.frame.origin.x - targetClosePoint)
let firstDuration = self.animationDurationForAnimationDistance(distance)
var newCenterRect = self.centerContainerView.frame
self.animatingDrawer = animated
let oldCenterViewController = self.centerViewController
if forwardAppearanceMethodsToCenterViewController {
oldCenterViewController?.beginAppearanceTransition(false, animated: animated)
}
newCenterRect.origin.x = targetClosePoint
UIView.animateWithDuration(firstDuration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: distance / self.animationVelocity, options: nil, animations: { () -> Void in
self.centerContainerView.frame = newCenterRect
sideDrawerViewController?.view.frame = self.childControllerContainerView.bounds
}, completion: { (finished) -> Void in
let oldCenterRect = self.centerContainerView.frame
self.setCenterViewController(newCenterViewController, animated: animated)
self.centerContainerView.frame = oldCenterRect
self.updateDrawerVisualStateForDrawerSide(self.openSide, percentVisible: 1.0)
if forwardAppearanceMethodsToCenterViewController {
oldCenterViewController?.endAppearanceTransition()
self.centerViewController?.beginAppearanceTransition(true, animated: animated)
}
sideDrawerViewController?.beginAppearanceTransition(false, animated: animated)
UIView.animateWithDuration(self.animationDurationForAnimationDistance(CGRectGetWidth(self.childControllerContainerView.bounds)), delay: DrawerDefaultFullAnimationDelay, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: CGRectGetWidth(self.childControllerContainerView.bounds) / self.animationVelocity, options: nil, animations: { () -> Void in
self.centerContainerView.frame = self.childControllerContainerView.bounds
self.updateDrawerVisualStateForDrawerSide(self.openSide, percentVisible: 0.0)
}, completion: { (finished) -> Void in
if forwardAppearanceMethodsToCenterViewController {
self.centerViewController?.endAppearanceTransition()
self.centerViewController?.didMoveToParentViewController(self)
}
sideDrawerViewController?.endAppearanceTransition()
self.resetDrawerVisualStateForDrawerSide(self.openSide)
if sideDrawerViewController != nil {
sideDrawerViewController!.view.frame = sideDrawerViewController!.evo_visibleDrawerFrame
}
self.openSide = .None
self.animatingDrawer = false
completion?(finished)
})
})
} else {
self.setCenterViewController(newCenterViewController, animated: animated)
if self.openSide != .None {
self.closeDrawerAnimated(animated, completion: completion)
} else if completion != nil {
completion!(true)
}
}
}
// MARK: - Bounce Methods
/**
Bounce preview for the specified `drawerSide` a distance of 40 points.
:param: drawerSide The drawer to preview. This value cannot be `DrawerSideNone`.
:param: completion The block called when the animation is finsihed.
*/
public func bouncePreviewForDrawerSide(drawerSide: DrawerSide, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
self.bouncePreviewForDrawerSide(drawerSide, distance: DrawerDefaultBounceDistance, completion: nil)
}
/**
Bounce preview for the specified `drawerSide`.
:param: drawerSide The drawer side to preview. This value cannot be `DrawerSideNone`.
:param: distance The distance to bounce.
:param: completion The block called when the animation is finsihed.
*/
public func bouncePreviewForDrawerSide(drawerSide: DrawerSide, distance: CGFloat, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
let sideDrawerViewController = self.sideDrawerViewControllerForSide(drawerSide)
if sideDrawerViewController == nil || self.openSide != .None {
completion?(false)
return
} else {
self.prepareToPresentDrawer(drawerSide, animated: true)
self.updateDrawerVisualStateForDrawerSide(drawerSide, percentVisible: 1.0)
CATransaction.begin()
CATransaction.setCompletionBlock {
sideDrawerViewController!.endAppearanceTransition()
sideDrawerViewController!.beginAppearanceTransition(false, animated: false)
sideDrawerViewController!.endAppearanceTransition()
completion?(true)
}
let modifier: CGFloat = (drawerSide == .Left) ? 1.0 : -1.0
let animation = bounceKeyFrameAnimationForDistanceOnView(distance * modifier, self.centerContainerView)
self.centerContainerView.layer.addAnimation(animation, forKey: "bouncing")
CATransaction.commit()
}
}
// MARK: - Gesture Handlers
func tapGestureCallback(tapGesture: UITapGestureRecognizer) {
if self.openSide != .None && self.animatingDrawer == false {
self.closeDrawerAnimated(true, completion: { (finished) in
if self.gestureCompletionBlock != nil {
self.gestureCompletionBlock!(self, tapGesture)
}
})
}
}
func panGestureCallback(panGesture: UIPanGestureRecognizer) {
switch panGesture.state {
case .Began:
if self.animatingDrawer {
panGesture.enabled = false
} else {
self.startingPanRect = self.centerContainerView.frame
}
case .Changed:
self.view.userInteractionEnabled = false
var newFrame = self.startingPanRect
var translatedPoint = panGesture.translationInView(self.centerContainerView)
newFrame.origin.x = self.roundedOriginXForDrawerConstraints(CGRectGetMinX(self.startingPanRect) + translatedPoint.x)
newFrame = CGRectIntegral(newFrame)
var xOffset = newFrame.origin.x
var visibleSide: DrawerSide = .None
var percentVisible: CGFloat = 0.0
if xOffset > 0 {
visibleSide = .Left
percentVisible = xOffset / self.maximumLeftDrawerWidth
} else if xOffset < 0 {
visibleSide = .Right
percentVisible = abs(xOffset) / self.maximumRightDrawerWidth
}
if let visibleSideDrawerViewController = self.sideDrawerViewControllerForSide(visibleSide) {
if self.openSide != visibleSide {
// Handle disappearing the visible drawer
if let sideDrawerViewController = self.sideDrawerViewControllerForSide(self.openSide) {
sideDrawerViewController.beginAppearanceTransition(false, animated: false)
sideDrawerViewController.endAppearanceTransition()
}
// Drawer is about to become visible
self.prepareToPresentDrawer(visibleSide, animated: false)
visibleSideDrawerViewController.endAppearanceTransition()
self.openSide = visibleSide
} else if visibleSide == .None {
self.openSide = .None
}
self.updateDrawerVisualStateForDrawerSide(visibleSide, percentVisible: percentVisible)
self.centerContainerView.center = CGPoint(x: CGRectGetMidX(newFrame), y: CGRectGetMidY(newFrame))
}
case .Ended, .Cancelled:
self.startingPanRect = CGRectNull
let velocity = panGesture.velocityInView(self.childControllerContainerView)
self.finishAnimationForPanGestureWithXVelocity(velocity.x, completion:{ (finished) in
if self.gestureCompletionBlock != nil {
self.gestureCompletionBlock!(self, panGesture)
}
})
self.view.userInteractionEnabled = true
default:
break
}
}
// MARK: - Open / Close Methods
// DrawerSide enum is not exported to Objective-C, so use these two methods instead
public func toggleLeftDrawerSideAnimated(animated: Bool, completion: ((Bool) -> Void)?) {
self.toggleDrawerSide(.Left, animated: animated, completion: completion)
}
public func toggleRightDrawerSideAnimated(animated: Bool, completion: ((Bool) -> Void)?) {
self.toggleDrawerSide(.Right, animated: animated, completion: completion)
}
/**
Toggles the drawer open/closed based on the `drawer` passed in.
Note that if you attempt to toggle a drawer closed while the other is open, nothing will happen. For example, if you pass in DrawerSideLeft, but the right drawer is open, nothing will happen. In addition, the completion block will be called with the finished flag set to NO.
:param: drawerSide The `DrawerSide` to toggle. This value cannot be `DrawerSideNone`.
:param: animated Determines whether the `drawer` should be toggle animated.
:param: completion The block that is called when the toggle is complete, or if no toggle took place at all.
*/
public func toggleDrawerSide(drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
if self.openSide == DrawerSide.None {
self.openDrawerSide(drawerSide, animated: animated, completion: completion)
} else {
if (drawerSide == DrawerSide.Left && self.openSide == DrawerSide.Left) || (drawerSide == DrawerSide.Right && self.openSide == DrawerSide.Right) {
self.closeDrawerAnimated(animated, completion: completion)
} else if completion != nil {
completion!(false)
}
}
}
/**
Opens the `drawer` passed in.
:param: drawerSide The `DrawerSide` to open. This value cannot be `DrawerSideNone`.
:param: animated Determines whether the `drawer` should be open animated.
:param: completion The block that is called when the toggle is open.
*/
public func openDrawerSide(drawerSide: DrawerSide, animated: Bool, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
self.openDrawerSide(drawerSide, animated: animated, velocity: self.animationVelocity, animationOptions: nil, completion: completion)
}
private func openDrawerSide(drawerSide: DrawerSide, animated: Bool, velocity: CGFloat, animationOptions options: UIViewAnimationOptions, completion: ((Bool) -> Void)?) {
assert({ () -> Bool in
return drawerSide != .None
}(), "drawerSide cannot be .None")
if self.animatingDrawer {
completion?(false)
} else {
self.animatingDrawer = animated
let sideDrawerViewController = self.sideDrawerViewControllerForSide(drawerSide)
if self.openSide != drawerSide {
self.prepareToPresentDrawer(drawerSide, animated: animated)
}
if sideDrawerViewController != nil {
var newFrame: CGRect
let oldFrame = self.centerContainerView.frame
if drawerSide == .Left {
newFrame = self.centerContainerView.frame
newFrame.origin.x = self._maximumLeftDrawerWidth
} else {
newFrame = self.centerContainerView.frame
newFrame.origin.x = 0 - self._maximumRightDrawerWidth
}
let distance = abs(CGRectGetMinX(oldFrame) - newFrame.origin.x)
let duration: NSTimeInterval = animated ? NSTimeInterval(max(distance / abs(velocity), DrawerMinimumAnimationDuration)) : 0.0
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: velocity / distance, options: options, animations: { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()
self.centerContainerView.frame = newFrame
self.updateDrawerVisualStateForDrawerSide(drawerSide, percentVisible: 1.0)
}, completion: { (finished) -> Void in
if drawerSide != self.openSide {
sideDrawerViewController!.endAppearanceTransition()
}
self.openSide = drawerSide
self.resetDrawerVisualStateForDrawerSide(drawerSide)
self.animatingDrawer = false
completion?(finished)
})
}
}
}
/**
Closes the open drawer.
:param: animated Determines whether the drawer side should be closed animated
:param: completion The block that is called when the close is complete
*/
public func closeDrawerAnimated(animated: Bool, completion: ((Bool) -> Void)?) {
self.closeDrawerAnimated(animated, velocity: self.animationVelocity, animationOptions: nil, completion: completion)
}
private func closeDrawerAnimated(animated: Bool, velocity: CGFloat, animationOptions options: UIViewAnimationOptions, completion: ((Bool) -> Void)?) {
if self.animatingDrawer {
completion?(false)
} else {
self.animatingDrawer = animated
let newFrame = self.childControllerContainerView.bounds
let distance = abs(CGRectGetMinX(self.centerContainerView.frame))
let duration: NSTimeInterval = animated ? NSTimeInterval(max(distance / abs(velocity), DrawerMinimumAnimationDuration)) : 0.0
let leftDrawerVisible = CGRectGetMinX(self.centerContainerView.frame) > 0
let rightDrawerVisible = CGRectGetMinX(self.centerContainerView.frame) < 0
var visibleSide: DrawerSide = .None
var percentVisible: CGFloat = 0.0
if leftDrawerVisible {
let visibleDrawerPoint = CGRectGetMinX(self.centerContainerView.frame)
percentVisible = max(0.0, visibleDrawerPoint / self._maximumLeftDrawerWidth)
visibleSide = .Left
} else if rightDrawerVisible {
let visibleDrawerPoints = CGRectGetWidth(self.centerContainerView.frame) - CGRectGetMaxX(self.centerContainerView.frame)
percentVisible = max(0.0, visibleDrawerPoints / self._maximumRightDrawerWidth)
visibleSide = .Right
}
let sideDrawerViewController = self.sideDrawerViewControllerForSide(visibleSide)
self.updateDrawerVisualStateForDrawerSide(visibleSide, percentVisible: percentVisible)
sideDrawerViewController?.beginAppearanceTransition(false, animated: animated)
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: self.drawerDampingFactor, initialSpringVelocity: velocity / distance, options: options, animations: { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()
self.centerContainerView.frame = newFrame
self.updateDrawerVisualStateForDrawerSide(visibleSide, percentVisible: 0.0)
}, completion: { (finished) -> Void in
sideDrawerViewController?.endAppearanceTransition()
self.openSide = .None
self.resetDrawerVisualStateForDrawerSide(visibleSide)
self.animatingDrawer = false
completion?(finished)
})
}
}
// MARK: - UIViewController
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
self.setupGestureRecognizers()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.centerViewController?.beginAppearanceTransition(true, animated: animated)
if self.openSide == .Left {
self.leftDrawerViewController?.beginAppearanceTransition(true, animated: animated)
} else if self.openSide == .Right {
self.rightDrawerViewController?.beginAppearanceTransition(true, animated: animated)
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.updateShadowForCenterView()
self.centerViewController?.endAppearanceTransition()
if self.openSide == .Left {
self.leftDrawerViewController?.endAppearanceTransition()
} else if self.openSide == .Right {
self.rightDrawerViewController?.endAppearanceTransition()
}
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.centerViewController?.beginAppearanceTransition(false, animated: animated)
if self.openSide == .Left {
self.leftDrawerViewController?.beginAppearanceTransition(false, animated: animated)
} else if self.openSide == .Right {
self.rightDrawerViewController?.beginAppearanceTransition(false, animated: animated)
}
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.centerViewController?.endAppearanceTransition()
if self.openSide == .Left {
self.leftDrawerViewController?.endAppearanceTransition()
} else if self.openSide == .Right {
self.rightDrawerViewController?.endAppearanceTransition()
}
}
public override func shouldAutomaticallyForwardAppearanceMethods() -> Bool {
return false
}
// MARK: - Rotation
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//If a rotation begins, we are going to cancel the current gesture and reset transform and anchor points so everything works correctly
var gestureInProgress = false
for gesture in self.view.gestureRecognizers as [UIGestureRecognizer] {
if gesture.state == .Changed {
gesture.enabled = false
gesture.enabled = true
gestureInProgress = true
}
if gestureInProgress {
self.resetDrawerVisualStateForDrawerSide(self.openSide)
}
}
coordinator.animateAlongsideTransition({ (context) -> Void in
//We need to support the shadow path rotation animation
//Inspired from here: http://blog.radi.ws/post/8348898129/calayers-shadowpath-and-uiview-autoresizing
if self.showsShadows {
let oldShadowPath = self.centerContainerView.layer.shadowPath
self.updateShadowForCenterView()
if oldShadowPath != nil {
let transition = CABasicAnimation(keyPath: "shadowPath")
transition.fromValue = oldShadowPath
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.duration = context.transitionDuration()
self.centerContainerView.layer.addAnimation(transition, forKey: "transition")
}
}
}, completion:nil)
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if self.openSide == .None {
let possibleOpenGestureModes = self.possibleOpenGestureModesForGestureRecognizer(gestureRecognizer, withTouch: touch)
return (self.openDrawerGestureModeMask & possibleOpenGestureModes).rawValue > 0
} else {
let possibleCloseGestureModes = self.possibleCloseGestureModesForGestureRecognizer(gestureRecognizer, withTouch: touch)
return (self.closeDrawerGestureModeMask & possibleCloseGestureModes).rawValue > 0
}
}
// MARK: - Gesture Recognizer Delegate Helpers
func possibleCloseGestureModesForGestureRecognizer(gestureRecognizer: UIGestureRecognizer, withTouch touch: UITouch) -> CloseDrawerGestureMode {
let point = touch.locationInView(self.childControllerContainerView)
var possibleCloseGestureModes: CloseDrawerGestureMode = .None
if gestureRecognizer.isKindOfClass(UITapGestureRecognizer) {
if self.isPointContainedWithinNavigationRect(point) {
possibleCloseGestureModes |= .TapNavigationBar
}
if self.isPointContainedWithinCenterViewContentRect(point) {
possibleCloseGestureModes |= .TapCenterView
}
} else if gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) {
if self.isPointContainedWithinNavigationRect(point) {
possibleCloseGestureModes |= .PanningNavigationBar
}
if self.isPointContainedWithinCenterViewContentRect(point) {
possibleCloseGestureModes |= .PanningCenterView
}
if self.isPointContainedWithinRightBezelRect(point) && self.openSide == .Left {
possibleCloseGestureModes |= .BezelPanningCenterView
}
if self.isPointContainedWithinLeftBezelRect(point) && self.openSide == .Right {
possibleCloseGestureModes |= .BezelPanningCenterView
}
if self.isPointContainedWithinCenterViewContentRect(point) == false && self.isPointContainedWithinNavigationRect(point) == false {
possibleCloseGestureModes |= .PanningDrawerView
}
}
if (self.closeDrawerGestureModeMask & CloseDrawerGestureMode.Custom).rawValue > 0 && self.gestureShouldRecognizeTouchBlock != nil {
if self.gestureShouldRecognizeTouchBlock!(self, gestureRecognizer, touch) {
possibleCloseGestureModes |= .Custom
}
}
return possibleCloseGestureModes
}
func possibleOpenGestureModesForGestureRecognizer(gestureRecognizer: UIGestureRecognizer, withTouch touch: UITouch) -> OpenDrawerGestureMode {
let point = touch.locationInView(self.childControllerContainerView)
var possibleOpenGestureModes: OpenDrawerGestureMode = .None
if gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) {
if self.isPointContainedWithinNavigationRect(point) {
possibleOpenGestureModes |= .PanningNavigationBar
}
if self.isPointContainedWithinCenterViewContentRect(point) {
possibleOpenGestureModes |= .PanningCenterView
}
if self.isPointContainedWithinLeftBezelRect(point) && self.leftDrawerViewController != nil {
possibleOpenGestureModes |= .BezelPanningCenterView
}
if self.isPointContainedWithinRightBezelRect(point) && self.rightDrawerViewController != nil {
possibleOpenGestureModes |= .BezelPanningCenterView
}
}
if (self.openDrawerGestureModeMask & OpenDrawerGestureMode.Custom).rawValue > 0 && self.gestureShouldRecognizeTouchBlock != nil {
if self.gestureShouldRecognizeTouchBlock!(self, gestureRecognizer, touch) {
possibleOpenGestureModes |= .Custom
}
}
return possibleOpenGestureModes
}
func isPointContainedWithinNavigationRect(point: CGPoint) -> Bool {
var navigationBarRect = CGRectNull
if let centerViewController = self.centerViewController {
if centerViewController.isKindOfClass(UINavigationController) {
let navBar = (self.centerViewController as UINavigationController).navigationBar
navigationBarRect = navBar.convertRect(navBar.bounds, toView: self.childControllerContainerView)
navigationBarRect = CGRectIntersection(navigationBarRect, self.childControllerContainerView.bounds)
}
}
return CGRectContainsPoint(navigationBarRect, point)
}
func isPointContainedWithinCenterViewContentRect(point: CGPoint) -> Bool {
var centerViewContentRect = self.centerContainerView.frame
centerViewContentRect = CGRectIntersection(centerViewContentRect, self.childControllerContainerView.bounds)
return CGRectContainsPoint(centerViewContentRect, point) && self.isPointContainedWithinNavigationRect(point) == false
}
func isPointContainedWithinLeftBezelRect(point: CGPoint) -> Bool {
var leftBezelRect = CGRectNull
var tempRect = CGRectNull
CGRectDivide(self.childControllerContainerView.bounds, &leftBezelRect, &tempRect, DrawerBezelRange, .MinXEdge)
return CGRectContainsPoint(leftBezelRect, point) && self.isPointContainedWithinCenterViewContentRect(point)
}
func isPointContainedWithinRightBezelRect(point: CGPoint) -> Bool {
var rightBezelRect = CGRectNull
var tempRect = CGRectNull
CGRectDivide(self.childControllerContainerView.bounds, &rightBezelRect, &tempRect, DrawerBezelRange, .MaxXEdge)
return CGRectContainsPoint(rightBezelRect, point) && self.isPointContainedWithinCenterViewContentRect(point)
}
}
| mit | 43aea4b31462d956bc916e1a1ec8ba2d | 46.527529 | 620 | 0.660928 | 5.742864 | false | false | false | false |
zhuhaow/Soca-iOS | Soca/View Controller/Config/AdapterConfigListTableViewController.swift | 1 | 7431 | //
// AdapterListTableViewController.swift
// soca
//
// Created by Zhuhao Wang on 3/10/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import UIKit
import SocaCore
import CoreData
protocol AdapterConfigDelegate {
func finishEditingConfig(config: AdapterConfig, save: Bool)
}
class AdapterConfigListTableViewController: UITableViewController, AdapterConfigDelegate, NSFetchedResultsControllerDelegate {
lazy var fetchedResultsController: NSFetchedResultsController = {
[unowned self] in
AdapterConfig.MR_fetchAllGroupedBy(nil, withPredicate: nil, sortedBy: nil, ascending: true, delegate: self)
}()
lazy var editContext: NSManagedObjectContext = {
NSManagedObjectContext.MR_context()
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func presentAdapterDetail(adapterConfig: AdapterConfig) {
var adapterViewController: AdapterConfigViewController!
switch adapterConfig {
case is SOCKS5AdapterConfig:
adapterViewController = ServerAdapterConfigViewController(adapterConfig: adapterConfig)
case is HTTPAdapterConfig, is SHTTPAdapterConfig:
adapterViewController = AuthenticationServerAdapterConfigViewController(adapterConfig: adapterConfig)
case is ShadowsocksAdapterConfig:
adapterViewController = ShadowsocksAdapterConfigViewController(adapterConfig: adapterConfig)
default:
return
}
adapterViewController.delegate = self
let navController = UINavigationController(rootViewController: adapterViewController)
self.presentViewController(navController, animated: true, completion: nil)
}
@IBAction func showAdapterTypeSheet(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Choose adapter type", message: nil, preferredStyle: .ActionSheet)
let HTTPAction = UIAlertAction(title: "HTTP", style: .Default) {_ in
self.presentAdapterDetail(HTTPAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SHTTPAction = UIAlertAction(title: "Secured HTTP", style: .Default) {_ in
self.presentAdapterDetail(SHTTPAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SOCKS5Action = UIAlertAction(title: "SOCKS5", style: .Default) {_ in
self.presentAdapterDetail(SOCKS5AdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let SSAction = UIAlertAction(title: "Shadowsocks", style: .Default) {_ in
self.presentAdapterDetail(ShadowsocksAdapterConfig.MR_createInContext(self.editContext) as! AdapterConfig)
}
let cancelAction = UIAlertAction(title: "cancel", style: .Cancel) {_ in }
alertController.addAction(HTTPAction)
alertController.addAction(SHTTPAction)
alertController.addAction(SOCKS5Action)
alertController.addAction(SSAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo).numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("adapterCell", forIndexPath: indexPath) as! UITableViewCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let adapterConfig: AdapterConfig = fetchedResultsController.objectAtIndexPath(indexPath) as! AdapterConfig
cell.textLabel!.text = adapterConfig.name
cell.detailTextLabel!.text = adapterConfig.type
if adapterConfig is DirectAdapterConfig {
cell.selectionStyle = .None
cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var configToEdit = fetchedResultsController.objectAtIndexPath(indexPath).MR_inContext(editContext) as! AdapterConfig
presentAdapterDetail(configToEdit as AdapterConfig)
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if fetchedResultsController.objectAtIndexPath(indexPath) is DirectAdapterConfig {
return false
}
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let config = fetchedResultsController.objectAtIndexPath(indexPath) as! AdapterConfig
config.MR_deleteEntity()
config.managedObjectContext?.MR_saveToPersistentStoreAndWait()
}
}
// MARK: NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
default:
break
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Update:
configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
// MARK: - AdapterConfigDelegate
func finishEditingConfig(config: AdapterConfig, save: Bool) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 4db069928bfca2cedbbc279bc092f521 | 42.203488 | 211 | 0.713228 | 5.76941 | false | true | false | false |
AnthonyMDev/Nimble | Sources/Nimble/Matchers/AllPass.swift | 47 | 5272 | import Foundation
public func allPass<T, U>
(_ passFunc: @escaping (T?) throws -> Bool) -> Predicate<U>
where U: Sequence, T == U.Iterator.Element {
let matcher = Predicate.simpleNilable("pass a condition") { actualExpression in
return PredicateStatus(bool: try passFunc(try actualExpression.evaluate()))
}
return createPredicate(matcher)
}
public func allPass<T, U>
(_ passName: String, _ passFunc: @escaping (T?) throws -> Bool) -> Predicate<U>
where U: Sequence, T == U.Iterator.Element {
let matcher = Predicate.simpleNilable(passName) { actualExpression in
return PredicateStatus(bool: try passFunc(try actualExpression.evaluate()))
}
return createPredicate(matcher)
}
public func allPass<S, M>(_ elementMatcher: M) -> Predicate<S>
where S: Sequence, M: Matcher, S.Iterator.Element == M.ValueType {
return createPredicate(elementMatcher.predicate)
}
public func allPass<S>(_ elementPredicate: Predicate<S.Iterator.Element>) -> Predicate<S>
where S: Sequence {
return createPredicate(elementPredicate)
}
private func createPredicate<S>(_ elementMatcher: Predicate<S.Iterator.Element>) -> Predicate<S>
where S: Sequence {
return Predicate { actualExpression in
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: .appends(.expectedTo("all pass"), " (use beNil() to match nils)")
)
}
var failure: ExpectationMessage = .expectedTo("all pass")
for currentElement in actualValue {
let exp = Expression(
expression: {currentElement}, location: actualExpression.location)
let predicateResult = try elementMatcher.satisfies(exp)
if predicateResult.status == .matches {
failure = predicateResult.message.prepended(expectation: "all ")
} else {
failure = predicateResult.message
.replacedExpectation({ .expectedTo($0.expectedMessage) })
.wrappedExpectation(
before: "all ",
after: ", but failed first at element <\(stringify(currentElement))>"
+ " in <\(stringify(actualValue))>"
)
return PredicateResult(status: .doesNotMatch, message: failure)
}
}
failure = failure.replacedExpectation({ expectation in
return .expectedTo(expectation.expectedMessage)
})
return PredicateResult(status: .matches, message: failure)
}
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func allPassMatcher(_ matcher: NMBMatcher) -> NMBPredicate {
return NMBPredicate { actualExpression in
let location = actualExpression.location
let actualValue = try actualExpression.evaluate()
var nsObjects = [NSObject]()
var collectionIsUsable = true
if let value = actualValue as? NSFastEnumeration {
var generator = NSFastEnumerationIterator(value)
while let obj = generator.next() {
if let nsObject = obj as? NSObject {
nsObjects.append(nsObject)
} else {
collectionIsUsable = false
break
}
}
} else {
collectionIsUsable = false
}
if !collectionIsUsable {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
// swiftlint:disable:next line_length
fail: "allPass can only be used with types which implement NSFastEnumeration (NSArray, NSSet, ...), and whose elements subclass NSObject, got <\(actualValue?.description ?? "nil")>"
)
)
}
let expr = Expression(expression: ({ nsObjects }), location: location)
let pred: Predicate<[NSObject]> = createPredicate(Predicate { expr in
if let predicate = matcher as? NMBPredicate {
return predicate.satisfies(({ try expr.evaluate() }), location: expr.location).toSwift()
} else {
let failureMessage = FailureMessage()
let result = matcher.matches(
// swiftlint:disable:next force_try
({ try! expr.evaluate() }),
failureMessage: failureMessage,
location: expr.location
)
let expectationMsg = failureMessage.toExpectationMessage()
return PredicateResult(
bool: result,
message: expectationMsg
)
}
})
return try pred.satisfies(expr).toObjectiveC()
}
}
}
#endif
| apache-2.0 | 95681f65c96b535a58a852acac4f46f2 | 42.213115 | 205 | 0.550455 | 5.699459 | false | false | false | false |
shhuangtwn/ProjectLynla | DataCollectionTool/ImageAnalyticViewController.swift | 1 | 11686 | //
// ImageAnalyticViewController.swift
// DataCollectionTool
//
// Created by Bryan Huang on 2016/9/30.
// Copyright © 2016年 Steven Hunag. All rights reserved.
//
import UIKit
import SwiftyJSON
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
import FirebaseAnalytics
class ImageAnalyticViewController: UIViewController, UITextFieldDelegate {
enum MatchingCase {
case brandNew
case newToUser
case existingItem
}
@IBAction func testSliderAction(sender: UISlider) {
let step: Float = 1
let roundedValue = round(sender.value / step) * step
sender.value = roundedValue
}
@IBOutlet weak var doneButtonForSaving: UIBarButtonItem!
@IBAction func doneButtonForSaving(sender: UIBarButtonItem) {
if self.userUID == "" {
let alert = UIAlertController(title: "Lynla!", message: "Thanks for trying out, please login to record your rating", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Back to Login", style: UIAlertActionStyle.Default, handler: { action in
self.performSegueWithIdentifier("segueBackToCaptureForDismissingVC", sender: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
} else {
postToCloudPressed()
}
}
@IBOutlet weak var avgFlavorLabel: UILabel!
@IBOutlet weak var avgTextureLabel: UILabel!
@IBOutlet weak var avgPointsLabel: UILabel!
@IBOutlet weak var ratedTimesLabel: UILabel!
@IBOutlet weak var logoTextfield: UITextField!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var testSlider: UISlider!
var receivedBarCode: String = ""
var receivedItemImageData = NSData()
var receivedLogoText: String = ""
var receivedInformationText: String = ""
var receivedMatchingStatus: Int = 0
var receivedItemUID: String = ""
@IBOutlet weak var barcodeLabel: UILabel!
@IBOutlet weak var logoResults: UILabel!
var ratedPoints: Double = 3.0
var ratedTexture: Double = 3.0
var ratedFlavor: Double = 3.0
var userUID: String = ""
@IBOutlet weak var ratingControl: RatingControl!
// @IBAction func ratingSegmentor(sender: UISegmentedControl) {
//
// switch sender.selectedSegmentIndex {
// case 0: ratedPoints = 1.0
// case 1: ratedPoints = 2.0
// case 2: ratedPoints = 3.0
// case 3: ratedPoints = 4.0
// case 4: ratedPoints = 5.0
// default: break
// }
// }
@IBAction func textureSegmentor(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: ratedTexture = 1.0
case 1: ratedTexture = 2.0
case 2: ratedTexture = 3.0
case 3: ratedTexture = 4.0
case 4: ratedTexture = 5.0
default: break
}
}
@IBAction func flavorSegmentor(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: ratedFlavor = 1.0
case 1: ratedFlavor = 2.0
case 2: ratedFlavor = 3.0
case 3: ratedFlavor = 4.0
case 4: ratedFlavor = 5.0
default: break
}
}
@IBOutlet weak var ratingSegmentor: UISegmentedControl!
@IBOutlet weak var textureSegmentor: UISegmentedControl!
@IBOutlet weak var flavorSegmentor: UISegmentedControl!
@IBOutlet weak var cardBGLabel: UILabel!
@IBOutlet weak var loadingSpinnerUI: UIActivityIndicatorView!
@IBOutlet weak var loadingMaskView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Set UI
self.loadingMaskView.hidden = true
self.loadingSpinnerUI.hidden = true
self.navigationController?.title = "Lynla"
self.navigationController?.navigationBar.backItem?.hidesBackButton = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.layer.shadowColor = UIColor.blackColor().CGColor
self.navigationController?.navigationBar.layer.shadowOffset = CGSizeMake(0, 1)
self.navigationController?.navigationBar.layer.shadowOpacity = 0.5
self.cardBGLabel.layer.shadowColor = UIColor.blackColor().CGColor
self.cardBGLabel.layer.shadowOpacity = 0.5
self.cardBGLabel.layer.shadowOffset = CGSizeMake(0.0, 2.0)
self.cardBGLabel.layer.shadowRadius = 2.5
self.imageView.layer.shadowColor = UIColor.blackColor().CGColor
self.imageView.layer.shadowOpacity = 0.5
self.imageView.layer.shadowOffset = CGSizeMake(0.0, 2.0)
self.imageView.layer.shadowRadius = 2.5
testSlider.hidden = true
ratingSegmentor.hidden = true
// ratingSegmentor.selectedSegmentIndex = (Int(ratedPoints) - 1 )
flavorSegmentor.selectedSegmentIndex = (Int(ratedTexture) - 1 )
textureSegmentor.selectedSegmentIndex = (Int(ratedFlavor) - 1 )
self.ratingControl.rating = Int(ratedPoints)
barcodeLabel.text = "Barcode: \(receivedBarCode)"
self.imageView.image = UIImage(data: receivedItemImageData)
self.logoTextfield.text = receivedLogoText
self.avgPointsLabel.hidden = true
self.avgTextureLabel.hidden = true
self.avgFlavorLabel.hidden = true
// Get userUID
let defaults = NSUserDefaults.standardUserDefaults()
if let uuid = defaults.stringForKey("userUID") {
self.userUID = uuid
} else {
getUserKey()
}
// FIrebase Analytics Event Log
FIRAnalytics.logEventWithName("complete_analyze", parameters: ["item": receivedLogoText])
// Receive matching state
if receivedMatchingStatus == 0 {
// Unmatch -> user to submit new item
print("enter unMatch")
} else if receivedMatchingStatus == 1 {
// New to user -> user to feedback from default value 3
print("enter newToUser")
self.logoTextfield.enabled = false
} else if receivedMatchingStatus == 2 {
// Existing item -> user to re-feedback from previous value
print("enter existingItem")
self.logoTextfield.enabled = false
} else {
fatalError("segue fail")
}
// Move keyboard and view
logoTextfield.delegate = self
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ImageAnalyticViewController.dismissKeyboard)))
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func postToCloudPressed() {
self.loadingMaskView.hidden = false
self.loadingSpinnerUI.hidden = false
self.loadingSpinnerUI.startAnimating()
self.ratedPoints = Double(self.ratingControl.rating)
let databaseRef = FIRDatabase.database().reference()
let postItemRef = databaseRef.child("items").childByAutoId()
// save barcode with item
var postItemKey: String = ""
if receivedMatchingStatus == 0 {
postItemKey = postItemRef.key
} else {
postItemKey = receivedItemUID
}
databaseRef.child("barcodes").child(receivedBarCode).setValue(postItemKey)
let storageRef = FIRStorage.storage().reference().child("user_item_images/TESTUSERKEY/\(postItemKey).png")
let uploadMetadata = FIRStorageMetadata()
uploadMetadata.contentType = "image/png"
var itemImageUrlString: String = ""
storageRef.putData(receivedItemImageData, metadata: uploadMetadata, completion: { (metadata, error) in
if (error != nil) {
print("uploading error: \(error)")
} else {
print("upload good: \(metadata)")
itemImageUrlString = metadata!.downloadURL()!.absoluteString
}
let postItemData: [String: AnyObject] = [
"name": self.logoTextfield.text!,
"image": itemImageUrlString]
postItemRef.setValue(postItemData)
dispatch_async(dispatch_get_main_queue(), {
let uniqueFeedbackKey = "\(self.userUID)\(postItemKey)"
let postUserFeedbackRef = databaseRef.child("user_feedbacks").child(uniqueFeedbackKey)
let postUFBRatingData: [String: AnyObject] = [
"user_uid":self.userUID,
"item_uid": postItemKey,
"points": self.ratedPoints,
"texture_points": self.ratedTexture,
"flavor_points": self.ratedFlavor,
"user_taken_image": itemImageUrlString]
postUserFeedbackRef.setValue(postUFBRatingData)
// FIrebase Analytics Event Log
FIRAnalytics.logEventWithName("complete_saving", parameters: ["state": "feedback saved"])
self.alertUserDataAdded()
})
})
}
func alertUserDataAdded() {
let alert = UIAlertController(title: "Lynla!", message: "Thanks for your feedback", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Home", style: UIAlertActionStyle.Default, handler: { action in
self.loadingMaskView.hidden = true
self.loadingSpinnerUI.hidden = true
self.loadingSpinnerUI.stopAnimating()
self.performSegueWithIdentifier("segueBackToCaptureForDismissingVC", sender: nil)
}))
alert.addAction(UIAlertAction(title: "Go back", style: UIAlertActionStyle.Cancel, handler: { action in
self.loadingMaskView.hidden = true
self.loadingSpinnerUI.hidden = true
self.loadingSpinnerUI.stopAnimating()
}))
self.presentViewController(alert, animated: true, completion: nil)
}
// Get backup user key
func getUserKey() {
if let user = FIRAuth.auth()?.currentUser {
self.userUID = user.uid;
} else {
self.userUID = ""
}
}
// Keyboard setup
func dismissKeyboard() {
logoTextfield.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
logoTextfield.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
}
| mit | 1a9b93d0e385cf5399c5015fa4573922 | 33.979042 | 174 | 0.6126 | 5.051016 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-inmodule-2argument-5distinct_use.swift | 3 | 15184 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueVys5UInt8VSSGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwCP{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwxx{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwcp{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwca{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwta{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwet{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVys5UInt8VSSGwst{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVys5UInt8VSSGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME:}> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVys5UInt8VSSGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$ss5UInt8VN",
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 [[ALIGNMENT]],
// CHECK-SAME: i64 3
// CHECK-SAME:}>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySSSdGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwCP{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwxx{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwcp{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwca{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwta{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwet{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySSSdGwst{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySSSdGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME:}> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySSSdGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: %swift.type* @"$sSdN",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 16,
// CHECK-SAME: i64 3
// CHECK-SAME:}>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySdSiGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]*@__swift_memcpy[^@]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_noop_void_return{{[^[:space:]]* to i8\*}}),
// CHECK_SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySdSiGwet{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVySdSiGwst{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySdSiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME:}> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySdSiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSdN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 8,
// CHECK-SAME: i64 3
// CHECK-SAME:}>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVyS2iGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]*@__swift_memcpy[^@]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_noop_void_return{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVyS2iGwet{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@"$s4main5ValueVyS2iGwst{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVyS2iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME:}> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVyS2iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 [[ALIGNMENT]],
// CHECK-SAME: i64 3
// CHECK-SAME:}>, align [[ALIGNMENT]]
struct Value<First, Second> {
let first: First
let second: Second
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVyS2iGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySdSiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySSSdGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys5UInt8VSSGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys4Int8Vs5UInt8VGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13, second: 13) )
consume( Value(first: 13.0, second: 13) )
consume( Value(first: "13.0", second: 13.0) )
consume( Value(first: 13 as UInt8, second: "13.0") )
consume( Value(first: 13 as Int8, second: 13 as UInt8) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: br i1 [[EQUAL_TYPES_1_2]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[TYPE_COMPARISON_2:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_2]]:
// CHECK: [[EQUAL_TYPE_2_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_2_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_2_1]]
// CHECK: [[EQUAL_TYPE_2_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_2_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_2_1]], [[EQUAL_TYPE_2_2]]
// CHECK: br i1 [[EQUAL_TYPES_2_2]], label %[[EXIT_PRESPECIALIZED_2:[0-9]+]], label %[[TYPE_COMPARISON_3:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_3]]:
// CHECK: [[EQUAL_TYPE_3_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_3_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_3_1]]
// CHECK: [[EQUAL_TYPE_3_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_3_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_3_1]], [[EQUAL_TYPE_3_2]]
// CHECK: br i1 [[EQUAL_TYPES_3_2]], label %[[EXIT_PRESPECIALIZED_3:[0-9]+]], label %[[TYPE_COMPARISON_4:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_4]]:
// CHECK: [[EQUAL_TYPE_4_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss5UInt8VN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_4_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_4_1]]
// CHECK: [[EQUAL_TYPE_4_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_4_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_4_1]], [[EQUAL_TYPE_4_2]]
// CHECK: br i1 [[EQUAL_TYPES_4_2]], label %[[EXIT_PRESPECIALIZED_4:[0-9]+]], label %[[TYPE_COMPARISON_5:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_5]]:
// CHECK: [[EQUAL_TYPE_5_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss4Int8VN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_5_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_5_1]]
// CHECK: [[EQUAL_TYPE_5_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss5UInt8VN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_5_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_5_1]], [[EQUAL_TYPE_5_2]]
// CHECK: br i1 [[EQUAL_TYPES_5_2]], label %[[EXIT_PRESPECIALIZED_5:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVyS2iGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_2]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySdSiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_3]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySSSdGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_4]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys5UInt8VSSGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_5]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys4Int8Vs5UInt8VGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 73f87857dfacacec8ab79bae5a945d9e | 64.731602 | 345 | 0.585287 | 2.847178 | false | false | false | false |
epeschard/RealmSearchTableViewController | CustomResultsTableViewController.swift | 1 | 2447 | import RealmSwift
import UIKit
class RealmResultsTableViewController: UITableViewController {
typealias Entity = CustomClass
typealias TableCell = CustomCell
let textForEmptyLabel = "No results matching search"
// MARK: - Instance Variables
var searchString = ""
var searchResults = try! Realm().objects(Entity) {
didSet {
tableView.reloadData()
}
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return searchResults.count
let rowCount = searchResults.count
// When no data insert centered label
if rowCount == 0 {
handleEmptyTable()
} else {
// Remove empty table label
tableView.backgroundView = nil
tableView.separatorStyle = .SingleLine
}
return rowCount
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell: TableCell =
tableView.dequeueReusableCellWithIdentifier("\(TableCell.self)", forIndexPath: indexPath) as! TableCell
cell.searchString = searchString
cell.object = searchResults[indexPath.row]
return cell
}
func handleEmptyTable() {
//create a lable size to fit the Table View
let messageLbl = UILabel(frame: CGRectMake(0, 0,
tableView.bounds.size.width,
tableView.bounds.size.height))
//set the message
messageLbl.text = textForEmptyLabel
// messageLbl.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
messageLbl.font = UIFont.systemFontOfSize(19)
messageLbl.textColor = UIColor.grayColor()
//center the text
messageLbl.textAlignment = .Center
//multiple lines
messageLbl.numberOfLines = 0
//auto size the text
messageLbl.sizeToFit()
//set back to label view
tableView.backgroundView = messageLbl
//no separator
tableView.separatorStyle = .None
}
}
| mit | c850eae3e2cbd2be12bb831659d93ee5 | 28.841463 | 119 | 0.594197 | 6.027094 | false | false | false | false |
ostatnicky/kancional-ios | Cancional/UI/Search/Text Search/TextSearchView.swift | 1 | 5266 | //
// TextSearchView.swift
// Cancional
//
// Created by Jiri Ostatnicky on 05/09/2017.
// Copyright © 2017 Jiri Ostatnicky. All rights reserved.
//
import UIKit
import Trackable
class TextSearchView: UIView {
// Dependencies
var viewModel: NumberNamesViewModel {
return resultsViewController.viewModel as! NumberNamesViewModel
}
// MARK: - UI
fileprivate var searchBar: UISearchBar!
fileprivate var searchBarPlace: UIView!
fileprivate var backgroundOverlay: UIView!
fileprivate var resultsViewController: ListViewController!
// MARK: - Properties
var onCancel: (() -> Void)?
weak var parentViewController: UIViewController?
var appearance: SongAppearance {
return Persistence.instance.songAppearance
}
// MARK: - Life cycle
override init(frame: CGRect) {
super.init(frame: .zero)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Actions
func showSearchBar() {
refreshUI()
searchBar.becomeFirstResponder()
UIView.animate(withDuration: 0.3) { [weak self] in
guard let `self` = self else { return }
self.alpha = 1
}
}
func hideSearchBar() {
searchBar.resignFirstResponder()
UIView.animate(withDuration: 0.3, animations: { [weak self] in
guard let `self` = self else { return }
self.alpha = 0
}) { [weak self] _ in
guard let `self` = self else { return }
self.searchBar.text = nil
self.resultsViewController.view.alpha = 0
}
}
func refreshUI() {
searchBar.keyboardAppearance = appearance.isDark ? .dark : .default
resultsViewController.refreshUI()
}
}
// MARK: Private
private extension TextSearchView {
func setupUI() {
// Place for search bar
searchBarPlace = UIView()
searchBarPlace.backgroundColor = UIColor.Cancional.tintColor()
addSubview(searchBarPlace)
searchBarPlace.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom)
searchBarPlace.autoSetDimension(.height, toSize: 44)
// Search bar
searchBar = UISearchBar()
searchBar.searchBarStyle = .minimal
searchBar.tintColor = .white
searchBar.placeholder = AppConfig.textSearchPlaceholder
searchBar.delegate = self
searchBarPlace.addSubview(searchBar)
if #available(iOS 11.0, *) {
searchBar.autoPinEdgesToSuperviewMargins()
} else {
searchBar.autoPinEdgesToSuperviewEdges(with: .zero)
}
// Background overlay
backgroundOverlay = UIView()
backgroundOverlay.backgroundColor = UIColor.Cancional.backgroundUnderlayColor()
addSubview(backgroundOverlay)
backgroundOverlay.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .top)
backgroundOverlay.autoPinEdge(.top, to: .bottom, of: searchBarPlace)
// Tap to hide
let tap = UITapGestureRecognizer(target: self, action: #selector(cancel))
backgroundOverlay.addGestureRecognizer(tap)
// Results view controller
resultsViewController = R.storyboard.main.pageListViewController()!
resultsViewController.onSelect = { [weak self] song in
guard let `self` = self else { return }
self.searchBar.resignFirstResponder()
self.parentViewController?.performSegue(withIdentifier: R.segue.mainViewController.songViewControllerSeque.identifier, sender: song)
self.track(TrackableEvents.User.didSearchText, trackedProperties: [
TrackableKeys.songNumber ~>> song?.fullNumberWithHymnal ?? "0",
TrackableKeys.text ~>> self.searchBar.text ?? "unknown"
])
}
addSubview(resultsViewController.view)
resultsViewController.view.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .top)
resultsViewController.view.autoPinEdge(.top, to: .bottom, of: searchBarPlace)
resultsViewController.view.alpha = 0
}
@objc func cancel() {
onCancel?()
}
func found() {
log.verbose("Found")
animateResults(show: true)
}
func emptyState() {
animateResults(show: false)
}
func animateResults(show: Bool) {
UIView.animate(withDuration: 0.3) { [weak self] in
guard let `self` = self else { return }
self.resultsViewController.view.alpha = show ? 1 : 0
}
}
}
// MARK: UISearchBarDelegate
extension TextSearchView: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
emptyState()
} else {
viewModel.configure(withContentType: .searched(searchText))
resultsViewController.reloadData()
if let songs = viewModel.items, songs.count > 0 {
found()
}
}
}
}
// MARK: - TrackableClass
extension TextSearchView: TrackableClass { }
| mit | aa8dd89f9017c40561a96b6b0db44ac8 | 31.5 | 144 | 0.62887 | 4.966981 | false | false | false | false |
natecook1000/swift | test/Frontend/OptimizationOptions-without-stdlib-checks.swift | 2 | 6162 | // RUN: %target-swift-frontend -module-name OptimizationOptions -Onone -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=DEBUG
// RUN: %target-swift-frontend -module-name OptimizationOptions -O -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=RELEASE
// RUN: %target-swift-frontend -module-name OptimizationOptions -Ounchecked -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=UNCHECKED
// RUN: %target-swift-frontend -module-name OptimizationOptions -Oplayground -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=PLAYGROUND
// REQUIRES: optimized_stdlib
// REQUIRES: swift_stdlib_no_asserts
func test_assert(x: Int, y: Int) -> Int {
assert(x >= y , "x smaller than y")
return x + y
}
func test_fatal(x: Int, y: Int) -> Int {
if x > y {
return x + y
}
preconditionFailure("Human nature ...")
}
func testprecondition_check(x: Int, y: Int) -> Int {
precondition(x > y, "Test precondition check")
return x + y
}
func test_partial_safety_check(x: Int, y: Int) -> Int {
assert(x > y, "Test partial safety check")
return x + y
}
// In debug mode keep user asserts and runtime checks.
// DEBUG-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// DEBUG: "x smaller than y"
// DEBUG: "Assertion failed"
// DEBUG: cond_fail
// DEBUG: return
// In playground mode keep user asserts and runtime checks.
// PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// PLAYGROUND: "x smaller than y"
// PLAYGROUND: "Assertion failed"
// PLAYGROUND: cond_fail
// In release mode remove user asserts and keep runtime checks.
// RELEASE-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// RELEASE-NOT: "x smaller than y"
// RELEASE-NOT: "Assertion failed"
// RELEASE: cond_fail
// In fast mode remove user asserts and runtime checks.
// FAST-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// FAST-NOT: "x smaller than y"
// FAST-NOT: "Assertion failed"
// FAST-NOT: cond_fail
// In debug mode keep verbose fatal errors.
// DEBUG-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// DEBUG-DAG: "Human nature ..."
// DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*assertionFailure.*]] : $@convention(thin)
// DEBUG: apply %[[FATAL_ERROR]]({{.*}})
// DEBUG: unreachable
// In playground mode keep verbose fatal errors.
// PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// PLAYGROUND-DAG: "Human nature ..."
// PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*assertionFailure.*]] : $@convention(thin)
// PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
// PLAYGROUND: unreachable
// In release mode keep succinct fatal errors (trap).
// RELEASE-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// RELEASE-NOT: "Human nature ..."
// RELEASE-NOT: "Fatal error"
// RELEASE: cond_fail
// RELEASE: return
// In fast mode remove fatal errors.
// FAST-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// FAST-NOT: "Human nature ..."
// FAST-NOT: "Fatal error"
// FAST-NOT: int_trap
// Precondition safety checks.
// In debug mode keep verbose library precondition checks.
// DEBUG-DAG: "Fatal error"
// DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
// DEBUG: apply %[[FATAL_ERROR]]({{.*}})
// DEBUG: unreachable
// DEBUG: return
// In playground mode keep verbose library precondition checks.
// PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// PLAYGROUND-DAG: "Precondition failed"
// PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
// PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
// PLAYGROUND: unreachable
// PLAYGROUND: return
// In release mode keep succinct library precondition checks (trap).
// RELEASE-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// RELEASE-NOT: "Fatal error"
// RELEASE: %[[V2:.+]] = builtin "xor_Int1"(%{{.+}}, %{{.+}})
// RELEASE: cond_fail %[[V2]]
// RELEASE: return
// In unchecked mode remove library precondition checks.
// UNCHECKED-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// UNCHECKED-NOT: "Fatal error"
// UNCHECKED-NOT: builtin "int_trap"
// UNCHECKED-NOT: unreachable
// UNCHECKED: return
// Partial safety checks.
// In debug mode keep verbose partial safety checks.
// DEBUG-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// DEBUG-DAG: "Assertion failed"
// DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
// DEBUG: apply %[[FATAL_ERROR]]({{.*}})
// DEBUG: unreachable
// In playground mode keep verbose partial safety checks.
// PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// PLAYGROUND-DAG: "Assertion failed"
// PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
// PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
// PLAYGROUND: unreachable
// In release mode remove partial safety checks.
// RELEASE-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// RELEASE-NOT: "Fatal error"
// RELEASE-NOT: builtin "int_trap"
// RELEASE-NOT: unreachable
// RELEASE: return
// In fast mode remove partial safety checks.
// FAST-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// FAST-NOT: "Fatal error"
// FAST-NOT: builtin "int_trap"
// FAST-NOT: unreachable
// FAST: return
| apache-2.0 | 76b7fde9627e3db8da4094444ac72543 | 42.090909 | 150 | 0.69815 | 3.338028 | false | true | false | false |
uber/RIBs | ios/tutorials/tutorial3/TicTacToe/LoggedIn/LoggedInRouter.swift | 2 | 2805 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
protocol LoggedInInteractable: Interactable, OffGameListener, TicTacToeListener {
var router: LoggedInRouting? { get set }
var listener: LoggedInListener? { get set }
}
protocol LoggedInViewControllable: ViewControllable {
func present(viewController: ViewControllable)
func dismiss(viewController: ViewControllable)
}
final class LoggedInRouter: Router<LoggedInInteractable>, LoggedInRouting {
init(interactor: LoggedInInteractable,
viewController: LoggedInViewControllable,
offGameBuilder: OffGameBuildable,
ticTacToeBuilder: TicTacToeBuildable) {
self.viewController = viewController
self.offGameBuilder = offGameBuilder
self.ticTacToeBuilder = ticTacToeBuilder
super.init(interactor: interactor)
interactor.router = self
}
override func didLoad() {
super.didLoad()
attachOffGame()
}
// MARK: - LoggedInRouting
func cleanupViews() {
if let currentChild = currentChild {
viewController.dismiss(viewController: currentChild.viewControllable)
}
}
func routeToTicTacToe() {
detachCurrentChild()
let ticTacToe = ticTacToeBuilder.build(withListener: interactor)
currentChild = ticTacToe
attachChild(ticTacToe)
viewController.present(viewController: ticTacToe.viewControllable)
}
func routeToOffGame() {
detachCurrentChild()
attachOffGame()
}
// MARK: - Private
private let viewController: LoggedInViewControllable
private let offGameBuilder: OffGameBuildable
private let ticTacToeBuilder: TicTacToeBuildable
private var currentChild: ViewableRouting?
private func attachOffGame() {
let offGame = offGameBuilder.build(withListener: interactor)
self.currentChild = offGame
attachChild(offGame)
viewController.present(viewController: offGame.viewControllable)
}
private func detachCurrentChild() {
if let currentChild = currentChild {
detachChild(currentChild)
viewController.dismiss(viewController: currentChild.viewControllable)
}
}
}
| apache-2.0 | c695984c7db1ca64b06280b01fe5f883 | 30.166667 | 81 | 0.706952 | 4.895288 | false | false | false | false |
asturkmani/Project-Athena | iOS/Athena/AppDelegate.swift | 1 | 6082 | //
// AppDelegate.swift
// Athena
//
// Created by Abdel Wahab Turkmani on 3/24/16.
// Copyright © 2016 AJI. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.AJI.Athena" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Athena", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bsd-3-clause | 365a3e79421fac4fa1120bf18c48dd90 | 53.783784 | 291 | 0.718961 | 5.841499 | false | false | false | false |
jwfriese/Fleet | TestAppCommon/BoxTurtleViewController.swift | 1 | 2427 | import UIKit
class BoxTurtleViewController: UIViewController {
@IBOutlet weak var boxTurtleImage: UIImageView?
@IBOutlet weak var leftBarButtonItem: UIBarButtonItem?
@IBOutlet weak var rightBarButtonItem: UIBarButtonItem?
@IBOutlet weak var informationLabel: UILabel?
@IBOutlet weak var textField: UITextField?
@IBAction func onLeftBarButtonItemTapped() {
informationLabel?.text = "box turtle stop party..."
if let boxTurtleImage = boxTurtleImage {
boxTurtleImage.layer.removeAllAnimations()
}
}
@IBAction func onRightBarButtonItemTapped() {
informationLabel?.text = "Box Turtle Dance Party!!!!!!"
doTurtleDanceParty()
}
fileprivate func doTurtleDanceParty() {
if let boxTurtleImage = boxTurtleImage {
let path = UIBezierPath()
let startingPoint = CGPoint(x: boxTurtleImage.frame.origin.x + (boxTurtleImage.frame.size.width / 2),
y: boxTurtleImage.frame.origin.y + (boxTurtleImage.frame.size.height / 2)
)
let rightPoint = CGPoint(x: startingPoint.x + 30, y: startingPoint.y)
let rightMoveControlLeft = CGPoint(x: startingPoint.x, y: startingPoint.y - 30)
let rightMoveControlRight = CGPoint(x: startingPoint.x + 30, y: startingPoint.y - 30)
let leftPoint = CGPoint(x: startingPoint.x - 30, y: startingPoint.y)
let leftMoveControlLeft = CGPoint(x: startingPoint.x - 30, y: startingPoint.y - 30)
let leftMoveControlRight = CGPoint(x: startingPoint.x, y: startingPoint.y - 30)
path.move(to: startingPoint)
path.addCurve(to: rightPoint, controlPoint1: rightMoveControlLeft, controlPoint2: rightMoveControlRight)
path.addCurve(to: startingPoint, controlPoint1: rightMoveControlRight, controlPoint2: rightMoveControlLeft)
path.addCurve(to: leftPoint, controlPoint1: leftMoveControlRight, controlPoint2: leftMoveControlLeft)
path.addCurve(to: startingPoint, controlPoint1: leftMoveControlLeft, controlPoint2: leftMoveControlRight)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path.cgPath
animation.duration = 1.5
animation.repeatCount = 10
boxTurtleImage.layer.add(animation, forKey: "TURTLE DANCE PARTY")
}
}
}
| apache-2.0 | d0c4ec675052d2fdd2c988b365f80609 | 43.944444 | 119 | 0.672023 | 4.587902 | false | false | false | false |
tuarua/WebViewANE | native_library/apple/WebViewANE/WebViewANE/SwiftController+URLSessionDownloadDelegate.swift | 1 | 3170 | // Copyright 2018 Tua Rua 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.
//
// Additional Terms
// No part, or derivative of this Air Native Extensions's code is permitted
// to be sold as the basis of a commercially packaged Air Native Extension which
// undertakes the same purpose as this software. That is, a WebView for Windows,
// OSX and/or iOS and/or Android.
// All Rights Reserved. Tua Rua Ltd.
import Foundation
import WebKit
import SwiftyJSON
extension SwiftController: URLSessionTaskDelegate, URLSessionDelegate, URLSessionDownloadDelegate {
// https://developer.apple.com/documentation/foundation/urlsessiondownloadtask
// https://www.raywenderlich.com/158106/urlsession-tutorial-getting-started
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
guard let destinationURL = downloadTaskSaveTos[downloadTask.taskIdentifier] else { return }
let fileManager = FileManager.default
try? fileManager.removeItem(at: destinationURL)
do {
try fileManager.copyItem(at: location, to: destinationURL)
} catch {
self.dispatchEvent(name: WebViewEvent.ON_DOWNLOAD_CANCEL,
value: downloadTask.originalRequest?.url?.absoluteString ?? "")
}
dispatchEvent(name: WebViewEvent.ON_DOWNLOAD_COMPLETE, value: String(describing: downloadTask.taskIdentifier))
downloadTaskSaveTos[downloadTask.taskIdentifier] = nil
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
var props = [String: Any]()
props["id"] = downloadTask.taskIdentifier
props["url"] = downloadTask.originalRequest?.url?.absoluteString
props["speed"] = 0
props["percent"] = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)) * 100
props["bytesLoaded"] = Double(totalBytesWritten)
props["bytesTotal"] = Double(totalBytesExpectedToWrite)
dispatchEvent(name: WebViewEvent.ON_DOWNLOAD_PROGRESS, value: JSON(props).description)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
self.dispatchEvent(name: WebViewEvent.ON_DOWNLOAD_CANCEL,
value: task.originalRequest?.url?.absoluteString ?? "")
}
}
| apache-2.0 | f9d6cdfc73572582112cead2440f4a0b | 47.030303 | 118 | 0.682019 | 5.023772 | false | true | false | false |
xmartlabs/Eureka | Source/Rows/Common/DateFieldRow.swift | 1 | 4817 | // DateFieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public protocol DatePickerRowProtocol: AnyObject {
var minimumDate: Date? { get set }
var maximumDate: Date? { get set }
var minuteInterval: Int? { get set }
}
open class DateCell: Cell<Date>, CellType {
public var datePicker: UIDatePicker
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
datePicker = UIDatePicker()
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
datePicker = UIDatePicker()
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
datePicker.datePickerMode = datePickerMode()
datePicker.addTarget(self, action: #selector(DateCell.datePickerValueDidChange(_:)), for: .valueChanged)
#if swift(>=5.2)
if #available(iOS 13.4, *) {
datePicker.preferredDatePickerStyle = .wheels
}
#endif
}
deinit {
datePicker.removeTarget(self, action: nil, for: .allEvents)
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow)
datePicker.minimumDate = (row as? DatePickerRowProtocol)?.minimumDate
datePicker.maximumDate = (row as? DatePickerRowProtocol)?.maximumDate
if let minuteIntervalValue = (row as? DatePickerRowProtocol)?.minuteInterval {
datePicker.minuteInterval = minuteIntervalValue
}
if row.isHighlighted {
textLabel?.textColor = tintColor
}
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
override open var inputView: UIView? {
if let v = row.value {
datePicker.setDate(v, animated:row is CountDownRow)
}
return datePicker
}
@objc(datePickerValueDidChange:) func datePickerValueDidChange(_ sender: UIDatePicker) {
row.value = sender.date
detailTextLabel?.text = row.displayValueFor?(row.value)
}
private func datePickerMode() -> UIDatePicker.Mode {
switch row {
case is DateRow:
return .date
case is TimeRow:
return .time
case is DateTimeRow:
return .dateAndTime
case is CountDownRow:
return .countDownTimer
default:
return .date
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return canBecomeFirstResponder
}
override open var canBecomeFirstResponder: Bool {
return !row.isDisabled
}
}
open class _DateFieldRow: Row<DateCell>, DatePickerRowProtocol, NoValueDisplayTextConformance {
/// The minimum value for this row's UIDatePicker
open var minimumDate: Date?
/// The maximum value for this row's UIDatePicker
open var maximumDate: Date?
/// The interval between options for this row's UIDatePicker
open var minuteInterval: Int?
/// The formatter for the date picked by the user
open var dateFormatter: DateFormatter?
open var noValueDisplayText: String? = nil
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let val = value, let formatter = self.dateFormatter else { return nil }
return formatter.string(from: val)
}
}
}
| mit | d0cf6e4e763d99ec561504549b2db217 | 32.451389 | 112 | 0.668051 | 4.905295 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/UIConstants.swift | 2 | 1742 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import Shared
extension UIColor {
// These are defaults from http://design.firefox.com/photon/visuals/color.html
struct Defaults {
static let MobileGreyF = UIColor(rgb: 0x636369)
static let iOSTextHighlightBlue = UIColor(rgb: 0xccdded) // This color should exactly match the ios text highlight
static let Purple60A30 = UIColor(rgba: 0x8000d74c)
static let MobilePrivatePurple = UIColor.Photon.Purple60
// Reader Mode Sepia
static let LightBeige = UIColor(rgb: 0xf0e6dc)
}
}
public struct UIConstants {
static let DefaultPadding: CGFloat = 10
static let SnackbarButtonHeight: CGFloat = 57
static let TopToolbarHeight: CGFloat = 56
static let TopToolbarHeightMax: CGFloat = 75
static var ToolbarHeight: CGFloat = 46
static let SystemBlueColor = UIColor.Photon.Blue40
// Static fonts
static let DefaultChromeSize: CGFloat = 16
static let DefaultChromeSmallSize: CGFloat = 11
static let PasscodeEntryFontSize: CGFloat = 36
static let DefaultChromeFont = UIFont.systemFont(ofSize: DefaultChromeSize, weight: UIFont.Weight.regular)
static let DefaultChromeSmallFontBold = UIFont.boldSystemFont(ofSize: DefaultChromeSmallSize)
static let PasscodeEntryFont = UIFont.systemFont(ofSize: PasscodeEntryFontSize, weight: UIFont.Weight.bold)
/// JPEG compression quality for persisted screenshots. Must be between 0-1.
static let ScreenshotQuality: Float = 0.3
static let ActiveScreenshotQuality: CGFloat = 0.5
}
| mpl-2.0 | 3e8c839dbb36406816ea8fff386c6d10 | 42.55 | 122 | 0.742824 | 4.455243 | false | false | false | false |
huahuasj/ios-charts | Charts/Classes/Data/LineChartDataSet.swift | 3 | 3460 | //
// LineChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIColor
public class LineChartDataSet: LineRadarChartDataSet
{
public var circleColors = [UIColor]()
public var circleHoleColor = UIColor.whiteColor()
public var circleRadius = CGFloat(8.0)
private var _cubicIntensity = CGFloat(0.2)
public var lineDashPhase = CGFloat(0.0)
public var lineDashLengths: [CGFloat]!
/// if true, drawing circles is enabled
public var drawCirclesEnabled = true
/// if true, cubic lines are drawn instead of linear
public var drawCubicEnabled = false
public var drawCircleHoleEnabled = true;
public override init()
{
super.init();
circleColors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0));
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label);
circleColors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0));
}
/// intensity for cubic lines (min = 0.05f, max = 1f)
/// :default: 0.2
public var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity;
}
set
{
_cubicIntensity = newValue;
if (_cubicIntensity > 1.0)
{
_cubicIntensity = 1.0;
}
if (_cubicIntensity < 0.05)
{
_cubicIntensity = 0.05;
}
}
}
/// Returns the color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
public func getCircleColor(var index: Int) -> UIColor?
{
let size = circleColors.count;
index = index % size;
if (index >= size)
{
return nil;
}
return circleColors[index];
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
public func setCircleColor(color: UIColor)
{
circleColors.removeAll(keepCapacity: false);
circleColors.append(color);
}
/// resets the circle-colors array and creates a new one
public func resetCircleColors(var index: Int)
{
circleColors.removeAll(keepCapacity: false);
}
public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled; }
public var isDrawCubicEnabled: Bool { return drawCubicEnabled; }
public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled; }
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! LineChartDataSet;
copy.circleColors = circleColors;
copy.circleRadius = circleRadius;
copy.cubicIntensity = cubicIntensity;
copy.lineDashPhase = lineDashPhase;
copy.lineDashLengths = lineDashLengths;
copy.drawCirclesEnabled = drawCirclesEnabled;
copy.drawCubicEnabled = drawCubicEnabled;
return copy;
}
}
| apache-2.0 | 16816712ab1aaceded22e2e4b6e9d1cb | 28.322034 | 106 | 0.622254 | 4.650538 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Authentication/Interface/Descriptions/ScreenDescriptions/Login/ReauthenticateWithCompanyLoginStepDescription.swift | 1 | 1352 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class ReauthenticateWithCompanyLoginStepDescription: AuthenticationStepDescription {
let backButton: BackButtonDescription?
let mainView: ViewDescriptor & ValueSubmission
let headline: String
let subtext: String?
let secondaryView: AuthenticationSecondaryViewDescription?
init() {
backButton = BackButtonDescription()
headline = "registration.signin.title".localized
subtext = "signin_logout.sso.subheadline".localized
mainView = SolidButtonDescription(title: "signin_logout.sso.buton".localized, accessibilityIdentifier: "company_login")
secondaryView = nil
}
}
| gpl-3.0 | 65d3271ce83ced3acb2948fcf259c347 | 34.578947 | 127 | 0.743343 | 4.646048 | false | false | false | false |
tnantoka/edhita | Edhita/Views/EditorView.swift | 1 | 4156 | //
// EditorView.swift
// Edhita
//
// Created by Tatsuya Tobioka on 2022/07/26.
//
import Introspect
import SwiftUI
struct EditorView: View {
enum Mode: String, CaseIterable, Identifiable {
case edit = "Edit"
case preview = "Preview"
case split = "Split"
var id: String { rawValue }
}
let item: FinderItem
@State private var content = ""
@State private var mode = Mode.edit
@State private var reloader = false
@State private var isPresentedActivity = false
@State private var textView: UITextView?
var webView: PreviewWebView {
PreviewWebView(url: item.url, reloader: reloader)
}
var body: some View {
HStack(spacing: 0.0) {
if mode == .edit || mode == .split {
TextEditor(text: $content)
.padding(.all, 8.0)
.onChange(of: content) { content in
item.update(content: content)
reloader.toggle()
}
.background(Settings.shared.backgroundColor)
.foregroundColor(Settings.shared.textColor)
.font(.custom(Settings.shared.fontName, size: Settings.shared.fontSize))
.disabled(!item.isEditable)
.introspectTextView(customize: { textView in
self.textView = textView
})
}
if mode == .split {
Color
.black
.opacity(0.12)
.frame(width: 1.0)
}
if mode == .preview || mode == .split {
webView
}
}
.navigationTitle(item.url.lastPathComponent)
.navigationBarTitleDisplayMode(.inline)
.onAppear {
self.content =
item.isEditable
? item.content : NSLocalizedString("The item cannot be edited", comment: "")
}
.onAppear {
UITextView.appearance().backgroundColor = .clear
}.onDisappear {
UITextView.appearance().backgroundColor = nil
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Picker("", selection: $mode) {
ForEach(Mode.allCases) {
mode in
Text(NSLocalizedString(mode.rawValue, comment: "")).tag(mode)
}
}
.pickerStyle(.segmented)
}
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
HStack {
Button(
action: {
isPresentedActivity.toggle()
},
label: {
Image(systemName: "square.and.arrow.up")
}
)
Button(
action: {
reloader.toggle()
},
label: {
Image(systemName: "arrow.clockwise")
}
)
.disabled(mode == .edit)
Spacer()
Text(String(format: NSLocalizedString("Chars: %d", comment: ""), content.count))
}
}
}
.toolbar {
ToolbarItem(placement: .keyboard) {
if let textView = textView, Settings.shared.keyboardAccessory {
AccessoryView(textView: textView)
}
}
}
.sheet(isPresented: $isPresentedActivity) {
ActivityView(activityItems: item.activityItems)
}
}
}
struct EditorView_Previews: PreviewProvider {
static var previews: some View {
let url = Bundle.main.url(
forResource: "root_file", withExtension: "txt", subdirectory: "root")!
let item = FinderItem(url: url)
NavigationView {
EditorView(item: item)
}
}
}
| mit | c589892a0b1e78a9a90144f169f5833d | 30.969231 | 100 | 0.462464 | 5.43268 | false | false | false | false |
designatednerd/SwiftSnake-tvOS | SwiftSnake/SwiftSnake/SKNodes/FoodNode.swift | 2 | 931 | //
// Food.swift
// SwiftSnake
//
// Created by Ellen Shapiro (Vokal) on 9/24/15.
// Copyright © 2015 Vokal. All rights reserved.
//
import Foundation
import SpriteKit
class FoodNode: SKLabelNode {
/**
Factory method
- returns: A new food node with a random food emoji.
*/
static func makeFood() -> FoodNode {
let food = FoodNode.randomFood()
let node = FoodNode(text: food)
node.name = NodeName.Food.rawValue
node.physicsBody?.categoryBitMask = NodeBitmask.Food.rawValue
return node
}
/**
- returns: A random food emoji string.
*/
private static func randomFood() -> String {
let foods = [
"🍔",
"🍆",
"🍕",
"🍖",
"🍅",
]
let randomIndex = Int(arc4random_uniform(UInt32(foods.count)))
return foods[randomIndex]
}
} | mit | 55e390950739343b0323eab1bc0297dc | 20.809524 | 70 | 0.547541 | 4.140271 | false | false | false | false |
keitaoouchi/RxAudioVisual | RxAudioVisualTests/AVPlayerItem+RxSpec.swift | 1 | 6589 | import Quick
import Nimble
import RxSwift
import AVFoundation
@testable import RxAudioVisual
class AVPlayerItemSpec: QuickSpec {
override func spec() {
describe("KVO through rx") {
var asset: AVAsset!
var item: AVPlayerItem!
var player: AVPlayer!
var disposeBag: DisposeBag!
beforeEach {
asset = AVAsset(url: TestHelper.sampleURL)
item = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: item)
disposeBag = DisposeBag()
}
afterEach {
player.pause()
}
it("should load asset") {
var e: AVAsset?
item.rx.asset.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(asset))
}
it("should load duration") {
var e: CMTime?
item.rx.duration.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventuallyNot(equal(kCMTimeZero))
}
it("should load loadedTimeRanges") {
var e: [NSValue]?
item.rx.loadedTimeRanges.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventuallyNot(beEmpty())
}
it("should load presentationSize") {
var e: CMTime?
item.rx.presentationSize.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(kCMTimeZero))
}
it("should load status") {
var e: AVPlayerItemStatus?
item.rx.status.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
// FIXME: WHY???
//expect(e).toEventually(equal(AVPlayerItemStatus.readyToPlay))
}
it("should load timebase") {
var e: CMTimebase?
item.rx.timebase.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
it("should load tracks") {
var e: [AVPlayerItemTrack]?
item.rx.tracks.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventuallyNot(beEmpty())
}
it("should load seekableTimeRanges") {
var e: [NSValue]?
item.rx.seekableTimeRanges.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventuallyNot(beEmpty())
}
it("should load isPlaybackLikelyToKeepUp") {
var e: Bool?
item.rx.isPlaybackLikelyToKeepUp.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
player.play()
}
it("should load isPlaybackBufferEmpty") {
var e: Bool?
item.rx.isPlaybackBufferEmpty.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
it("should load isPlaybackBufferFull") {
player.play()
var e: Bool?
item.rx.isPlaybackBufferFull.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
}
describe("Notification through rx") {
var asset: AVAsset!
var item: AVPlayerItem!
var disposeBag: DisposeBag!
beforeEach {
let path = Bundle(for: AVPlayerItemSpec.self).path(forResource: "sample", ofType: "mov")
let url = URL(string: path!)
asset = AVAsset(url: url!)
item = AVPlayerItem(asset: asset)
disposeBag = DisposeBag()
}
it("should not receive didPlayToEnd of another item") {
var e: Notification? = nil
item.rx.didPlayToEnd.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
let anotherItem = AVPlayerItem(asset: asset)
NotificationCenter.default.post(name: .AVPlayerItemDidPlayToEndTime, object: anotherItem)
expect(e).toEventually(beNil())
}
it("should receive didPlayToEnd") {
var e: Notification? = nil
item.rx.didPlayToEnd.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemDidPlayToEndTime, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemDidPlayToEndTime))
}
it("should receive timeJumped") {
var e: Notification? = nil
item.rx.timeJumped.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemTimeJumped, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemTimeJumped))
}
it("should receive failedToPlayToEndTime") {
var e: Notification? = nil
item.rx.failedToPlayToEndTime.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemFailedToPlayToEndTime, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemFailedToPlayToEndTime))
}
it("should receive playbackStalled") {
var e: Notification? = nil
item.rx.playbackStalled.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemPlaybackStalled, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemPlaybackStalled))
}
it("should receive newAccessLogEntry") {
var e: Notification? = nil
item.rx.newAccessLogEntry.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemNewAccessLogEntry, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemNewAccessLogEntry))
}
it("should receive newErrorLogEntry") {
var e: Notification? = nil
item.rx.newErrorLogEntry.subscribe(onNext: { v in
e = v
}).disposed(by: disposeBag)
NotificationCenter.default.post(name: .AVPlayerItemNewErrorLogEntry, object: item)
expect(e).toEventuallyNot(beNil())
expect(e!.name).to(equal(Notification.Name.AVPlayerItemNewErrorLogEntry))
}
}
}
}
| mit | d869dd2147d00363ba0bf2580e7d1149 | 32.963918 | 99 | 0.624829 | 4.349175 | false | false | false | false |
aatalyk/swift-algorithm-club | Breadth-First Search/Tests/BreadthFirstSearchTests.swift | 13 | 2736 | import XCTest
class BreadthFirstSearchTests: XCTestCase {
func testExploringTree() {
let tree = Graph()
let nodeA = tree.addNode("a")
let nodeB = tree.addNode("b")
let nodeC = tree.addNode("c")
let nodeD = tree.addNode("d")
let nodeE = tree.addNode("e")
let nodeF = tree.addNode("f")
let nodeG = tree.addNode("g")
let nodeH = tree.addNode("h")
tree.addEdge(nodeA, neighbor: nodeB)
tree.addEdge(nodeA, neighbor: nodeC)
tree.addEdge(nodeB, neighbor: nodeD)
tree.addEdge(nodeB, neighbor: nodeE)
tree.addEdge(nodeC, neighbor: nodeF)
tree.addEdge(nodeC, neighbor: nodeG)
tree.addEdge(nodeE, neighbor: nodeH)
let nodesExplored = breadthFirstSearch(tree, source: nodeA)
XCTAssertEqual(nodesExplored, ["a", "b", "c", "d", "e", "f", "g", "h"])
}
func testExploringGraph() {
let graph = Graph()
let nodeA = graph.addNode("a")
let nodeB = graph.addNode("b")
let nodeC = graph.addNode("c")
let nodeD = graph.addNode("d")
let nodeE = graph.addNode("e")
let nodeF = graph.addNode("f")
let nodeG = graph.addNode("g")
let nodeH = graph.addNode("h")
let nodeI = graph.addNode("i")
graph.addEdge(nodeA, neighbor: nodeB)
graph.addEdge(nodeA, neighbor: nodeH)
graph.addEdge(nodeB, neighbor: nodeA)
graph.addEdge(nodeB, neighbor: nodeC)
graph.addEdge(nodeB, neighbor: nodeH)
graph.addEdge(nodeC, neighbor: nodeB)
graph.addEdge(nodeC, neighbor: nodeD)
graph.addEdge(nodeC, neighbor: nodeF)
graph.addEdge(nodeC, neighbor: nodeI)
graph.addEdge(nodeD, neighbor: nodeC)
graph.addEdge(nodeD, neighbor: nodeE)
graph.addEdge(nodeD, neighbor: nodeF)
graph.addEdge(nodeE, neighbor: nodeD)
graph.addEdge(nodeE, neighbor: nodeF)
graph.addEdge(nodeF, neighbor: nodeC)
graph.addEdge(nodeF, neighbor: nodeD)
graph.addEdge(nodeF, neighbor: nodeE)
graph.addEdge(nodeF, neighbor: nodeG)
graph.addEdge(nodeG, neighbor: nodeF)
graph.addEdge(nodeG, neighbor: nodeH)
graph.addEdge(nodeG, neighbor: nodeI)
graph.addEdge(nodeH, neighbor: nodeA)
graph.addEdge(nodeH, neighbor: nodeB)
graph.addEdge(nodeH, neighbor: nodeG)
graph.addEdge(nodeH, neighbor: nodeI)
graph.addEdge(nodeI, neighbor: nodeC)
graph.addEdge(nodeI, neighbor: nodeG)
graph.addEdge(nodeI, neighbor: nodeH)
let nodesExplored = breadthFirstSearch(graph, source: nodeA)
XCTAssertEqual(nodesExplored, ["a", "b", "h", "c", "g", "i", "d", "f", "e"])
}
func testExploringGraphWithASingleNode() {
let graph = Graph()
let node = graph.addNode("a")
let nodesExplored = breadthFirstSearch(graph, source: node)
XCTAssertEqual(nodesExplored, ["a"])
}
}
| mit | 813e618c3a8eb6b612d2e2ad57564b45 | 31.188235 | 80 | 0.667763 | 3.41573 | false | true | false | false |
SASAbus/SASAbus-ios | SASAbus/Configuration.swift | 1 | 2297 | //
// Configuration.swift
// SASAbus
//
// Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]>
//
// This file is part of SASAbus.
//
// SASAbus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SASAbus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SASAbus. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
struct Configuration {
static let dataFolder = ""
static let dataUrl:String = ""
// Router
static let timeoutInterval = 0.0
//download
static let downloadTimeoutIntervalForResource = 0.0
static let downloadTimeoutIntervalForRequest = 0.0
//realtime information
static let realTimeDataUrl = ""
//privacy
static let privacyBaseUrl = ""
//map
static let mapDownloadZip = ""
static let mapTilesDirectory = ""
static let mapOnlineTiles = ""
static let mapStandardLatitude = 0.0
static let mapStandardLongitude = 0.0
static let mapStandardZoom = 0
static let mapHowOftenShouldIAskForMapDownload = 0
//parkinglot
static let parkingLotBaseUrl = ""
//news
static let newsApiUrl = ""
//beacon survey (bus)
static let beaconUid = ""
static let beaconIdentifier = ""
static let beaconSecondsInBus = 0
static let beaconMinTripDistance = 0
static let beaconLastSeenTreshold = 0
//beacon stationdetection (busstops)
static let busStopBeaconUid = ""
static let busStopBeaconIdentifier = ""
static let busStopValiditySeconds = 0
//survey
static let surveyApiUrl = ""
static let surveyApiUsername = ""
static let surveyApiPassword = ""
static let surveyRecurringTimeDefault = 0
//busstop
static let busStopDistanceTreshold = 0.0
} | gpl-3.0 | fd5ccb8f6046cb59cb4884e59f008908 | 27.358025 | 118 | 0.688589 | 4.323917 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/View/Question/QuestionBodyCell.swift | 1 | 3738 | //
// QuestionBodyCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/3/25.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
import DTCoreText
@objc protocol QuestionBodyCellLinkButtonDelegate {
optional func didPressLinkButton(linkButton: DTLinkButton)
optional func didLongPressLinkButton(linkButton: DTLinkButton)
}
class QuestionBodyCell: DTAttributedTextCell, DTAttributedTextContentViewDelegate {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var borderA: UIView!
@IBOutlet weak var borderB: UIView!
@IBOutlet weak var borderC: UIView!
weak var lazyImageViewDelegate: DTLazyImageViewDelegate?
weak var linkButtonDelegate: QuestionBodyCellLinkButtonDelegate?
override func awakeFromNib() {
super.awakeFromNib()
msr_scrollView?.delaysContentTouches = false
backgroundColor = UIColor.clearColor()
contentView.backgroundColor = UIColor.clearColor()
attributedTextContextView.backgroundColor = UIColor.clearColor()
attributedTextContextView.delegate = self
attributedTextContextView.shouldDrawImages = true
attributedTextContextView.shouldDrawLinks = true
attributedTextContextView.edgeInsets = UIEdgeInsets(top: 10, left: 18, bottom: 10, right: 18)
let theme = SettingsManager.defaultManager.currentTheme
containerView.backgroundColor = theme.backgroundColorA
for v in [borderA, borderB, borderC] {
v.backgroundColor = theme.borderColorA
}
}
func update(#question: Question?) {
if question?.body != nil {
let theme = SettingsManager.defaultManager.currentTheme
setHTMLString(question?.body ?? "加载中……",
options: [
DTDefaultFontName: UIFont.systemFontOfSize(0).fontName,
DTDefaultFontSize: 16,
DTDefaultTextColor: theme.bodyTextColor,
DTDefaultLineHeightMultiplier: 1.5,
DTDefaultLinkColor: UIColor.msr_materialLightBlue(),
DTDefaultLinkDecoration: true
])
}
setNeedsLayout()
layoutIfNeeded()
}
func attributedTextContentView(attributedTextContentView: DTAttributedTextContentView!, viewForAttachment attachment: DTTextAttachment!, frame: CGRect) -> UIView! {
if attachment is DTImageTextAttachment {
let imageView = DTLazyImageView(frame: frame)
imageView.delegate = lazyImageViewDelegate
imageView.url = attachment.contentURL
return imageView
}
return nil
}
func attributedTextContentView(attributedTextContentView: DTAttributedTextContentView!, viewForLink url: NSURL!, identifier: String!, frame: CGRect) -> UIView! {
let button = DTLinkButton()
button.URL = url
button.GUID = identifier
button.frame = frame
button.showsTouchWhenHighlighted = true
button.minimumHitSize = CGSize(width: 44, height: 44)
button.addTarget(self, action: "linkButton:forEvent:", forControlEvents: .TouchUpInside)
button.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "linkButton:"))
return button
}
func linkButton(linkButton: DTLinkButton, forEvent event: UIEvent) {
linkButtonDelegate?.didPressLinkButton?(linkButton)
}
func linkButton(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .Began {
linkButtonDelegate?.didLongPressLinkButton?(recognizer.view as! DTLinkButton)
}
}
}
| gpl-2.0 | 1cff9f10d2c3be3d56fe9b4d40e109b4 | 39.064516 | 168 | 0.683575 | 5.423581 | false | false | false | false |
cardstream/iOS-SDK | cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/CSArrayType+Extensions.swift | 4 | 3152 | //
// _ArrayType+Extensions.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public protocol CSArrayType: RangeReplaceableCollection {
func cs_arrayValue() -> [Iterator.Element]
}
extension Array: CSArrayType {
public func cs_arrayValue() -> [Iterator.Element] {
return self
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func toHexString() -> String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.characters.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func md5() -> [Iterator.Element] {
return Digest.md5(cs_arrayValue())
}
public func sha1() -> [Iterator.Element] {
return Digest.sha1(cs_arrayValue())
}
public func sha224() -> [Iterator.Element] {
return Digest.sha224(cs_arrayValue())
}
public func sha256() -> [Iterator.Element] {
return Digest.sha256(cs_arrayValue())
}
public func sha384() -> [Iterator.Element] {
return Digest.sha384(cs_arrayValue())
}
public func sha512() -> [Iterator.Element] {
return Digest.sha512(cs_arrayValue())
}
public func sha2(_ variant: SHA2.Variant) -> [Iterator.Element] {
return Digest.sha2(cs_arrayValue(), variant: variant)
}
public func sha3(_ variant: SHA3.Variant) -> [Iterator.Element] {
return Digest.sha3(cs_arrayValue(), variant: variant)
}
public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 {
return Checksum.crc32(cs_arrayValue(), seed: seed, reflect: reflect)
}
public func crc16(seed: UInt16? = nil) -> UInt16 {
return Checksum.crc16(cs_arrayValue(), seed: seed)
}
public func encrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.encrypt(cs_arrayValue().slice)
}
public func decrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.decrypt(cs_arrayValue().slice)
}
public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Iterator.Element] {
return try authenticator.authenticate(cs_arrayValue())
}
}
| gpl-3.0 | 1b550dc966f77991530bfb0bb30baaf4 | 32.521277 | 217 | 0.660425 | 4.151515 | false | false | false | false |
SoneeJohn/WWDC | ThrowBack/TBPreferences.swift | 1 | 11227 | //
// TBPreferences.swift
// WWDC
//
// Created by Guilherme Rambo on 13/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
public final class TBPreferences {
public static let shared: TBPreferences = TBPreferences()
var presentedVersionFiveMigrationPrompt: Bool {
get {
return UserDefaults.standard.bool(forKey: #function)
}
set {
UserDefaults.standard.set(newValue, forKey: #function)
}
}
// MARK: - Legacy Preferences
fileprivate let defaults = UserDefaults.standard
fileprivate let nc = NotificationCenter.default
// keys for NSUserDefault's dictionary
fileprivate struct Keys {
static let mainWindowFrame = "mainWindowFrame"
static let localVideoStoragePath = "localVideoStoragePath"
static let lastVideoWindowScale = "lastVideoWindowScale"
static let autoplayLiveEvents = "autoplayLiveEvents"
static let liveEventCheckInterval = "liveEventCheckInterval"
static let userKnowsLiveEventThing = "userKnowsLiveEventThing"
static let tvTechTalksAlerted = "tvTechTalksAlerted"
static let automaticRefreshEnabled = "automaticRefreshEnabled"
static let floatOnTopEnabled = "floatOnTopEnabled"
static let automaticRefreshSuggestionPresentedAt = "automaticRefreshSuggestionPresentedAt"
struct transcript {
static let font = "transcript.font"
static let textColor = "transcript.textColor"
static let bgColor = "transcript.bgColor"
}
struct VideosController {
static let selectedItem = "VideosController.selectedItem"
static let searchTerm = "VideosController.searchTerm"
static let dividerPosition = "VideosController.dividerPosition"
}
}
// default values if preferences were not set
fileprivate struct DefaultValues {
static let localVideoStoragePath = NSString.path(withComponents: [NSHomeDirectory(), "Library", "Application Support", "WWDC"])
static let lastVideoWindowScale = CGFloat(100.0)
static let autoplayLiveEvents = true
static let liveEventCheckInterval = 15.0
static let userKnowsLiveEventThing = false
static let tvTechTalksAlerted = false
static let automaticRefreshEnabled = true
static let automaticRefreshIntervalOnWWDCWeek = 900.0
static let automaticRefreshIntervalRegular = 3600.0
static let floatOnTopEnabled = false
static let automaticRefreshSuggestionPresentedAt = Date.distantPast
struct transcript {
static let font = NSFont(name: "Avenir Next", size: 16.0)!
static let textColor = NSColor.black
static let bgColor = NSColor.white
}
struct VideosController {
static let selectedItem = -1
static let searchTerm = ""
static let dividerPosition = 260.0
}
}
// the main window's frame
var mainWindowFrame: NSRect {
set {
defaults.set(NSStringFromRect(newValue), forKey: Keys.mainWindowFrame)
}
get {
if let rectString = defaults.object(forKey: Keys.mainWindowFrame) as? String {
return NSRectFromString(rectString)
} else {
return NSZeroRect
}
}
}
// the selected session on the list
var selectedSession: Int {
set {
defaults.set(newValue, forKey: Keys.VideosController.selectedItem)
}
get {
if let item = defaults.object(forKey: Keys.VideosController.selectedItem) as? Int {
return item
} else {
return DefaultValues.VideosController.selectedItem
}
}
}
// the splitView's divider position
var dividerPosition: CGFloat {
set {
defaults.set(NSNumber(value: Double(newValue)), forKey: Keys.VideosController.dividerPosition)
}
get {
if let width = defaults.object(forKey: Keys.VideosController.dividerPosition) as? NSNumber {
return CGFloat(width.doubleValue)
} else {
return CGFloat(DefaultValues.VideosController.dividerPosition)
}
}
}
// the search term
var searchTerm: String {
set {
defaults.set(newValue, forKey: Keys.VideosController.searchTerm)
}
get {
if let term = defaults.object(forKey: Keys.VideosController.searchTerm) as? String {
return term
} else {
return DefaultValues.VideosController.searchTerm
}
}
}
// where to save downloaded videos
public var localVideoStoragePath: String {
set {
defaults.set(newValue, forKey: Keys.localVideoStoragePath)
}
get {
if let path = defaults.object(forKey: Keys.localVideoStoragePath) as? String {
return path
} else {
return DefaultValues.localVideoStoragePath
}
}
}
// the transcript font
var transcriptFont: NSFont {
set {
// NSFont can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob
let data = NSKeyedArchiver.archivedData(withRootObject: newValue)
defaults.set(data, forKey: Keys.transcript.font)
}
get {
if let fontData = defaults.data(forKey: Keys.transcript.font) {
if let font = NSKeyedUnarchiver.unarchiveObject(with: fontData) as? NSFont {
return font
} else {
return DefaultValues.transcript.font
}
} else {
return DefaultValues.transcript.font
}
}
}
// the transcript's text color
var transcriptTextColor: NSColor {
// NSColor can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob
set {
let colorData = NSKeyedArchiver.archivedData(withRootObject: newValue)
defaults.set(colorData, forKey: Keys.transcript.textColor)
}
get {
if let colorData = defaults.data(forKey: Keys.transcript.textColor) {
if let color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? NSColor {
return color
} else {
return DefaultValues.transcript.textColor
}
} else {
return DefaultValues.transcript.textColor
}
}
}
// the transcript's background color
var transcriptBgColor: NSColor {
// NSColor can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob
set {
let colorData = NSKeyedArchiver.archivedData(withRootObject: newValue)
defaults.set(colorData, forKey: Keys.transcript.bgColor)
}
get {
if let colorData = defaults.data(forKey: Keys.transcript.bgColor) {
if let color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? NSColor {
return color
} else {
return DefaultValues.transcript.bgColor
}
} else {
return DefaultValues.transcript.bgColor
}
}
}
// the last scale selected for the video window
var lastVideoWindowScale: CGFloat {
get {
if let scale = defaults.object(forKey: Keys.lastVideoWindowScale) as? NSNumber {
return CGFloat(scale.doubleValue)
} else {
return DefaultValues.lastVideoWindowScale
}
}
set {
defaults.set(NSNumber(value: Double(newValue)), forKey: Keys.lastVideoWindowScale)
}
}
// play live events automatically or not
var autoplayLiveEvents: Bool {
get {
if let object = defaults.object(forKey: Keys.autoplayLiveEvents) as? NSNumber {
return object.boolValue
} else {
return DefaultValues.autoplayLiveEvents
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.autoplayLiveEvents)
}
}
// how often to check for live events (in seconds)
var liveEventCheckInterval: Double {
get {
if let object = defaults.object(forKey: Keys.liveEventCheckInterval) as? NSNumber {
return object.doubleValue
} else {
return DefaultValues.liveEventCheckInterval
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.liveEventCheckInterval)
}
}
// user was informed about the possibility to watch the live keynote here :)
var userKnowsLiveEventThing: Bool {
get {
if let object = defaults.object(forKey: Keys.userKnowsLiveEventThing) as? NSNumber {
return object.boolValue
} else {
return DefaultValues.userKnowsLiveEventThing
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.userKnowsLiveEventThing)
}
}
// user was informed about the possibility to watch the 2016 Apple TV Tech Talks
var tvTechTalksAlerted: Bool {
get {
if let object = defaults.object(forKey: Keys.tvTechTalksAlerted) as? NSNumber {
return object.boolValue
} else {
return DefaultValues.tvTechTalksAlerted
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.tvTechTalksAlerted)
}
}
// periodically refresh the list of sessions
var automaticRefreshEnabled: Bool {
get {
if let object = defaults.object(forKey: Keys.automaticRefreshEnabled) as? NSNumber {
return object.boolValue
} else {
return DefaultValues.automaticRefreshEnabled
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.automaticRefreshEnabled)
}
}
var floatOnTopEnabled: Bool {
get {
if let object = defaults.object(forKey: Keys.floatOnTopEnabled) as? NSNumber {
return object.boolValue
} else {
return DefaultValues.floatOnTopEnabled
}
}
set {
defaults.set(NSNumber(value: newValue), forKey: Keys.floatOnTopEnabled)
}
}
var automaticRefreshSuggestionPresentedAt: Date? {
get {
if let object = defaults.object(forKey: Keys.automaticRefreshSuggestionPresentedAt) as? Date {
return object
} else {
return DefaultValues.automaticRefreshSuggestionPresentedAt
}
}
set {
defaults.set(newValue, forKey: Keys.automaticRefreshSuggestionPresentedAt)
}
}
}
| bsd-2-clause | d272dcf62f97816297e9698afc92610b | 33.863354 | 135 | 0.597898 | 5.238451 | false | false | false | false |
JudoPay/JudoKit | Source/Amount.swift | 1 | 5544 | //
// JudoErrors.swift
// Judo
//
// Copyright (c) 2016 Alternative Payments 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 Foundation
/**
**Amount**
Amount object stores information about an amount and the corresponding currency for a transaction
*/
public struct Amount: ExpressibleByStringLiteral {
/// The currency ISO Code - GBP is default
public var currency: Currency = .GBP
/// The amount to process, to two decimal places
public var amount: NSDecimalNumber
/**
Initializer for amount
- parameter decimalNumber: a decimal number with the value of an amount to transact
- parameter currency: the currency of the amount to transact
- returns: an Amount object
*/
public init(decimalNumber: NSDecimalNumber, currency: Currency) {
self.currency = currency
self.amount = decimalNumber
}
/**
Initializer for Amount
- parameter amountString: a string with the value of an amount to transact
- parameter currency: the currency of the amount to transact
- returns: an Amount object
*/
public init(amountString: String, currency: Currency) {
self.amount = NSDecimalNumber(string: amountString)
self.currency = currency
}
/**
possible patterns for initializing with a string literal
- 12 GBP
- 12GBP
- parameter value: a string value holding a currency and an amount
- returns: an Amount object
*/
init(amount value: String) {
let last3 = value.index(value.endIndex, offsetBy: -3)
self.amount = NSDecimalNumber(string: String(value[..<last3]))
self.currency = Currency(String(value[last3...]))
}
public init(stringLiteral value: String) {
let last3 = value.index(value.endIndex, offsetBy: -3)
self.amount = NSDecimalNumber(string: String(value[..<last3]))
self.currency = Currency(String(value[last3...]))
}
public init(extendedGraphemeClusterLiteral value: String) {
let last3 = value.index(value.endIndex, offsetBy: -3)
self.amount = NSDecimalNumber(string: String(value[..<last3]))
self.currency = Currency(String(value[last3...]))
}
public init(unicodeScalarLiteral value: String) {
let last3 = value.index(value.endIndex, offsetBy: -3)
self.amount = NSDecimalNumber(string: String(value[..<last3]))
self.currency = Currency(String(value[last3...]))
}
}
/// Collection of static identifiers for all supported currencies
public struct Currency {
/// Raw value of the currency as a String
public let rawValue: String
/**
Designated initializer
- parameter fromRaw: raw string value of the currency based on ISO standards
- returns: a Currency object
*/
public init(_ fromRaw: String) {
self.rawValue = fromRaw
}
/// Australian Dollars
public static let AUD = Currency("AUD")
/// United Arab Emirates Dirham
public static let AED = Currency("AED")
/// Brazilian Real
public static let BRL = Currency("BRL")
/// Canadian Dollars
public static let CAD = Currency("CAD")
/// Swiss Franks
public static let CHF = Currency("CHF")
/// Czech Republic Koruna
public static let CZK = Currency("CZK")
/// Danish Krone
public static let DKK = Currency("DKK")
/// Euro
public static let EUR = Currency("EUR")
/// British Pound
public static let GBP = Currency("GBP")
/// Hong Kong Dollar
public static let HKD = Currency("HKD")
/// Hungarian Forint
public static let HUF = Currency("HUF")
/// Japanese Yen
public static let JPY = Currency("JPY")
/// Norwegian Krone
public static let NOK = Currency("NOK")
/// New Zealand Dollar
public static let NZD = Currency("NZD")
/// Polish Zloty
public static let PLN = Currency("PLN")
/// Qatari Rial
public static let QAR = Currency("QAR")
/// Saudi Riyal
public static let SAR = Currency("SAR")
/// Swedish Krone
public static let SEK = Currency("SEK")
/// Singapore dollar
public static let SGD = Currency("SGD")
/// United States Dollar
public static let USD = Currency("USD")
/// South African Rand
public static let ZAR = Currency("ZAR")
/// Unsupported Currency
public static let XOR = Currency("Unsupported Currency")
}
| mit | 4ff1655a31fe956f978c70a5cb826e89 | 32.6 | 98 | 0.662698 | 4.467365 | false | false | false | false |
humeng12/DouYuZB | DouYuZB/Pods/Alamofire/Source/Alamofire.swift | 1 | 18655 | //
// Alamofire.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct
/// URL requests.
public protocol URLConvertible {
/// Returns a URL that conforms to RFC 2396 or throws an `Error`.
///
/// - throws: An `Error` if the type cannot be converted to a `URL`.
///
/// - returns: A URL or throws an `Error`.
func asURL() throws -> URL
}
extension String: URLConvertible {
/// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`.
///
/// - throws: An `AFError.invalidURL` if `self` is not a valid URL string.
///
/// - returns: A URL or throws an `AFError`.
public func asURL() throws -> URL {
guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) }
return url
}
}
extension URL: URLConvertible {
/// Returns self.
public func asURL() throws -> URL { return self }
}
extension URLComponents: URLConvertible {
/// Returns a URL if `url` is not nil, otherise throws an `Error`.
///
/// - throws: An `AFError.invalidURL` if `url` is `nil`.
///
/// - returns: A URL or throws an `AFError`.
public func asURL() throws -> URL {
guard let url = url else { throw AFError.invalidURL(url: self) }
return url
}
}
// MARK: -
/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
public protocol URLRequestConvertible {
/// Returns a URL request or throws if an `Error` was encountered.
///
/// - throws: An `Error` if the underlying `URLRequest` is `nil`.
///
/// - returns: A URL request.
func asURLRequest() throws -> URLRequest
}
extension URLRequestConvertible {
/// The URL request.
public var urlRequest: URLRequest? { return try? asURLRequest() }
}
extension URLRequest: URLRequestConvertible {
/// Returns a URL request or throws if an `Error` was encountered.
public func asURLRequest() throws -> URLRequest { return self }
}
// MARK: -
extension URLRequest {
/// Creates an instance with the specified `method`, `urlString` and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The new `URLRequest` instance.
public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
let url = try url.asURL()
self.init(url: url)
httpMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
setValue(headerValue, forHTTPHeaderField: headerField)
}
}
}
func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
guard let adapter = adapter else { return self }
return try adapter.adapt(self)
}
}
// MARK: - Data Request
/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
/// `method`, `parameters`, `encoding` and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@available(iOS 9.0, *)
@discardableResult
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
return SessionManager.default.request(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
/// specified `urlRequest`.
///
/// - parameter urlRequest: The URL request
///
/// - returns: The created `DataRequest`.
@available(iOS 9.0, *)
@discardableResult
public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
return SessionManager.default.request(urlRequest)
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
to: destination
)
}
/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
/// specified `urlRequest` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// - parameter urlRequest: The URL request.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(urlRequest, to: destination)
}
// MARK: Resume Data
/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional
/// information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(resumingWith: resumeData, to: destination)
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `file`.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers)
}
/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `file`.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(fileURL, with: urlRequest)
}
// MARK: Data
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `data`.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(data, to: url, method: method, headers: headers)
}
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `data`.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(data, with: urlRequest)
}
// MARK: InputStream
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `stream`.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(stream, to: url, method: method, headers: headers)
}
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `stream`.
///
/// - parameter urlRequest: The URL request.
/// - parameter stream: The stream to upload.
///
/// - returns: The created `UploadRequest`.
@available(iOS 9.0, *)
@discardableResult
public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(stream, with: urlRequest)
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
@available(iOS 9.0, *)
public func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
{
return SessionManager.default.upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
to: url,
method: method,
headers: headers,
encodingCompletion: encodingCompletion
)
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
@available(iOS 9.0, *)
public func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
{
return SessionManager.default.upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
/// and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@available(iOS 9.0, *)
@discardableResult
public func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return SessionManager.default.stream(withHostName: hostName, port: port)
}
// MARK: NetService
/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@available(iOS 9.0, *)
@discardableResult
public func stream(with netService: NetService) -> StreamRequest {
return SessionManager.default.stream(with: netService)
}
#endif
| mit | e34f18ebc651878e7751bf21359d5ca5 | 38.607219 | 118 | 0.703243 | 4.552221 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch22-KVC/KVC-Collection/KVC-Collection/RootViewController.swift | 1 | 1093 | //
// RootViewController.swift
// KVC-Collection
//
// Created by wj on 15/11/29.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class RootViewController: UIViewController {
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var entryLabel: UILabel!
var array = TimesTwoArray()
@IBAction func performAdd(_ sender: UIButton) {
array.incrementCount()
refresh()
}
func refresh(){
let items = array.value(forKey: "numbers") as AnyObject
let count = items.count
countLabel.text = "\(count!)"
entryLabel.text = (items.lastObject! as AnyObject).description
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let VC = segue.destination as! KVCTableViewController
VC.array = array
}
}
| mit | cf79d96ff4a7b004d4a7f45d41817510 | 25.585366 | 106 | 0.646789 | 4.522822 | false | false | false | false |
haskellswift/swift-package-manager | Fixtures/DependencyResolution/External/IgnoreIndirectTests/deck-of-playing-cards/src/Deck.swift | 4 | 1499 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import FisherYates
import PlayingCard
public struct Deck {
fileprivate var cards: [PlayingCard]
public static func standard52CardDeck() -> Deck {
let suits: [Suit] = [.Spades, .Hearts, .Diamonds, .Clubs]
let ranks: [Rank] = [.Ace, .Two, .Three, .Four, .Five, .Six, .Seven, .Eight, .Nine, .Ten, .Jack, .Queen, .King]
var cards: [PlayingCard] = []
for suit in suits {
for rank in ranks {
cards.append(PlayingCard(rank: rank, suit: suit))
}
}
return Deck(cards)
}
public init(_ cards: [PlayingCard]) {
self.cards = cards
}
public mutating func shuffle() {
cards.shuffleInPlace()
}
public mutating func deal() -> PlayingCard? {
guard !cards.isEmpty else { return nil }
return cards.removeLast()
}
}
// MARK: - ExpressibleByArrayLiteral
extension Deck : ExpressibleByArrayLiteral {
public init(arrayLiteral elements: PlayingCard...) {
self.init(elements)
}
}
// MARK: - Equatable
extension Deck : Equatable {}
public func ==(lhs: Deck, rhs: Deck) -> Bool {
return lhs.cards == rhs.cards
}
| apache-2.0 | 1c210edcb3e16cdf1365ccc7eabfe043 | 23.983333 | 119 | 0.633756 | 4.051351 | false | false | false | false |
limianwang/swift-calculator | Calculator/ViewController.swift | 1 | 2056 | //
// ViewController.swift
// Calculator
//
// Created by Limian Wang on 2015-08-24.
// Copyright (c) 2015 LiTech Ventures Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
// initializing array of doubles
var operandStack = Array<Double>()
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation({ $0 * $1 })
case "÷": performOperation({ $1 / $0 })
case "+": performOperation({ $0 + $1 })
case "−": performOperation({ $1 - $0 })
case "√": performOperation({ sqrt($0) })
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
@nonobjc
func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
}
| mit | 2eb781c3a6fbd99759322885cf9b30c3 | 24.308642 | 90 | 0.587805 | 5.112219 | false | false | false | false |
ben-ng/swift | test/decl/typealias/typealias.swift | 1 | 775 | // RUN: %target-typecheck-verify-swift
typealias rgb = Int32 // expected-note {{declared here}}
var rgb : rgb? // expected-error {{invalid redeclaration of 'rgb'}}
// This used to produce a diagnostic about 'rgba' being used in its own
// type, but arguably that is incorrect, since we are referencing a
// different 'rgba'.
struct Color {
var rgba : rgba? { // expected-error {{'rgba' used within its own type}}
return nil
}
typealias rgba = Int32
}
struct Color2 {
let rgba : rgba?
struct rgba {}
}
typealias Integer = Int
var i: Integer
struct Hair<Style> {
typealias Hairdo = Style
typealias MorningHair = Style?
func fancy() -> Hairdo {}
func wakeUp() -> MorningHair {}
}
typealias FunnyHair = Hair<Color>
var f: FunnyHair
| apache-2.0 | 9b43fbf7547edc3dee56cb998c824e88 | 19.945946 | 76 | 0.672258 | 3.708134 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryToolbar.swift | 1 | 2242 | import UIKit
final class PhotoLibraryToolbar: UIView {
// MARK: - Subviews
private let discardButton = UIButton()
private let confirmButton = UIButton()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
discardButton.addTarget(self, action: #selector(onDiscardButtonTap(_:)), for: .touchUpInside)
confirmButton.addTarget(self, action: #selector(onConfirmButtonTap(_:)), for: .touchUpInside)
addSubview(discardButton)
addSubview(confirmButton)
setUpAccessibilityIdentifiers()
}
private func setUpAccessibilityIdentifiers() {
discardButton.setAccessibilityId(.discardLibraryButton)
confirmButton.setAccessibilityId(.confirmLibraryButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - PhotoLibraryToolbar
var onDiscardButtonTap: (() -> ())?
var onConfirmButtonTap: (() -> ())?
func setDiscardButtonIcon(_ icon: UIImage?) {
discardButton.setImage(icon, for: .normal)
}
func setConfirmButtonIcon(_ icon: UIImage?) {
confirmButton.setImage(icon, for: .normal)
}
// MARK: - UIView
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: size.width, height: 50 + paparazzoSafeAreaInsets.bottom)
}
override func layoutSubviews() {
super.layoutSubviews()
let bottomInset = paparazzoSafeAreaInsets.bottom / 2
discardButton.size = CGSize.minimumTapAreaSize
discardButton.center = CGPoint(
x: bounds.left + bounds.width / 4,
y: bounds.top + bounds.height / 2 - bottomInset
)
confirmButton.size = CGSize.minimumTapAreaSize
confirmButton.center = CGPoint(
x: bounds.right - bounds.width / 4,
y: bounds.top + bounds.height / 2 - bottomInset
)
}
// MARK: - Private
@objc private func onDiscardButtonTap(_: UIButton) {
onDiscardButtonTap?()
}
@objc private func onConfirmButtonTap(_: UIButton) {
onConfirmButtonTap?()
}
}
| mit | b62a59be67c57ab50954a838b8223362 | 29.712329 | 101 | 0.619982 | 5.095455 | false | false | false | false |
tuannme/Up | Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotatePulse.swift | 2 | 4470 | //
// NVActivityIndicatorAnimationBallClipRotatePulse.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 NVActivityIndicatorAnimationBallClipRotatePulse: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
smallCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
bigCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
}
func smallCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Animation
let animation = CAKeyframeAnimation(keyPath:"transform.scale")
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circleSize = size.width / 2
let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func bigCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath:"transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, M_PI, 2 * M_PI]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringTwoHalfVertical.layerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 1a20393423fcdf260e311883ec236de8 | 44.151515 | 137 | 0.673602 | 5.056561 | false | false | false | false |
NetScaleNow-Admin/ios_sdk | NetScaleNow/Classes/CampaignCollectionViewCell.swift | 1 | 2418 | //
// CampaignCollectionViewCell.swift
// Pods
//
// Created by Jonas Stubenrauch on 18.05.17.
//
//
import UIKit
import Foundation
class CampaignCollectionViewCell: UICollectionViewCell {
var heightChangeCallback: (() -> Void)?
// @IBOutlet
// var image: UIImageView!
//
@IBOutlet
var discount: UILabel!
@IBOutlet
var imageView: LeftDrawingImageView!
@IBOutlet
var arrow: UIImageView! {
didSet {
arrow.tintColor = Config.tintColor
}
}
@IBOutlet
var separator: UIView!
@IBOutlet
var detailContainer: UIView!
@IBOutlet
var limitations: UILabel!
var showDetails = false {
didSet {
if (limitations.text != nil && limitations.text!.lengthOfBytes(using: .utf8) > 0){
detailContainer.isHidden = !showDetails
} else {
detailContainer.isHidden = true
}
}
}
@IBAction
func toggleDetails() {
showDetails = !showDetails
heightChangeCallback?()
}
override func prepareForReuse() {
super.prepareForReuse()
showDetails = false
}
override func awakeFromNib() {
super.awakeFromNib()
showDetails = false
contentView.translatesAutoresizingMaskIntoConstraints = false
}
var widthConstraint: NSLayoutConstraint?
var aspectRatioConstraint: NSLayoutConstraint?
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let attributes = super.preferredLayoutAttributesFitting(layoutAttributes)
preferredWidth = attributes.frame.size.width
return attributes
}
var preferredWidth: CGFloat? {
didSet {
guard let preferredWith = preferredWidth else {
return
}
if widthConstraint == nil {
widthConstraint = contentView.widthAnchor.constraint(equalToConstant: preferredWith)
widthConstraint?.isActive = true
}
widthConstraint?.constant = preferredWith
}
}
}
extension CampaignCollectionViewCell {
func show(campaign: Campaign) {
discount.text = campaign.discount
limitations.text = campaign.limitations
if (limitations.text != nil && limitations.text!.lengthOfBytes(using: .utf8) == 0){
limitations.text = campaign.limitationsDescription
}
if let logoUrl = campaign.resizedLogoUrl {
imageView.setImage(image: logoUrl)
}
}
}
| mit | bf2e28c2ad484bb35562d9ac4bf82db4 | 20.589286 | 140 | 0.681969 | 5.058577 | false | false | false | false |
akuraru/PureViewIcon | PureViewIcon/Views/PVICaretLeftCircle.swift | 1 | 2015 | //
// PVICaretLeftCircle.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func makeCaretLeftCircleConstraints() {
base.snp.updateConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = resetTransform()
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 2)
// before
before.top.alpha = 1
before.left.alpha = 0
before.right.alpha = 0
before.bottom.alpha = 0
before.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().dividedBy(14 / 17.0)
make.width.equalToSuperview().multipliedBy(11 / 34.0)
make.height.equalToSuperview().multipliedBy(2 / 34.0)
}
before.view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_4))
// main
main.top.alpha = 0
main.left.alpha = 0
main.right.alpha = 0
main.bottom.alpha = 0
main.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview().multipliedBy(30 / 34.0)
make.height.equalToSuperview().multipliedBy(30 / 34.0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 1
after.left.alpha = 0
after.right.alpha = 0
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().dividedBy(20 / 17.0)
make.width.equalToSuperview().multipliedBy(11 / 34.0)
make.height.equalToSuperview().multipliedBy(2 / 34.0)
}
after.view.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4))
}
}
| mit | 912723fd985d13f0e626df64e2dc1b14 | 30.484375 | 81 | 0.580645 | 4.342672 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.