repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
swizzlr/Either | refs/heads/master | Either/EitherType.swift | mit | 1 | // Copyright (c) 2014 Rob Rix. All rights reserved.
/// A type representing an alternative of one of two types.
///
/// By convention, and where applicable, `Left` is used to indicate failure, while `Right` is to indicate success. (Mnemonic: “right is right,” i.e. “right” is a synonym for “correct.”)
///
/// Otherwise it is implied that `Left` and `Right` are effectively unordered.
public protocol EitherType {
typealias Left
typealias Right
/// Constructs a `Left` instance.
class func left(value: Left) -> Self
/// Constructs a `Right` instance.
class func right(value: Right) -> Self
/// Returns the result of applying `f` to `Left` values, or `g` to `Right` values.
func either<Result>(f: Left -> Result, _ g: Right -> Result) -> Result
}
// MARK: API
/// Equality (tho not `Equatable`) over `EitherType` where `Left` & `Right` : `Equatable`.
public func == <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool {
return lhs.either({ $0 == rhs.either(id, const(nil)) }, { $0 == rhs.either(const(nil), id) })
}
/// Inequality over `EitherType` where `Left` & `Right` : `Equatable`.
public func != <E: EitherType where E.Left: Equatable, E.Right: Equatable> (lhs: E, rhs: E) -> Bool {
return !(lhs == rhs)
}
// MARK: Imports
import Prelude
| 087cbbc4f25f864d9e036bbbf70a4f51 | 32.307692 | 185 | 0.665897 | false | false | false | false |
X140Yu/Lemon | refs/heads/master | Lemon/Library/GitHub API/User.swift | gpl-3.0 | 1 | import Foundation
import ObjectMapper
enum UserType {
case User
case Organization
}
extension UserType {
init(typeString: String) {
if typeString == "Organization" {
self = .Organization
// } else if typeString == "User" {
// self = .User
} else {
self = .User
}
}
}
class User: Mappable {
var avatarUrl : String?
var bio : String?
var blog : String?
var company : String?
var createdAt : String?
var email : String?
var eventsUrl : String?
var followers : Int = 0
var followersUrl : String?
var following : Int = 0
var followingUrl : String?
var gistsUrl : String?
var gravatarId : String?
var hireable : Bool?
var htmlUrl : String?
var id : Int?
var location : String?
var login : String?
var name : String?
var organizationsUrl : String?
var publicGists : Int = 0
var publicRepos : Int = 0
var receivedEventsUrl : String?
var reposUrl : String?
var siteAdmin : Bool?
var starredUrl : String?
var subscriptionsUrl : String?
var type : UserType = .User
var updatedAt : String?
var url : String?
public init(){}
public required init?(map: Map) {}
public func mapping(map: Map)
{
avatarUrl <- map["avatar_url"]
bio <- map["bio"]
blog <- map["blog"]
company <- map["company"]
createdAt <- map["created_at"]
email <- map["email"]
eventsUrl <- map["events_url"]
followers <- map["followers"]
followersUrl <- map["followers_url"]
following <- map["following"]
followingUrl <- map["following_url"]
gistsUrl <- map["gists_url"]
gravatarId <- map["gravatar_id"]
hireable <- map["hireable"]
htmlUrl <- map["html_url"]
id <- map["id"]
location <- map["location"]
login <- map["login"]
name <- map["name"]
organizationsUrl <- map["organizations_url"]
publicGists <- map["public_gists"]
publicRepos <- map["public_repos"]
receivedEventsUrl <- map["received_events_url"]
reposUrl <- map["repos_url"]
siteAdmin <- map["site_admin"]
starredUrl <- map["starred_url"]
subscriptionsUrl <- map["subscriptions_url"]
if let typeString = map["type"].currentValue as? String {
type = UserType(typeString: typeString)
}
// type <- map["type"]
updatedAt <- map["updated_at"]
url <- map["url"]
}
}
extension User: CustomStringConvertible {
var description: String {
return "User: `\(login ?? "")` `\(bio ?? "")` `\(blog ?? "")` `\(company ?? "")`"
}
}
| d249e87b47e23c146f21aa8fe4ee10aa | 24.171717 | 85 | 0.615169 | false | false | false | false |
takeo-asai/math-puzzle | refs/heads/master | problems/22.swift | mit | 1 | var memo: [Int: Int] = Dictionary()
func partition(n: Int) -> Int {
if n%2 != 0 {
return 0
} else if n == 0 {
return 1
}
var count = 0
for k in 1 ... n-1 {
let x = partition(k-1)
let y = partition(n-k-1)
count += x * y
memo[k-1] = x
memo[n-k-1] = y
}
return count
}
let n = 16
let p = partition(n)
print(p)
| d2ec9171f4fd011cc62d981adf2868b9 | 14 | 35 | 0.539394 | false | false | false | false |
TalkingBibles/Talking-Bible-iOS | refs/heads/master | TalkingBible/DashboardButtonView.swift | apache-2.0 | 1 | //
// Copyright 2015 Talking Bibles International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class DashboardButtonView: UIView {
@IBOutlet weak var caret: UIImageView!
@IBOutlet weak var button: UIButton!
let buttonObservableKeyPath = "titleLabel.alpha"
override func awakeFromNib() {
super.awakeFromNib()
caret.tintColor = button.titleLabel?.tintColor
if let image = caret.image {
caret.image = nil
caret.image = image
}
button.addObserver(self, forKeyPath: buttonObservableKeyPath, options: [.Initial, .New], context: nil)
}
override func removeFromSuperview() {
log.debug("Removing button from superview")
button.removeObserver(self, forKeyPath: buttonObservableKeyPath)
super.removeFromSuperview()
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == buttonObservableKeyPath {
if let buttonTitleLabelAlpha = button.titleLabel?.alpha {
caret.alpha = buttonTitleLabelAlpha
}
}
}
}
| af670690bac2821909653b64f5c5f860 | 30.396226 | 155 | 0.712139 | false | false | false | false |
andrlee/swift-data-structures | refs/heads/master | CircularBuffer/CircularBuffer.playground/Sources/CircularBuffer.swift | mit | 1 | import Foundation
/**
Dynamically resized circular buffer/queue
- important: This structure is not thread safe!
Both read and write have O(1) time complexity
*/
public struct CircularBuffer<Element> {
private let scaleFactor = 2
// MARK: - Vars
private var head: Int
private var tail: Int
private var numberOfElements: Int
private var elements: [Element?]
public var count: Int {
return numberOfElements
}
/**
Create circular buffer
- parameter capacity: Initial buffer capacity
*/
public init(capacity: Int) {
self.head = 0
self.tail = 0
self.numberOfElements = 0
self.elements = [Element?](repeating: nil, count: capacity)
}
// MARK: - Public
/**
Insert element into the circular buffer
- important: The buffer resizes automatically when reaches capacity limit
- parameter element: The element of the generic type
*/
public mutating func write(_ element: Element) {
// Needs resize
if numberOfElements == elements.count {
// Rotate array
elements = [Element?](elements[head ..< count] + elements[0 ..< head])
// Reset head and tail
head = 0
tail = numberOfElements
// Resize array
elements += [Element?](repeating: nil, count: elements.count*scaleFactor)
}
elements[tail] = element
tail = (tail + 1) % elements.count
numberOfElements += 1
}
/**
Retrieve element from circular buffer
- returns: The element of the generic type,
nil if buffer is empty
*/
public mutating func read() -> Element? {
if numberOfElements == 0 {
return nil
}
numberOfElements -= 1
let element = elements[head]
head = (head + 1) % elements.count
return element
}
}
| 941740b2f201f7da78453f5c28930ece | 24.222222 | 85 | 0.558982 | false | false | false | false |
Stealth2012/InfoBipSmsSwift | refs/heads/master | InfoBip/MainViewController.swift | mit | 1 | //
// ViewController.swift
// InfoBip
//
// Created by Artem Shuba on 12/11/15.
// Copyright © 2015 Artem Shuba. All rights reserved.
//
import UIKit
import CoreLocation
class MainViewController: UIViewController, CLLocationManagerDelegate, UITextFieldDelegate {
//MARK: fields
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var smsTextField: UITextField!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
private var locationManager: CLLocationManager!
private var gotLocation: Bool = false
private var address: String?
//MARK: properties
var login: String!
var password: String!
private var canSend: Bool {
get {
return (phoneTextField.text != nil && !phoneTextField.text!.isEmpty) &&
(smsTextField.text != nil && !smsTextField.text!.isEmpty)
}
}
//MARK: methods
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.hidden = false
phoneTextField.delegate = self
startActivity()
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self;
locationManager.startUpdatingLocation()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
//if it's a phoneTextField then switch to smsTextField
if textField == phoneTextField
{
smsTextField.becomeFirstResponder()
}
return true
}
@IBAction func fieldTextChanged(sender: UITextField) {
sendButton.enabled = canSend
}
@IBAction func sendButtonClick(sender: AnyObject) {
let smsService = InfoBipService()
smsService.login = login
smsService.password = password
startActivity()
var sms = smsTextField.text!
if address != nil
{
sms += " " + address!
}
smsService.sendSmsTo(self.phoneTextField.text!, text: sms).then({success, message in
if success
{
self.smsTextField.text = ""
UIAlertView.show("Success", message: message ?? "Message sent")
}
else
{
UIAlertView.show("Error", message: message ?? "Unable to send message, try again")
}
}).always({
self.stopActivity()
}).error({ error in
if let e: NSError = error as NSError
{
print(e.localizedDescription)
UIAlertView.show("Error", message: e.localizedDescription)
}
else
{
UIAlertView.show("Error", message: "Unable to send message, try again")
}
})
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.Denied
{
stopActivity()
UIAlertView.show(message: "You should allow app access to your location in Settings")
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
if gotLocation
{
return
}
gotLocation = true
locationManager.stopUpdatingLocation()
print("currentLocation = \(newLocation)")
let lat: Double = Double(newLocation.coordinate.latitude)
let lon: Double = Double(newLocation.coordinate.longitude)
//decode address using Google geocoding service
GoogleGeocoder.getAddressFromCoordinates(lat, lon: lon).then ( {address in
print("found address = \(address!)")
self.address = address
}).always ({
self.stopActivity()
}).error({ error in
if let e: NSError = error as NSError
{
print(e.localizedDescription)
UIAlertView.show("Error", message: e.localizedDescription)
}
else
{
UIAlertView.show("Error", message: "Unable to find your address")
}
})
}
private func startActivity()
{
self.phoneTextField.enabled = false
self.smsTextField.enabled = false
self.sendButton.enabled = false
activityIndicator.startAnimating()
}
private func stopActivity()
{
self.phoneTextField.enabled = true
self.smsTextField.enabled = true
self.sendButton.enabled = canSend
self.activityIndicator.stopAnimating()
}
}
| fc87bbed96ac6462de02166cd4d3e68a | 28.728324 | 137 | 0.581762 | false | false | false | false |
wftllc/hahastream | refs/heads/master | Haha Stream/Features/Account/AccountViewController.swift | mit | 1 | import UIKit
class AccountViewController: HahaViewController, UITextFieldDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var deviceStatusLabel: UILabel!
var interactor: AccountInteractor?
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.layer.cornerRadius = 40;
self.imageView.layer.masksToBounds = true;
self.imageView.layer.shadowRadius = 20;
self.imageView.layer.shadowColor = UIColor.black.cgColor;
self.imageView.layer.shadowOpacity = 0.5;
updateView(isActivated: nil)
interactor?.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
interactor?.viewDidAppear()
super.viewDidAppear(animated)
}
// func showLoading() {
// self.activityIndicator.startAnimating();
// }
//
// func hideLoading() {
// self.activityIndicator.stopAnimating();
// }
@IBAction func deactivateDidTap(_ sender: Any) {
interactor?.viewDidTapDeactivate()
}
func updateView(isActivated: Bool?) {
if let isActivated = isActivated {
self.deviceStatusLabel.text = isActivated ? "Activated" : "Not Activated"
self.activityIndicator.stopAnimating()
}
else {
self.deviceStatusLabel.text = ""
self.activityIndicator.startAnimating()
}
}
func showConfirmDeactivationDialog() {
self.showAlert(title: "Deactivate and Logout?", message: "This will deactivate your device and log you out.", okTitle: "Log Out") {
self.interactor?.viewDidConfirmDeactivation()
}
}
}
| 861e99e0ac1579f3776075e5340bcdbb | 26.45614 | 133 | 0.742492 | false | false | false | false |
JGiola/swift | refs/heads/main | validation-test/Sema/type_checker_crashers_fixed/rdar91110069.swift | apache-2.0 | 8 | // RUN: %target-typecheck-verify-swift
protocol Schema: RawRepresentable {
var rawValue: String { get }
}
enum MySchema: String, Schema {
case hello = "hello"
}
struct Parser<S: Schema> : Equatable {
}
protocol Entity {
}
protocol MyInitializable {
init() throws
}
typealias MyInitializableEntity = MyInitializable & Entity
extension Parser where S == MySchema {
func test(kind: Entity.Type) throws {
guard let entityType = kind as? MyInitializableEntity.Type else {
return
}
let _ = try entityType.init() // Ok
}
}
| 158689bedfd5bf9ebf0db7b9f43e1de0 | 16.83871 | 69 | 0.688969 | false | false | false | false |
CodaFi/swift | refs/heads/master | stdlib/public/core/CTypes.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
#if os(Windows) && arch(x86_64)
public typealias CUnsignedLong = UInt32
#else
public typealias CUnsignedLong = UInt
#endif
/// The C 'unsigned long long' type.
public typealias CUnsignedLongLong = UInt64
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && arch(x86_64)
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
public typealias CLongLong = Int64
/// The C '_Float16' type.
@available(iOS 14.0, watchOS 7.0, tvOS 14.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
public typealias CFloat16 = Float16
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
/// The C 'long double' type.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// On Darwin, long double is Float80 on x86, and Double otherwise.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#else
public typealias CLongDouble = Double
#endif
#elseif os(Windows)
// On Windows, long double is always Double.
public typealias CLongDouble = Double
#elseif os(Linux)
// On Linux/x86, long double is Float80.
// TODO: Fill in definitions for additional architectures as needed. IIRC
// armv7 should map to Double, but arm64 and ppc64le should map to Float128,
// which we don't yet have in Swift.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#endif
// TODO: Fill in definitions for other OSes.
#if arch(s390x)
// On s390x '-mlong-double-64' option with size of 64-bits makes the
// Long Double type equivalent to Double type.
public typealias CLongDouble = Double
#endif
#elseif os(Android)
// On Android, long double is Float128 for AAPCS64, which we don't have yet in
// Swift (SR-9072); and Double for ARMv7.
#if arch(arm)
public typealias CLongDouble = Double
#endif
#elseif os(OpenBSD)
public typealias CLongDouble = Float80
#endif
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = Unicode.Scalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = Unicode.Scalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@frozen
public struct OpaquePointer {
@usableFromInline
internal var _rawValue: Builtin.RawPointer
@usableFromInline @_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension OpaquePointer: Equatable {
@inlinable // unsafe-performance
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension OpaquePointer: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue)))
}
}
extension OpaquePointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
/// A wrapper around a C `va_list` pointer.
#if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: (__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32)
@inlinable // unsafe-performance
public // @testable
init(__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32) {
_value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off)
}
}
extension CVaListPointer: CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_value.__stack.debugDescription), " +
"\(_value.__gr_top.debugDescription), " +
"\(_value.__vr_top.debugDescription), " +
"\(_value.__gr_off), " +
"\(_value.__vr_off))"
}
}
#else
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: UnsafeMutableRawPointer
@inlinable // unsafe-performance
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
_value = from
}
}
extension CVaListPointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _value.debugDescription
}
}
#endif
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` should not overlap.
@inlinable
internal func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` may overlap.
@inlinable
internal func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
| 239af0583ff52f76fb9b86241e8fa0f4 | 28.780864 | 84 | 0.671987 | false | false | false | false |
StanDimitroff/cogs-ios-client-sdk | refs/heads/master | CogsSDK/Classes/Date+Utils.swift | apache-2.0 | 2 | //
// DialectValidator.swift
// CogsSDK
//
/**
* Copyright (C) 2017 Aviata Inc. All Rights Reserved.
* This code is licensed under the Apache License 2.0
*
* This license can be found in the LICENSE.txt at or near the root of the
* project or repository. It can also be found here:
* http://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of the Apache License 2.0 license with this
* code or source file. If not, please contact [email protected]
*/
import Foundation
extension Date {
var toISO8601: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.string(from: self)
}
}
| 0f680bf5352e2de5e84d455d367aa0f8 | 28.548387 | 78 | 0.691048 | false | false | false | false |
HTWDD/HTWDresden-iOS | refs/heads/master | HTWDD/Core/Extensions/UIPageViewControll.swift | gpl-2.0 | 1 | //
// UIPageViewControll.swift
// HTWDD
//
// Created by Mustafa Karademir on 31.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
extension UIPageViewController {
var pageControl: UIPageControl? {
return view.subviews.first(where: { $0 is UIPageControl }) as? UIPageControl
}
func goToNextPage(animated: Bool = true) {
guard let currentViewController = viewControllers?.first, let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
}
func goToPreviousPage(animated: Bool = true) {
guard let currentViewController = viewControllers?.first, let prevoisViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
setViewControllers([prevoisViewController], direction: .reverse, animated: animated, completion: nil)
}
}
| 689fe2a32657d17173431e7864988d97 | 39.576923 | 191 | 0.732701 | false | false | false | false |
chengxxxxwang/buttonPopView | refs/heads/master | SwiftCircleButton/SwiftCircleButton/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwiftCircleButton
//
// Created by chenxingwang on 2017/3/14.
// Copyright © 2017年 chenxingwang. All rights reserved.
//
import UIKit
let kScreenHeight = UIScreen.main.bounds.size.height
let kScreenWidth = UIScreen.main.bounds.size.width
class ViewController: UIViewController {
@IBOutlet weak var showViewAction: circleButton!
var popView = UIView()
var isShow:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
showViewAction.layer.cornerRadius = 4
showViewAction.layer.masksToBounds = true
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func showView(_ sender: Any) {
if self.isShow == false{
if self.popView.frame.size.width != 0 {
self.popView.removeFromSuperview()
}
setUpPopView()
showPopView()
self.isShow = !isShow
}else{
dismissPopView()
self.isShow = !isShow
}
}
fileprivate func setUpPopView(){
self.popView = UIView(frame:CGRect(x:60,y:300,width:kScreenWidth - 120,height:kScreenWidth/20))
self.popView.backgroundColor = UIColor.cyan
self.popView.layer.cornerRadius = 5
self.popView.layer.masksToBounds = true
self.view.addSubview(self.popView)
}
fileprivate func showPopView(){
UIView.animate(withDuration: 0.25, delay: 0.05, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
self.popView.frame = CGRect.init(origin: CGPoint.init(x: 60, y: 100), size: CGSize.init(width: kScreenWidth - 120, height: kScreenWidth/3*2))
}) { (Bool) in
}
}
fileprivate func dismissPopView(){
print("dismiss")
UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
self.popView.frame = CGRect.init(origin: CGPoint.init(x: 60, y: 300), size: CGSize.init(width: kScreenWidth - 120, height: kScreenWidth/20))
}) { (Bool) in
self.popView.removeFromSuperview()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 834fb774ea295a88b06c0c9b546abba3 | 30.74026 | 153 | 0.610884 | false | false | false | false |
jigneshsheth/Datastructures | refs/heads/master | DataStructure/DataStructure/Shopify/IDCodeVerification.swift | mit | 1 | //
// IDCodeVarification.swift
// DataStructure
//
// Created by Jigs Sheth on 11/1/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
/**
* Say, an organization issues ID cards to its employees with unique ID codes.
* The ID code for an employee named Jigarius Caesar looks as follows: CAJI202002196.
Here’s how the ID code is derived:
CA: First 2 characters of the employee’s last name.
JI: First 2 characters of the employee’s first name.
2020: Full year of joining.
02: 2 digit representation of the month of joining.
19: Indicates that this is the 19th employee who joined in Feb 2020.
This will have at least 2 digits, starting with 01, 02, and so on.
6: The last digit is a verification digit which is computed as follows:
Take the numeric part of the ID code (without the verification digit).
Sum all digits in odd positions. Say this is O.
Sum all digits in even positions. Say this is E.
Difference between O & E. Say this is V.
If V is negative, ignore the sign, e.g., -6 is treated as 6. Say this is V.
If V is greater than 9, divide it by 10 and take the reminder. Say this is V.
V is the verification code.
For the above ID card, here’s how you‘ll test the verification digit.
CAJI202002196 # ID code
202002196 # Numeric part
20200219 # Ignoring verification digit
2 + 2 + 0 + 1 = 5 # Sum of odd position digits, i.e. O
0 + 0 + 2 + 9 = 11 # Sum of even position digits, i.e. E
5 - 11 = -6 # V = O - E
6 # Verification digit, ignoring sign
An ID code is considered valid if:
The first 4 characters of the card are correct, i.e. CAJI.
The verification digit is correct, i.e. 6.
Problem
Write a command-line program in your preferred coding language that:
Allows the user to enter their First name, Last name and ID code.
Prints PASS if the ID code seems valid.
Prints INVESTIGATE otherwise.
Write relevant tests.
It is not necessary to use a testing library.
You can use your custom implementation of tests.
*/
import Foundation
//
class IDCodeVerification{
/// Check ID is valid or not
/// - Parameters:
/// - firstName: first name
/// - lastName: last name
/// - idCode: ID Code
/// - Returns: PASS if valid otherwise INVESTIGATE
static func checkValidID(firstName:String, lastName:String, idCode:String) -> String{
let result = "INVESTIGATION"
guard idCode.count == 13 else {
return result
}
let first = firstName.uppercased()
let last = lastName.uppercased()
let idCodeValue = idCode.uppercased()
let firstNameArray = first.map{String($0)}
if idCodeValue.prefix(2).caseInsensitiveCompare(last.prefix(2)) != .orderedSame{
return result
}else {
var verificationDigit:Int = 0
var oddSum:Int = 0
var evenSum:Int = 0
for (index,char) in idCodeValue.enumerated(){
print("index = \(index) char: \(char)")
if index == 0 || index == 1 {
continue
}else if (index == 2 && String(char) != firstNameArray[0]) || (index == 3 && String(char) != firstNameArray[1]){
return result
}else {
if index == 12,let num = Int(String(char)){
verificationDigit = num
}else if index % 2 == 0,let num = Int(String(char)) {
evenSum += num
}else if let oddNum = Int(String(char)) {
oddSum += oddNum
}
}
}
if (abs(oddSum - evenSum) % 10) != verificationDigit {
return result
}else{
return "PASS"
}
}
}
/// <#Description#>
/// - Parameters:
/// - firstName: <#firstName description#>
/// - lastName: <#lastName description#>
/// - idCode: <#idCode description#>
/// - Returns: <#description#>
static func checkValidIDAlt(firstName:String, lastName:String, idCode:String) -> String{
let result = "INVESTIGATION"
guard idCode.count == 13 else {
return result
}
let firstNameArray = firstName.uppercased().prefix(2).map{String($0)}
let lastNameArray = lastName.uppercased().prefix(2).map{String($0)}
let idCodeArray = idCode.uppercased().map{String($0)}
var verificationDigit = 0
var evenSum = 0
var oddSum = 0
for (i,char) in idCodeArray.enumerated() {
if (i == 0 || i == 1), lastNameArray[i] != idCodeArray[i]{
return result
}else if (i == 2 || i == 3), firstNameArray[i-2] != idCodeArray[i]{
return result
}else {
if i == 12,let num = Int(String(char)){
verificationDigit = num
}else if i % 2 == 0,let num = Int(String(char)) {
evenSum += num
}else if let oddNum = Int(String(char)) {
oddSum += oddNum
}
}
}
if (abs(oddSum - evenSum) % 10) != verificationDigit {
return result
}else{
return "PASS"
}
}
}
| 2abb3353cc4fe1706773fc35573f4d70 | 29.350649 | 116 | 0.657039 | false | false | false | false |
atljeremy/JFCardSelectionViewController | refs/heads/master | JFCardSelectionViewController/JFCardSelectionViewController+JFFocusedCardViewDelegate.swift | mit | 1 | /*
* JFCardSelectionViewController
*
* Created by Jeremy Fox on 3/1/16.
* Copyright (c) 2016 Jeremy Fox. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import UIKit
extension JFCardSelectionViewController: JFFocusedCardViewDelegate {
func focusedCardViewDidSelectActionItemOne(_ focusedCardView: JFFocusedCardView) {
guard let actionOne = focusedCardView.card.actionOne else { return }
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
delegate?.cardSelectionViewController(self, didSelectCardAction: actionOne, forCardAtIndexPath: indexPath)
} else {
let indexPath = IndexPath(item: 0, section: 0)
delegate?.cardSelectionViewController(self, didSelectCardAction: actionOne, forCardAtIndexPath: indexPath)
}
}
func focusedCardViewDidSelectActionItemTwo(_ focusedCardView: JFFocusedCardView) {
guard let actionTwo = focusedCardView.card.actionTwo else { return }
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
delegate?.cardSelectionViewController(self, didSelectCardAction: actionTwo, forCardAtIndexPath: indexPath)
} else {
let indexPath = IndexPath(item: 0, section: 0)
delegate?.cardSelectionViewController(self, didSelectCardAction: actionTwo, forCardAtIndexPath: indexPath)
}
}
func focusedCardViewDidSelectDetailAction(_ focusedCardView: JFFocusedCardView) {
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
delegate?.cardSelectionViewController(self, didSelectDetailActionForCardAtIndexPath: indexPath)
} else {
let indexPath = IndexPath(item: 0, section: 0)
delegate?.cardSelectionViewController(self, didSelectDetailActionForCardAtIndexPath: indexPath)
}
}
}
| 2e1e6d0e905de4b1ab45f690493c7346 | 49.12069 | 118 | 0.743722 | false | false | false | false |
Zewo/TCPIP | refs/heads/master | Tests/TCPClientSocketTests.swift | mit | 1 | // TCPClientSocketTests.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 XCTest
import TCPIP
import Dispatch
class TCPClientSocketTests: XCTestCase {
func testConnectionRefused() {
var called = false
do {
let ip = try IP(address: "127.0.0.1", port: 5555)
let _ = try TCPClientSocket(ip: ip)
XCTAssert(false)
} catch {
called = true
}
XCTAssert(called)
}
func testInitWithFileDescriptor() {
var called = false
do {
let _ = try TCPClientSocket(fileDescriptor: 0)
called = true
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testSendClosedSocket() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.close()
try clientSocket.send(nil, length: 0)
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testFlushClosedSocket() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.close()
try clientSocket.flush()
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testReceiveClosedSocket() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.close()
try clientSocket.receive()
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testReceiveUntilClosedSocket() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.close()
try clientSocket.receive(untilDelimiter: "")
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testDetachClosedSocket() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
clientSocket.close()
try clientSocket.detach()
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testSendBufferPointerInvalidLength() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
try clientSocket.send(nil, length: -1)
XCTAssert(false)
} catch {
called = true
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
try serverSocket.accept()
NSThread.sleepForTimeInterval(0.1)
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
func testSendReceive() {
var called = false
func client(port: Int) {
do {
let ip = try IP(address: "127.0.0.1", port: port)
let clientSocket = try TCPClientSocket(ip: ip)
try clientSocket.send([123])
try clientSocket.flush()
} catch {
XCTAssert(false)
}
}
do {
let port = 5555
let ip = try IP(port: port)
let serverSocket = try TCPServerSocket(ip: ip)
async {
client(port)
}
let clientSocket = try serverSocket.accept()
let data = try clientSocket.receive(bufferSize: 1)
called = true
XCTAssert(data == [123])
clientSocket.close()
} catch {
XCTAssert(false)
}
XCTAssert(called)
}
}
| feb9ac31a061620b54fc72aee4424146 | 26.583333 | 81 | 0.504794 | false | false | false | false |
IntrepidPursuits/swift-wisdom | refs/heads/master | SwiftWisdom/Core/StandardLibrary/Array/Array+Utilities.swift | mit | 1 | //
// Array+Utilities.swift
// SwiftWisdom
//
import Foundation
extension Array {
/// Creates an array containing the elements at the indices passed in. If an index is out of the array's bounds it will be ignored.
///
/// - parameter indices: An array of integers representing the indices to grab
///
/// - returns: An array of elements at the specified indices
public func ip_subArray(fromIndices indices: [Int]) -> [Element] {
var subArray: [Element] = []
for (idx, element) in enumerated() {
if indices.contains(idx) {
subArray.append(element)
}
}
return subArray
}
@available (*, unavailable, message: "use allSatisfy(_:) instead")
public func ip_passes(test: (Element) -> Bool) -> Bool {
for ob in self {
if test(ob) {
return true
}
}
return false
}
}
extension Array {
/// Separates this array's elements into chunks with a given length. Elements in these chunks and the chunks themselves
/// are ordered the same way they are ordered in this array.
///
/// If this array is empty, we always return an empty array.
///
/// If `length` is not a positive number or if it's greater than or equal to this array's length, we return a new array
/// with no chunks at all, plus the "remainder" which is this array itself iff `includeRemainder` is `true`.
///
/// - parameter length: Number of elements in each chunk.
/// - parameter includeRemainder: If set to `true`, include the remainder in returned array even if its length is less than
/// `length`. If set to `false`, discard the remainder. Defaults to `true`.
///
/// - returns: New array of chunks of elements in this array.
public func ip_chunks(of length: Int, includeRemainder: Bool = true) -> [[Element]] {
guard !isEmpty else { return [] }
guard length > 0 else { return includeRemainder ? [self] : [] }
var chunks = [[Element]]()
var nextChunkLeftIndex = 0
let nextChunkRightIndex = { nextChunkLeftIndex + length - 1 }
while nextChunkRightIndex() < count {
let nextChunk = Array(self[nextChunkLeftIndex...nextChunkRightIndex()])
chunks.append(nextChunk)
nextChunkLeftIndex += length
}
if includeRemainder && nextChunkLeftIndex < count {
let remainder = Array(self[nextChunkLeftIndex..<count])
chunks.append(remainder)
}
return chunks
}
}
extension Array where Element: Equatable {
/// Removes a single element from the array.
///
/// - parameter object: Element to remove
///
/// - returns: Boolean value indicating the success/failure of removing the element.
@discardableResult public mutating func ip_remove(object: Element) -> Bool {
for (idx, objectToCompare) in enumerated() where object == objectToCompare {
remove(at: idx)
return true
}
return false
}
/// Removes multiple elements from an array.
///
/// - parameter elements: Array of elements to remove
public mutating func ip_remove(elements: [Element]) {
self = self.filter { element in
return !elements.contains(element)
}
}
/// Returns NSNotFound for any element in elements that does not exist.
///
/// - parameter elements: Array of Equatable elements
///
/// - returns: Array of indexes or NSNotFound if element does not exist in self; count is equal to the count of `elements`
public func ip_indices(ofElements elements: [Element]) -> [Int] {
return elements.map { element in
return firstIndex(of: element) ?? NSNotFound
}
}
}
extension Array where Element: Hashable {
/// Converts an Array into a Set of the same type.
///
/// - returns: Set of the array's elements
public func ip_toSet() -> Set<Element> {
return Set(self)
}
}
extension Array {
/// Provides a way to safely index into an array. If the index is beyond the array's
/// bounds this method will return `nil`.
///
/// - parameter index: Index of the element to return
///
/// - returns: An `Element` if the index is valid, or `nil` if the index is outside the bounds of the array.
public subscript(ip_safely index: Int) -> Element? {
guard 0 <= index && index < count else { return nil }
return self[index]
}
}
extension Array {
/// Removes the first instance of an element within an array.
///
/// - parameter matcher: The element that should be removed
public mutating func ip_removeFirst(matcher: (Iterator.Element) -> Bool) {
guard let idx = firstIndex(where: matcher) else { return }
remove(at: idx)
}
}
extension Array {
//TODO: Add documentation
public var ip_iterator: AnyIterator<Element> {
var idx = 0
let count = self.count
return AnyIterator {
guard idx < count else { return nil }
defer { idx += 1 }
return self[idx]
}
}
@available (*, unavailable, message: "ip_generator has been renamed to ip_iterator")
public var ip_generator: AnyIterator<Element> {
var idx = 0
let count = self.count
return AnyIterator {
guard idx < count else { return nil }
let this = idx
idx += 1
return self[this]
}
}
}
extension Collection {
/// This grabs the element(s) in the middle of the array without doing any sorting.
/// If there's an odd number the return array is just one element.
/// If there are an even number it will return the two middle elements.
/// The two middle elements will be flipped if the array has an even number.
public var ip_middleElements: [Element] {
guard count > 0 else { return [] }
let needsAverageOfTwo = Int(count).ip_isEven
let middle = index(startIndex, offsetBy: count / 2)
if needsAverageOfTwo {
let leftOfMiddle = index(middle, offsetBy: -1)
return [self[middle], self[leftOfMiddle]]
} else {
return [self[middle]]
}
}
}
| c58e6541477a35a8638ba28fbd5f6f7e | 33.922652 | 135 | 0.612403 | false | false | false | false |
ripventura/VCHTTPConnect | refs/heads/master | Example/Pods/EFQRCode/Source/EFQRCodeGenerator.swift | mit | 2 | //
// EFQRCodeGenerator.swift
// EFQRCode
//
// Created by EyreFree on 17/1/24.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(watchOS)
import CoreGraphics
#else
import CoreImage
#endif
// EFQRCode+Create
public class EFQRCodeGenerator {
// MARK: - Parameters
// Content of QR Code
private var content: String? {
didSet {
imageQRCode = nil
imageCodes = nil
}
}
public func setContent(content: String) {
self.content = content
}
// Mode of QR Code
private var mode: EFQRCodeMode = .none {
didSet {
imageQRCode = nil
}
}
public func setMode(mode: EFQRCodeMode) {
self.mode = mode
}
// Error-tolerant rate
// L 7%
// M 15%
// Q 25%
// H 30%(Default)
private var inputCorrectionLevel: EFInputCorrectionLevel = .h {
didSet {
imageQRCode = nil
imageCodes = nil
}
}
public func setInputCorrectionLevel(inputCorrectionLevel: EFInputCorrectionLevel) {
self.inputCorrectionLevel = inputCorrectionLevel
}
// Size of QR Code
private var size: EFIntSize = EFIntSize(width: 256, height: 256) {
didSet {
imageQRCode = nil
}
}
public func setSize(size: EFIntSize) {
self.size = size
}
// Magnification of QRCode compare with the minimum size,
// (Parameter size will be ignored if magnification is not nil).
private var magnification: EFIntSize? {
didSet {
imageQRCode = nil
}
}
public func setMagnification(magnification: EFIntSize?) {
self.magnification = magnification
}
// backgroundColor
private var backgroundColor: CGColor = CGColor.EFWhite() {
didSet {
imageQRCode = nil
}
}
// foregroundColor
private var foregroundColor: CGColor = CGColor.EFBlack() {
didSet {
imageQRCode = nil
}
}
#if !os(watchOS)
public func setColors(backgroundColor: CIColor, foregroundColor: CIColor) {
self.backgroundColor = backgroundColor.toCGColor() ?? .EFWhite()
self.foregroundColor = foregroundColor.toCGColor() ?? .EFBlack()
}
#endif
public func setColors(backgroundColor: CGColor, foregroundColor: CGColor) {
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
}
// Icon in the middle of QR Code
private var icon: CGImage? = nil {
didSet {
imageQRCode = nil
}
}
// Size of icon
private var iconSize: EFIntSize? = nil {
didSet {
imageQRCode = nil
}
}
public func setIcon(icon: CGImage?, size: EFIntSize?) {
self.icon = icon
self.iconSize = size
}
// Watermark
private var watermark: CGImage? = nil {
didSet {
imageQRCode = nil
}
}
// Mode of watermark
private var watermarkMode: EFWatermarkMode = .scaleAspectFill {
didSet {
imageQRCode = nil
}
}
public func setWatermark(watermark: CGImage?, mode: EFWatermarkMode? = nil) {
self.watermark = watermark
if let mode = mode {
self.watermarkMode = mode
}
}
// Offset of foreground point
private var foregroundPointOffset: CGFloat = 0 {
didSet {
imageQRCode = nil
}
}
public func setForegroundPointOffset(foregroundPointOffset: CGFloat) {
self.foregroundPointOffset = foregroundPointOffset
}
// Alpha 0 area of watermark will transparent
private var allowTransparent: Bool = true {
didSet {
imageQRCode = nil
}
}
public func setAllowTransparent(allowTransparent: Bool) {
self.allowTransparent = allowTransparent
}
// Shape of foreground point
private var pointShape: EFPointShape = .square {
didSet {
imageQRCode = nil
}
}
public func setPointShape(pointShape: EFPointShape) {
self.pointShape = pointShape
}
// Threshold for binarization (Only for mode binarization).
private var binarizationThreshold: CGFloat = 0.5 {
didSet {
imageQRCode = nil
}
}
public func setBinarizationThreshold(binarizationThreshold: CGFloat) {
self.binarizationThreshold = binarizationThreshold
}
// Cache
private var imageCodes: [[Bool]]?
private var imageQRCode: CGImage?
private var minSuitableSize: EFIntSize!
// MARK: - Init
public init(
content: String,
size: EFIntSize = EFIntSize(width: 256, height: 256)
) {
self.content = content
self.size = size
}
// Final QRCode image
public func generate() -> CGImage? {
if nil == imageQRCode {
imageQRCode = createImageQRCode()
}
return imageQRCode
}
// MARK: - Draw
private func createImageQRCode() -> CGImage? {
var finalSize = self.size
let finalBackgroundColor = getBackgroundColor()
let finalForegroundColor = getForegroundColor()
let finalIcon = self.icon
let finalIconSize = self.iconSize
let finalWatermark = self.watermark
let finalWatermarkMode = self.watermarkMode
// Get QRCodes from image
guard let codes = generateCodes() else {
return nil
}
// If magnification is not nil, reset finalSize
if let tryMagnification = magnification {
finalSize = EFIntSize(
width: tryMagnification.width * codes.count, height: tryMagnification.height * codes.count
)
}
var result: CGImage?
if let context = createContext(size: finalSize) {
// Cache size
minSuitableSize = EFIntSize(
width: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.widthCGFloat()) ?? finalSize.width,
height: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.heightCGFloat()) ?? finalSize.height
)
// Watermark
if let tryWatermark = finalWatermark {
// Draw background with watermark
drawWatermarkImage(
context: context,
image: tryWatermark,
colorBack: finalBackgroundColor,
mode: finalWatermarkMode,
size: finalSize.toCGSize()
)
// Draw QR Code
if let tryFrontImage = createQRCodeImageTransparent(
codes: codes,
colorBack: finalBackgroundColor,
colorFront: finalForegroundColor,
size: minSuitableSize
) {
context.draw(tryFrontImage, in: CGRect(origin: .zero, size: finalSize.toCGSize()))
}
} else {
// Draw background without watermark
let colorCGBack = finalBackgroundColor
context.setFillColor(colorCGBack)
context.fill(CGRect(origin: .zero, size: finalSize.toCGSize()))
// Draw QR Code
if let tryImage = createQRCodeImage(
codes: codes,
colorBack: finalBackgroundColor,
colorFront: finalForegroundColor,
size: minSuitableSize
) {
context.draw(tryImage, in: CGRect(origin: .zero, size: finalSize.toCGSize()))
}
}
// Add icon
if let tryIcon = finalIcon {
var finalIconSizeWidth = CGFloat(finalSize.width) * 0.2
var finalIconSizeHeight = CGFloat(finalSize.width) * 0.2
if let tryFinalIconSize = finalIconSize {
finalIconSizeWidth = CGFloat(tryFinalIconSize.width)
finalIconSizeHeight = CGFloat(tryFinalIconSize.height)
}
let maxLength = [CGFloat(0.2), 0.3, 0.4, 0.5][inputCorrectionLevel.rawValue] * CGFloat(finalSize.width)
if finalIconSizeWidth > maxLength {
finalIconSizeWidth = maxLength
print("Warning: icon width too big, it has been changed.")
}
if finalIconSizeHeight > maxLength {
finalIconSizeHeight = maxLength
print("Warning: icon height too big, it has been changed.")
}
let iconSize = EFIntSize(width: Int(finalIconSizeWidth), height: Int(finalIconSizeHeight))
drawIcon(
context: context,
icon: tryIcon,
size: iconSize
)
}
result = context.makeImage()
}
// Mode apply
switch mode {
case .grayscale:
if let tryModeImage = result?.grayscale() {
result = tryModeImage
}
case .binarization:
if let tryModeImage = result?.binarization(
value: binarizationThreshold,
foregroundColor: foregroundColor,
backgroundColor: backgroundColor
) {
result = tryModeImage
}
default:
break
}
return result
}
private func getForegroundColor() -> CGColor {
if mode == .binarization {
return CGColor.EFBlack()
}
return foregroundColor
}
private func getBackgroundColor() -> CGColor {
if mode == .binarization {
return CGColor.EFWhite()
}
return backgroundColor
}
// Create Colorful QR Image
#if !os(watchOS)
private func createQRCodeImage(
codes: [[Bool]],
colorBack: CIColor,
colorFront: CIColor,
size: EFIntSize) -> CGImage? {
guard let colorCGFront = colorFront.toCGColor() else {
return nil
}
return createQRCodeImage(codes: codes, colorFront: colorCGFront, size: size)
}
#endif
private func createQRCodeImage(
codes: [[Bool]],
colorBack colorCGBack: CGColor? = nil,
colorFront colorCGFront: CGColor,
size: EFIntSize) -> CGImage? {
let scaleX = CGFloat(size.width) / CGFloat(codes.count)
let scaleY = CGFloat(size.height) / CGFloat(codes.count)
if scaleX < 1.0 || scaleY < 1.0 {
print("Warning: Size too small.")
}
let codeSize = codes.count
var result: CGImage?
if let context = createContext(size: size) {
// Point
context.setFillColor(colorCGFront)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where true == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset,
y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset,
width: scaleX - 2 * foregroundPointOffset,
height: scaleY - 2 * foregroundPointOffset
)
)
}
}
result = context.makeImage()
}
return result
}
// Create Colorful QR Image
#if !os(watchOS)
private func createQRCodeImageTransparent(
codes: [[Bool]],
colorBack: CIColor,
colorFront: CIColor,
size: EFIntSize) -> CGImage? {
guard let colorCGBack = colorBack.toCGColor(), let colorCGFront = colorFront.toCGColor() else {
return nil
}
return createQRCodeImageTransparent(codes: codes, colorBack: colorCGBack, colorFront: colorCGFront, size: size)
}
#endif
private func createQRCodeImageTransparent(
codes: [[Bool]],
colorBack colorCGBack: CGColor,
colorFront colorCGFront: CGColor,
size: EFIntSize) -> CGImage? {
let scaleX = CGFloat(size.width) / CGFloat(codes.count)
let scaleY = CGFloat(size.height) / CGFloat(codes.count)
if scaleX < 1.0 || scaleY < 1.0 {
print("Warning: Size too small.")
}
let codeSize = codes.count
let pointMinOffsetX = scaleX / 3
let pointMinOffsetY = scaleY / 3
let pointWidthOriX = scaleX
let pointWidthOriY = scaleY
let pointWidthMinX = scaleX - 2 * pointMinOffsetX
let pointWidthMinY = scaleY - 2 * pointMinOffsetY
// Get AlignmentPatternLocations first
var points = [EFIntPoint]()
if let locations = getAlignmentPatternLocations(version: getVersion(size: codeSize - 2)) {
for indexX in locations {
for indexY in locations {
let finalX = indexX + 1
let finalY = indexY + 1
if !((finalX == 7 && finalY == 7)
|| (finalX == 7 && finalY == (codeSize - 8))
|| (finalX == (codeSize - 8) && finalY == 7)) {
points.append(EFIntPoint(x: finalX, y: finalY))
}
}
}
}
var finalImage: CGImage?
if let context = createContext(size: size) {
// Back point
context.setFillColor(colorCGBack)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where false == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX,
y: CGFloat(indexYCTM) * scaleY,
width: pointWidthOriX,
height: pointWidthOriY
)
)
} else {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX,
y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY,
width: pointWidthMinX,
height: pointWidthMinY
)
)
}
}
}
// Front point
context.setFillColor(colorCGFront)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where true == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset,
y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset,
width: pointWidthOriX - 2 * foregroundPointOffset,
height: pointWidthOriY - 2 * foregroundPointOffset
)
)
} else {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX,
y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY,
width: pointWidthMinX,
height: pointWidthMinY
)
)
}
}
}
finalImage = context.makeImage()
}
return finalImage
}
// Pre
#if !os(watchOS)
private func drawWatermarkImage(
context: CGContext,
image: CGImage,
colorBack: CIColor,
mode: EFWatermarkMode,
size: CGSize) {
drawWatermarkImage(context: context, image: image, colorBack: colorBack.toCGColor(), mode: mode, size: size)
}
#endif
private func drawWatermarkImage(
context: CGContext,
image: CGImage,
colorBack: CGColor?,
mode: EFWatermarkMode,
size: CGSize) {
// BGColor
if let tryColor = colorBack {
context.setFillColor(tryColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
if allowTransparent {
guard let codes = generateCodes() else {
return
}
if let tryCGImage = createQRCodeImage(
codes: codes,
colorBack: getBackgroundColor(),
colorFront: getForegroundColor(),
size: minSuitableSize
) {
context.draw(tryCGImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
// Image
var finalSize = size
var finalOrigin = CGPoint.zero
let imageSize = CGSize(width: image.width, height: image.height)
switch mode {
case .bottom:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: 0)
case .bottomLeft:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: 0)
case .bottomRight:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: 0)
case .center:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: (size.height - imageSize.height) / 2.0)
case .left:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: (size.height - imageSize.height) / 2.0)
case .right:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: (size.height - imageSize.height) / 2.0)
case .top:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: size.height - imageSize.height)
case .topLeft:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: size.height - imageSize.height)
case .topRight:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: size.height - imageSize.height)
case .scaleAspectFill:
let scale = max(size.width / imageSize.width, size.height / imageSize.height)
finalSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0)
case .scaleAspectFit:
let scale = max(imageSize.width / size.width, imageSize.height / size.height)
finalSize = CGSize(width: imageSize.width / scale, height: imageSize.height / scale)
finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0)
default:
break
}
context.draw(image, in: CGRect(origin: finalOrigin, size: finalSize))
}
private func drawIcon(context: CGContext, icon: CGImage, size: EFIntSize) {
context.draw(
icon,
in: CGRect(
origin: CGPoint(
x: CGFloat(context.width - size.width) / 2.0,
y: CGFloat(context.height - size.height) / 2.0
),
size: size.toCGSize()
)
)
}
private func drawPoint(context: CGContext, rect: CGRect) {
if pointShape == .circle {
context.fillEllipse(in: rect)
} else {
context.fill(rect)
}
}
private func createContext(size: EFIntSize) -> CGContext? {
return CGContext(
data: nil, width: size.width, height: size.height,
bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
)
}
#if !os(watchOS)
// MARK: - Data
private func getPixels() -> [[EFUIntPixel]]? {
guard let finalContent = content else {
return nil
}
let finalInputCorrectionLevel = inputCorrectionLevel
guard let tryQRImagePixels = CIImage.generateQRCode(
string: finalContent, inputCorrectionLevel: finalInputCorrectionLevel
)?.toCGImage()?.pixels() else {
print("Warning: Content too large.")
return nil
}
return tryQRImagePixels
}
#endif
// Get QRCodes from pixels
private func getCodes(pixels: [[EFUIntPixel]]) -> [[Bool]] {
var codes = [[Bool]]()
for indexY in 0 ..< pixels.count {
codes.append([Bool]())
for indexX in 0 ..< pixels[0].count {
let pixel = pixels[indexY][indexX]
codes[indexY].append(
pixel.red == 0 && pixel.green == 0 && pixel.blue == 0
)
}
}
return codes
}
// Get QRCodes from pixels
private func generateCodes() -> [[Bool]]? {
if let tryImageCodes = imageCodes {
return tryImageCodes
}
func fetchPixels() -> [[Bool]]? {
#if os(iOS) || os(macOS) || os(tvOS)
// Get pixels from image
guard let tryQRImagePixels = getPixels() else {
return nil
}
// Get QRCodes from image
return getCodes(pixels: tryQRImagePixels)
#else
let level = inputCorrectionLevel.qrErrorCorrectLevel
if let finalContent = content,
let typeNumber = try? QRCodeType.typeNumber(of: finalContent, errorCorrectLevel: level),
let model = QRCodeModel(text: finalContent, typeNumber: typeNumber, errorCorrectLevel: level) {
return (0 ..< model.moduleCount).map {
r in
(0 ..< model.moduleCount).map {
c in
model.isDark(r, c)
}
}
}
return nil
#endif
}
imageCodes = fetchPixels()
return imageCodes
}
// Special Points of QRCode
private func isStatic(x: Int, y: Int, size: Int, APLPoints: [EFIntPoint]) -> Bool {
// Empty border
if x == 0 || y == 0 || x == (size - 1) || y == (size - 1) {
return true
}
// Finder Patterns
if (x <= 8 && y <= 8) || (x <= 8 && y >= (size - 9)) || (x >= (size - 9) && y <= 8) {
return true
}
// Timing Patterns
if x == 7 || y == 7 {
return true
}
// Alignment Patterns
for point in APLPoints {
if x >= (point.x - 2) && x <= (point.x + 2) && y >= (point.y - 2) && y <= (point.y + 2) {
return true
}
}
return false
}
// Alignment Pattern Locations
// http://stackoverflow.com/questions/13238704/calculating-the-position-of-qr-code-alignment-patterns
private func getAlignmentPatternLocations(version: Int) -> [Int]? {
if version == 1 {
return nil
}
let divs = 2 + version / 7
let size = getSize(version: version)
let total_dist = size - 7 - 6
let divisor = 2 * (divs - 1)
// Step must be even, for alignment patterns to agree with timing patterns
let step = (total_dist + divisor / 2 + 1) / divisor * 2 // Get the rounding right
var coords = [6]
// divs-2 down to 0, inclusive
for i in 0...(divs - 2) {
coords.append(size - 7 - (divs - 2 - i) * step)
}
return coords
}
// QRCode version
private func getVersion(size: Int) -> Int {
return (size - 21) / 4 + 1
}
// QRCode size
private func getSize(version: Int) -> Int {
return 17 + 4 * version
}
// Recommand magnification
public func minMagnificationGreaterThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let finalWatermark = watermark
let baseMagnification = max(1, Int(size / CGFloat(codes.count)))
for offset in [0, 1, 2, 3] {
let tempMagnification = baseMagnification + offset
if CGFloat(Int(tempMagnification) * codes.count) >= size {
if finalWatermark == nil {
return tempMagnification
} else if tempMagnification % 3 == 0 {
return tempMagnification
}
}
}
return nil
}
public func maxMagnificationLessThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let finalWatermark = watermark
let baseMagnification = max(1, Int(size / CGFloat(codes.count)))
for offset in [0, -1, -2, -3] {
let tempMagnification = baseMagnification + offset
if tempMagnification <= 0 {
return finalWatermark == nil ? 1 : 3
}
if CGFloat(tempMagnification * codes.count) <= size {
if finalWatermark == nil {
return tempMagnification
} else if tempMagnification % 3 == 0 {
return tempMagnification
}
}
}
return nil
}
// Calculate suitable size
private func minSuitableSizeGreaterThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let baseSuitableSize = Int(size)
for offset in 0...codes.count {
let tempSuitableSize = baseSuitableSize + offset
if tempSuitableSize % codes.count == 0 {
return tempSuitableSize
}
}
return nil
}
}
| 455246ab8288ce96b10b44e9b3d2fecf | 33.622249 | 119 | 0.532361 | false | false | false | false |
1457792186/JWSwift | refs/heads/develop | NBUStatProject/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift | apache-2.0 | 11 | //
// BubbleDataEntry.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class BubbleChartDataEntry: ChartDataEntry
{
/// The size of the bubble.
@objc open var size = CGFloat(0.0)
public required init()
{
super.init()
}
/// - parameter x: The index on the x-axis.
/// - parameter y: The value on the y-axis.
/// - parameter size: The size of the bubble.
@objc public init(x: Double, y: Double, size: CGFloat)
{
super.init(x: x, y: y)
self.size = size
}
/// - parameter x: The index on the x-axis.
/// - parameter y: The value on the y-axis.
/// - parameter size: The size of the bubble.
/// - parameter data: Spot for additional data this Entry represents.
@objc public init(x: Double, y: Double, size: CGFloat, data: AnyObject?)
{
super.init(x: x, y: y, data: data)
self.size = size
}
/// - parameter x: The index on the x-axis.
/// - parameter y: The value on the y-axis.
/// - parameter size: The size of the bubble.
/// - parameter icon: icon image
@objc public init(x: Double, y: Double, size: CGFloat, icon: NSUIImage?)
{
super.init(x: x, y: y, icon: icon)
self.size = size
}
/// - parameter x: The index on the x-axis.
/// - parameter y: The value on the y-axis.
/// - parameter size: The size of the bubble.
/// - parameter icon: icon image
/// - parameter data: Spot for additional data this Entry represents.
@objc public init(x: Double, y: Double, size: CGFloat, icon: NSUIImage?, data: AnyObject?)
{
super.init(x: x, y: y, icon: icon, data: data)
self.size = size
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BubbleChartDataEntry
copy.size = size
return copy
}
}
| 4e133503fa8858014850f44e5033b9df | 26.909091 | 94 | 0.584458 | false | false | false | false |
podverse/podverse-ios | refs/heads/master | Podverse/String+MediaPlayerTimeToSeconds.swift | agpl-3.0 | 1 | //
// String+MediaPlayerTimeToSeconds.swift
// Podverse
//
// Created by Mitchell Downey on 7/22/18.
// Copyright © 2018 Podverse LLC. All rights reserved.
//
import Foundation
extension String {
func mediaPlayerTimeToSeconds() -> Int64 {
let timeComponents = self.components(separatedBy: ":")
var int = Int64(0)
if timeComponents.count == 2, let minutes = Int64(timeComponents[0]), let seconds = Int64(timeComponents[1]) {
int = minutes * 60 + seconds
} else if timeComponents.count == 3, let hours = Int64(timeComponents[0]), let minutes = Int64(timeComponents[1]), let seconds = Int64(timeComponents[2]) {
int = hours * 3600 + minutes * 60 + seconds
}
return int
}
}
| 6b6747953e514c201fafe5b72030d32e | 31.291667 | 164 | 0.624516 | false | false | false | false |
playbasis/native-sdk-ios | refs/heads/master | PlaybasisSDK/Classes/PBModel/PBRewardData.swift | mit | 1 | //
// PBRewardData.swift
// Playbook
//
// Created by Nuttapol Thitaweera on 6/21/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
import ObjectMapper
public class PBRedeem: PBModel {
public var point:PBRedeemPoint!
public var custom:[PBRedeemCustom]! = []
override public func mapping(map: Map) {
super.mapping(map)
point <- map["point"]
custom <- map["custom"]
}
}
public class PBRedeemPoint:PBModel {
public var pointValue:Int! = 0
override public func mapping(map: Map) {
super.mapping(map)
pointValue <- map["point_value"]
}
}
public class PBRedeemCustom:PBModel {
public var customId:String?
public var customName:String?
public var customValue:Int! = 0
override public func mapping(map: Map) {
super.mapping(map)
customId <- map["custom_id"]
customName <- map["custom_name"]
customValue <- map["custom_value"]
}
}
public class PBRewardData: PBModel {
public var rewardDataId:String?
public var desc:String! = ""
public var imageURL:String! = ""
public var status:Bool = false
public var deleted:Bool = false
public var sponsor:Bool = false
public var tags:[String]?
public var dateStart:NSDate?
public var dateExpire:NSDate?
public var dateAdded:NSDate?
public var dateModified:NSDate?
public var name:String! = ""
public var code:String! = ""
public var clientId:String?
public var siteId:String?
public var goodsId:String?
public var group:String?
public var amount:Int = 0
public var quantity:Int = 0
public var perUser:Int = 0
public var sortOrder:Int = 0
public var languageId:Int = 0
public var redeem:PBRedeem!
public override init() {
super.init()
}
required public init?(_ map: Map) {
super.init(map)
}
override public func mapping(map: Map) {
super.mapping(map)
rewardDataId <- map["_id"]
desc <- map["description"]
quantity <- map["quantity"]
perUser <- map["per_user"]
imageURL <- map["image"]
status <- map["status"]
deleted <- map["deleted"]
sponsor <- map["sponsor"]
sortOrder <- map["sort_order"]
languageId <- map["language_id"]
sortOrder <- map["sort_order"]
tags <- map["tags"]
dateStart <- (map["date_start"], ISO8601DateTransform())
dateExpire <- (map["date_expire"], ISO8601DateTransform())
dateAdded <- (map["date_added"], ISO8601DateTransform())
dateModified <- (map["date_modified"], ISO8601DateTransform())
name <- map["name"]
code <- map["code"]
clientId <- map["client_id"]
siteId <- map["site_id"]
goodsId <- map["goods_id"]
group <- map["group"]
amount <- map["amount"]
redeem <- map["redeem"]
}
class func pbGoodsFromApiResponse(apiResponse:PBApiResponse) -> [PBRewardData] {
var goods:[PBRewardData] = []
goods = Mapper<PBRewardData>().mapArray(apiResponse.parsedJson!["goods_list"])!
return goods
}
class func pbSmallGoodsFromApiResponse(apiResponse:PBApiResponse) -> [PBRewardData] {
var goods:[PBRewardData] = []
goods = Mapper<PBRewardData>().mapArray(apiResponse.parsedJson!["goods"])!
return goods
}
}
| 88f180b1a6167c37b7299b9ac9b54dea | 27.595041 | 89 | 0.607803 | false | false | false | false |
937447974/YJCocoa | refs/heads/master | Demo/Swift/DeveloperTools/YJTimeProfiler/YJTimeProfiler/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// YJFoundation
//
// Created by 阳君 on 2019/5/6.
// Copyright © 2019 YJCocoa. All rights reserved.
//
import UIKit
import YJCocoa
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let timeProfiler = YJTimeProfiler()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.timeProfiler.start()
YJLog.levels = [.verbose, .debug, .info, .warn, .error]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
self.window?.rootViewController = ViewController()
self.window?.makeKeyAndVisible()
return true
}
}
| 22ee85245729e98b3beb2c27c9cb55f5 | 26.241379 | 145 | 0.696203 | false | false | false | false |
BradLarson/GPUImage2 | refs/heads/develop | GPUImage-Swift/framework/Source/Operations/PolkaDot.swift | apache-2.0 | 9 | public class PolkaDot: BasicOperation {
public var dotScaling:Float = 0.90 { didSet { uniformSettings["dotScaling"] = dotScaling } }
public var fractionalWidthOfAPixel:Float = 0.01 {
didSet {
let imageWidth = 1.0 / Float(self.renderFramebuffer?.size.width ?? 2048)
uniformSettings["fractionalWidthOfPixel"] = max(fractionalWidthOfAPixel, imageWidth)
}
}
public init() {
super.init(fragmentShader:PolkaDotFragmentShader, numberOfInputs:1)
({fractionalWidthOfAPixel = 0.01})()
({dotScaling = 0.90})()
}
} | c5e6722cd6a2dbf6986f465f5b9dec35 | 36.5625 | 96 | 0.638333 | false | false | false | false |
PatMurrayDEV/WWDC17 | refs/heads/master | PatMurrayWWDC17.playground/Sources/extensions.swift | mit | 1 | import UIKit
internal struct RotationOptions: OptionSet {
let rawValue: Int
static let flipOnVerticalAxis = RotationOptions(rawValue: 1)
static let flipOnHorizontalAxis = RotationOptions(rawValue: 2)
}
public extension UIImage {
// This outputs the image as an array of pixels
public func pixelData() -> [[UInt8]]? {
// Resize and rotate the image
let resizedImage = self.resizeImage(newHeight: 50)
let rotatedImage = resizedImage.rotated(by: Measurement(value: 90, unit: .degrees), options: RotationOptions.flipOnHorizontalAxis)!
// Get the size of the image to be used in calculatations below
let size = rotatedImage.size
let width = size.width
let height = size.height
// Generate pixel array
let dataSize = width * height * 4
var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceGray()
let context = CGContext(data: &pixelData,
width: Int(width),
height: Int(height),
bitsPerComponent: 8,
bytesPerRow: 4 * Int(width),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let cgImage = rotatedImage.cgImage else { return nil }
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
// Clean pixels to just keep black pixels
let cleanedPixels = stride(from: 1, to: pixelData.count, by: 2).map {
pixelData[$0]
}
// Separate pixels into rows (Array of arrays)
let chunkSize = 2 * Int(width) // this was 4
let chunks = stride(from: 0, to: cleanedPixels.count, by: chunkSize).map {
Array(cleanedPixels[$0..<min($0 + chunkSize, cleanedPixels.count)])
}
return chunks
}
func resizeImage(newHeight: CGFloat) -> UIImage {
let scale = newHeight / self.size.height
let newWidth = self.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
internal func rotated(by rotationAngle: Measurement<UnitAngle>, options: RotationOptions = []) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let rotationInRadians = CGFloat(rotationAngle.converted(to: .radians).value)
let transform = CGAffineTransform(rotationAngle: rotationInRadians)
var rect = CGRect(origin: .zero, size: self.size).applying(transform)
rect.origin = .zero
let renderer = UIGraphicsImageRenderer(size: rect.size)
return renderer.image { renderContext in
renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
renderContext.cgContext.rotate(by: rotationInRadians)
let x = options.contains(.flipOnVerticalAxis) ? -1.0 : 1.0
let y = options.contains(.flipOnHorizontalAxis) ? 1.0 : -1.0
renderContext.cgContext.scaleBy(x: CGFloat(x), y: CGFloat(y))
let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size)
renderContext.cgContext.draw(cgImage, in: drawRect)
}
}
}
| fc3238779a13ca82449031709b3434ae | 35.705882 | 139 | 0.591346 | false | false | false | false |
xxxAIRINxxx/MusicPlayerTransition | refs/heads/master | MusicPlayerTransition/MusicPlayerTransition/ViewController.swift | mit | 1 | //
// ViewController.swift
// MusicPlayerTransition
//
// Created by xxxAIRINxxx on 2015/08/27.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
import ARNTransitionAnimator
final class ViewController: UIViewController {
@IBOutlet fileprivate(set) weak var containerView : UIView!
@IBOutlet fileprivate(set) weak var miniPlayerView : LineView!
@IBOutlet fileprivate(set) weak var miniPlayerButton : UIButton!
private var animator : ARNTransitionAnimator?
fileprivate var modalVC : ModalViewController!
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
self.modalVC = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController
self.modalVC.modalPresentationStyle = .overCurrentContext
let color = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.3)
self.miniPlayerButton.setBackgroundImage(self.generateImageWithColor(color), for: .highlighted)
self.setupAnimator()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("ViewController viewWillAppear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("ViewController viewWillDisappear")
}
func setupAnimator() {
let animation = MusicPlayerTransitionAnimation(rootVC: self, modalVC: self.modalVC)
animation.completion = { [weak self] isPresenting in
if isPresenting {
guard let _self = self else { return }
let modalGestureHandler = TransitionGestureHandler(targetView: _self.modalVC.view, direction: .bottom)
modalGestureHandler.panCompletionThreshold = 15.0
_self.animator?.registerInteractiveTransitioning(.dismiss, gestureHandler: modalGestureHandler)
} else {
self?.setupAnimator()
}
}
let gestureHandler = TransitionGestureHandler(targetView: self.miniPlayerView, direction: .top)
gestureHandler.panCompletionThreshold = 15.0
gestureHandler.panFrameSize = self.view.bounds.size
self.animator = ARNTransitionAnimator(duration: 0.5, animation: animation)
self.animator?.registerInteractiveTransitioning(.present, gestureHandler: gestureHandler)
self.modalVC.transitioningDelegate = self.animator
}
@IBAction func tapMiniPlayerButton() {
self.present(self.modalVC, animated: true, completion: nil)
}
fileprivate func generateImageWithColor(_ color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| 747ad3eab9b4a510a227a7228c062ef2 | 35.090909 | 122 | 0.666247 | false | false | false | false |
kitoko552/MaterialButton | refs/heads/master | Sample/ViewController.swift | mit | 1 | //
// ViewController.swift
// MaterialButton
//
// Created by Kosuke Kito on 2015/06/29.
// Copyright (c) 2015年 Kosuke Kito. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var plusButton: MaterialButton! {
didSet {
plusButton.layer.cornerRadius = plusButton.bounds.size.width / 2
plusButton.layer.shadowOffset = CGSizeMake(0, 10)
plusButton.layer.shadowRadius = 4
plusButton.layer.shadowOpacity = 0.2
}
}
@IBOutlet weak var xButton: MaterialButton! {
didSet {
// You can change ripple color.
xButton.rippleColor = UIColor.lightGrayColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| fbf3e4e7600ecfd00433df2bfd588cf4 | 24.516129 | 76 | 0.618205 | false | false | false | false |
cseduardorangel/Cantina | refs/heads/master | Cantina/Class/Util/Extension/NSDateExtensions.swift | mit | 1 | //
// NSDateExtension.swift
// Cantina
//
// Created by Eduardo Rangel on 1/26/16.
// Copyright © 2016 Concrete Solutions. All rights reserved.
//
import Foundation
extension NSDate {
static func hourMinute(date: NSDate) -> String {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(name: "America/Sao_Paulo")!
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
let minute = components.minute
return String(format: "%d:%.2dh", hour, minute)
}
static func dayMonth(date: NSDate) -> String {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Day, .Month], fromDate: date)
let day = components.day
let months = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
let month = months[components.month - 1]
return String(format: "%d %@", day, month)
}
} | a022606ad6e374b99f304b417370d361 | 28 | 105 | 0.59469 | false | false | false | false |
exchangegroup/MprHttp | refs/heads/master | MprHttp/TegQ/TegString.swift | mit | 2 | //
// Helper functions to work with strings.
//
import Foundation
public struct TegString {
public static func blank(text: String) -> Bool {
let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return trimmed.isEmpty
}
public static func trim(text: String) -> String {
return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
public static func contains(text: String, substring: String,
ignoreCase: Bool = false,
ignoreDiacritic: Bool = false) -> Bool {
var options: UInt = 0
if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue }
if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue }
return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil
}
//
// Returns a single space if string is empty.
// It is used to set UITableView cells labels as a workaround.
//
public static func singleSpaceIfEmpty(text: String) -> String {
if text == "" {
return " "
}
return text
}
}
| e09d93bcecf0901eda8b5732fca16555 | 27.875 | 105 | 0.720346 | false | false | false | false |
gdelarosa/Safe-Reach | refs/heads/master | Safe Reach/MapViewController.swift | mit | 1 | //
// ViewController.swift
// Safe Reach
//
// Created by Gina De La Rosa on 9/6/16.
// Copyright © 2016 Gina De La Rosa. All rights reserved.
//
import UIKit
import MapKit
protocol HandleMapSearch: class {
func dropPinZoomIn(_ placemark:MKPlacemark)
}
class MapViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var mapView: MKMapView!
var locations = [Locations]()
var locationManager = CLLocationManager()
// Testing
var selectedPin: MKPlacemark?
var resultSearchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
mapView.delegate = self
loadInitialData()
mapView.addAnnotations(locations)
// Navigation Controller UI
let imageView = UIImageView(image: UIImage(named: "Triangle"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}
// override func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
// //checkLocationAuthorizationStatus()
// }
// let regionRadius: CLLocationDistance = 10000
//
// func centerMapOnLocation(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// if let location = locations.first {
// let span = MKCoordinateSpanMake(0.05, 0.05)
// let region = MKCoordinateRegion(center: location.coordinate, span: span)
// mapView.setRegion(region, animated: true)
// }
//// let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
//// mapView.setRegion(coordinateRegion, animated: true)
// }
func loadInitialData(){
let filename = Bundle.main.path(forResource: "Location", ofType: "json")
var data: Data?
do{
data = try Data(contentsOf: URL(fileURLWithPath: filename!), options: Data.ReadingOptions(rawValue: 0))
}catch _ {
data = nil
}
var jsonObject: AnyObject?
if let data = data {
do {
jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as AnyObject
}catch _ {
jsonObject = nil
}
}
if let jsonObject = jsonObject as? [String: AnyObject], let jsonData = JSONValue.fromObject(jsonObject as AnyObject)?["data"]?.array{
for locationJSON in jsonData {
if let locationJSON = locationJSON.array, let location = Locations.fromJSON(locationJSON){
locations.append(location)
}
}
}
}
// func checkLocationAuthorizationStatus(){
// if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
// mapView.showsUserLocation = true
// }else {
// locationManager.requestWhenInUseAuthorization()
// }
// }
// TESTING, zooms to users location.
// func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// if let location = locations.first {
// let span = MKCoordinateSpanMake(0.05, 0.05)
// let region = MKCoordinateRegion(center: location.coordinate, span: span)
// mapView.setRegion(region, animated: true)
// }
// }
}
extension MapViewController : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.first != nil {
print("location:: (location)")
}
if let location = locations.first {
let span = MKCoordinateSpanMake(0.10, 0.10)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
}
| 867a7d3446eb4c3ef30d50b2e307a742 | 33.042553 | 143 | 0.62625 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | refs/heads/master | TruckMuncher/api/Error.swift | gpl-2.0 | 1 | //
// Error.swift
// TruckMuncher
//
// Created by Josh Ault on 4/16/15.
// Copyright (c) 2015 TruckMuncher. All rights reserved.
//
import Foundation
class Error {
var userMessage: String = ""
var internalCode: String = ""
class func parseFromDict(dict: [String: AnyObject]) -> Error {
let error = Error()
error.userMessage = dict["userMessage"] as! String
error.internalCode = dict["internalCode"] as! String
return error
}
} | 8193e1b7f5fa7119ea1cd6b06c146e34 | 22.190476 | 66 | 0.62963 | false | false | false | false |
shajrawi/swift | refs/heads/master | test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift | apache-2.0 | 2 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: rdar50301438
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
import Accelerate
var Accelerate_vDSPClippingLimitThresholdTests = TestSuite("Accelerate_vDSPClippingLimitThreshold")
//===----------------------------------------------------------------------===//
//
// vDSP clipping, limit, and threshold tests; single-precision.
//
//===----------------------------------------------------------------------===//
if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) {
let count = 256
let n = vDSP_Length(256)
let bounds = Float(-0.5) ... Float(0.5)
let outputConstant: Float = 99
let source: [Float] = (0 ..< 256).map { i in
return sin(Float(i) * 0.05) + sin(Float(i) * 0.025)
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionClipping") {
var result = [Float](repeating: 0,
count: count)
vDSP.clip(source,
to: bounds,
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_vclip(source, 1,
[bounds.lowerBound],
[bounds.upperBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.clip(source,
to: bounds)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionInvertedClipping") {
var result = [Float](repeating: 0,
count: count)
vDSP.invertedClip(source,
to: bounds,
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_viclip(source, 1,
[bounds.lowerBound],
[bounds.upperBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.invertedClip(source,
to: bounds)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThreshold") {
var result = [Float](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .clampToThreshold,
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_vthr(source, 1,
[bounds.lowerBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .clampToThreshold)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithConstant") {
var result = [Float](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .signedConstant(outputConstant),
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_vthrsc(source, 1,
[bounds.lowerBound],
[outputConstant],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .signedConstant(outputConstant))
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithZeroFill") {
var result = [Float](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .zeroFill,
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_vthres(source, 1,
[bounds.lowerBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .zeroFill)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionLimit") {
var result = [Float](repeating: 0,
count: count)
vDSP.limit(source,
limit: bounds.upperBound,
withOutputConstant: outputConstant,
result: &result)
var legacyResult = [Float](repeating: -1,
count: count)
vDSP_vlim(source, 1,
[bounds.upperBound],
[outputConstant],
&legacyResult, 1,
n)
let returnedResult = vDSP.limit(source,
limit: bounds.upperBound,
withOutputConstant: outputConstant)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
}
//===----------------------------------------------------------------------===//
//
// vDSP clipping, limit, and threshold tests; double-precision.
//
//===----------------------------------------------------------------------===//
if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) {
let count = 256
let n = vDSP_Length(256)
let bounds = Double(-0.5) ... Double(0.5)
let outputConstant: Double = 99
let source: [Double] = (0 ..< 256).map { i in
return sin(Double(i) * 0.05) + sin(Double(i) * 0.025)
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionClipping") {
var result = [Double](repeating: 0,
count: count)
vDSP.clip(source,
to: bounds,
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_vclipD(source, 1,
[bounds.lowerBound],
[bounds.upperBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.clip(source,
to: bounds)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionInvertedClipping") {
var result = [Double](repeating: 0,
count: count)
vDSP.invertedClip(source,
to: bounds,
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_viclipD(source, 1,
[bounds.lowerBound],
[bounds.upperBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.invertedClip(source,
to: bounds)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThreshold") {
var result = [Double](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .clampToThreshold,
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_vthrD(source, 1,
[bounds.lowerBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .clampToThreshold)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithConstant") {
var result = [Double](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .signedConstant(outputConstant),
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_vthrscD(source, 1,
[bounds.lowerBound],
[outputConstant],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .signedConstant(outputConstant))
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithZeroFill") {
var result = [Double](repeating: 0,
count: count)
vDSP.threshold(source,
to: bounds.lowerBound,
with: .zeroFill,
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_vthresD(source, 1,
[bounds.lowerBound],
&legacyResult, 1,
n)
let returnedResult = vDSP.threshold(source,
to: bounds.lowerBound,
with: .zeroFill)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionLimit") {
var result = [Double](repeating: 0,
count: count)
vDSP.limit(source,
limit: bounds.upperBound,
withOutputConstant: outputConstant,
result: &result)
var legacyResult = [Double](repeating: -1,
count: count)
vDSP_vlimD(source, 1,
[bounds.upperBound],
[outputConstant],
&legacyResult, 1,
n)
let returnedResult = vDSP.limit(source,
limit: bounds.upperBound,
withOutputConstant: outputConstant)
expectTrue(result.elementsEqual(legacyResult))
expectTrue(result.elementsEqual(returnedResult))
}
}
runAllTests()
| b00a977baab179dcae8ddf7341279989 | 34.431818 | 99 | 0.466966 | false | true | false | false |
alblue/swift | refs/heads/master | test/Prototypes/BigInt.swift | apache-2.0 | 2 | //===--- BigInt.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// XFAIL: linux
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 4 -o %t/a.out %s
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import StdlibUnittest
import Darwin
extension FixedWidthInteger {
/// Returns the high and low parts of a potentially overflowing addition.
func addingFullWidth(_ other: Self) ->
(high: Self, low: Self) {
let sum = self.addingReportingOverflow(other)
return (sum.overflow ? 1 : 0, sum.partialValue)
}
/// Returns the high and low parts of two seqeuential potentially overflowing
/// additions.
static func addingFullWidth(_ x: Self, _ y: Self, _ z: Self) ->
(high: Self, low: Self) {
let xy = x.addingReportingOverflow(y)
let xyz = xy.partialValue.addingReportingOverflow(z)
let high: Self = (xy.overflow ? 1 : 0) +
(xyz.overflow ? 1 : 0)
return (high, xyz.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial difference of this value and `rhs`.
func subtractingWithBorrow(_ rhs: Self) ->
(borrow: Self, partialValue: Self) {
let difference = subtractingReportingOverflow(rhs)
return (difference.overflow ? 1 : 0, difference.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial value of `x` and `y` subtracted from this value.
func subtractingWithBorrow(_ x: Self, _ y: Self) ->
(borrow: Self, partialValue: Self) {
let firstDifference = subtractingReportingOverflow(x)
let secondDifference =
firstDifference.partialValue.subtractingReportingOverflow(y)
let borrow: Self = (firstDifference.overflow ? 1 : 0) +
(secondDifference.overflow ? 1 : 0)
return (borrow, secondDifference.partialValue)
}
}
//===--- BigInt -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A dynamically-sized signed integer.
///
/// The `_BigInt` type is fully generic on the size of its "word" -- the
/// `BigInt` alias uses the system's word-sized `UInt` as its word type, but
/// any word size should work properly.
public struct _BigInt<Word: FixedWidthInteger & UnsignedInteger> :
BinaryInteger, SignedInteger, CustomStringConvertible,
CustomDebugStringConvertible
where Word.Magnitude == Word
{
/// The binary representation of the value's magnitude, with the least
/// significant word at index `0`.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false` and `_data == []`
internal var _data: [Word] = []
/// A Boolean value indicating whether this instance is negative.
public private(set) var isNegative = false
/// A Boolean value indicating whether this instance is equal to zero.
public var isZero: Bool {
return _data.count == 0
}
//===--- Numeric initializers -------------------------------------------===//
/// Creates a new instance equal to zero.
public init() { }
/// Creates a new instance using `_data` as the data collection.
init<C: Collection>(_ _data: C) where C.Iterator.Element == Word {
self._data = Array(_data)
_standardize()
}
public init(integerLiteral value: Int) {
self.init(value)
}
public init<T : BinaryInteger>(_ source: T) {
var source = source
if source < 0 as T {
if source.bitWidth <= UInt64.bitWidth {
let sourceMag = Int(truncatingIfNeeded: source).magnitude
self = _BigInt(sourceMag)
self.isNegative = true
return
} else {
// Have to kind of assume that we're working with another BigInt here
self.isNegative = true
source *= -1
}
}
// FIXME: This is broken on 32-bit arch w/ Word = UInt64
let wordRatio = UInt.bitWidth / Word.bitWidth
assert(wordRatio != 0)
for var sourceWord in source.words {
for _ in 0..<wordRatio {
_data.append(Word(truncatingIfNeeded: sourceWord))
sourceWord >>= Word.bitWidth
}
}
_standardize()
}
public init?<T : BinaryInteger>(exactly source: T) {
self.init(source)
}
public init<T : BinaryInteger>(truncatingIfNeeded source: T) {
self.init(source)
}
public init<T : BinaryInteger>(clamping source: T) {
self.init(source)
}
public init<T : BinaryFloatingPoint>(_ source: T) {
fatalError("Not implemented")
}
public init?<T : BinaryFloatingPoint>(exactly source: T) {
fatalError("Not implemented")
}
/// Returns a randomly-generated word.
static func _randomWord() -> Word {
// This handles up to a 64-bit word
if Word.bitWidth > UInt32.bitWidth {
return Word(arc4random()) << 32 | Word(arc4random())
} else {
return Word(truncatingIfNeeded: arc4random())
}
}
/// Creates a new instance whose magnitude has `randomBits` bits of random
/// data. The sign of the new value is randomly selected.
public init(randomBits: Int) {
let (words, extraBits) =
randomBits.quotientAndRemainder(dividingBy: Word.bitWidth)
// Get the bits for any full words.
self._data = (0..<words).map({ _ in _BigInt._randomWord() })
// Get another random number - the highest bit will determine the sign,
// while the lower `Word.bitWidth - 1` bits are available for any leftover
// bits in `randomBits`.
let word = _BigInt._randomWord()
if extraBits != 0 {
let mask = ~((~0 as Word) << Word(extraBits))
_data.append(word & mask)
}
isNegative = word & ~(~0 >> 1) == 0
_standardize()
}
//===--- Private methods ------------------------------------------------===//
/// Standardizes this instance after mutation, removing trailing zeros
/// and making sure zero is nonnegative. Calling this method satisfies the
/// two invariants.
mutating func _standardize(source: String = #function) {
defer { _checkInvariants(source: source + " >> _standardize()") }
while _data.last == 0 {
_data.removeLast()
}
// Zero is never negative.
isNegative = isNegative && _data.count != 0
}
/// Checks and asserts on invariants -- all invariants must be satisfied
/// at the end of every mutating method.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false`
func _checkInvariants(source: String = #function) {
if _data.count == 0 {
assert(isNegative == false,
"\(source): isNegative with zero length _data")
}
assert(_data.last != 0, "\(source): extra zeroes on _data")
}
//===--- Word-based arithmetic ------------------------------------------===//
mutating func _unsignedAdd(_ rhs: Word) {
defer { _standardize() }
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// Quick return if `self == 0`
if isZero {
_data.append(rhs)
return
}
// Add `rhs` to the first word, catching any carry.
var carry: Word
(carry, _data[0]) = _data[0].addingFullWidth(rhs)
// Handle any additional carries
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs <= self.magnitude`
mutating func _unsignedSubtract(_ rhs: Word) {
precondition(_data.count > 1 || _data[0] > rhs)
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// If `isZero == true`, then `rhs` must also be zero.
precondition(!isZero)
var carry: Word
(carry, _data[0]) = _data[0].subtractingWithBorrow(rhs)
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
assert(carry == 0)
_standardize()
}
/// Adds `rhs` to this instance.
mutating func add(_ rhs: Word) {
if isNegative {
// If _data only contains one word and `rhs` is greater, swap them,
// make self positive and continue with unsigned subtraction.
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = false
}
_unsignedSubtract(rhs)
} else { // positive or zero
_unsignedAdd(rhs)
}
}
/// Subtracts `rhs` from this instance.
mutating func subtract(_ rhs: Word) {
guard rhs != 0 else { return }
if isNegative {
_unsignedAdd(rhs)
} else if isZero {
isNegative = true
_data.append(rhs)
} else {
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = true
}
_unsignedSubtract(rhs)
}
}
/// Multiplies this instance by `rhs`.
mutating func multiply(by rhs: Word) {
// If either `self` or `rhs` is zero, the result is zero.
guard !isZero && rhs != 0 else {
self = 0
return
}
// If `rhs` is a power of two, can just left shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
self <<= rhsLSB
return
}
var carry: Word = 0
for i in 0..<_data.count {
let product = _data[i].multipliedFullWidth(by: rhs)
(carry, _data[i]) = product.low.addingFullWidth(carry)
carry = carry &+ product.high
}
// Add the leftover carry
if carry != 0 {
_data.append(carry)
}
_standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func divide(by rhs: Word) -> Word {
precondition(rhs != 0, "divide by zero")
// No-op if `rhs == 1` or `self == 0`.
if rhs == 1 || isZero {
return 0
}
// If `rhs` is a power of two, can just right shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
defer { self >>= rhsLSB }
return _data[0] & ~(~0 << rhsLSB)
}
var carry: Word = 0
for i in (0..<_data.count).reversed() {
let lhs = (high: carry, low: _data[i])
(_data[i], carry) = rhs.dividingFullWidth(lhs)
}
_standardize()
return carry
}
//===--- Numeric --------------------------------------------------------===//
public typealias Magnitude = _BigInt
public var magnitude: _BigInt {
var result = self
result.isNegative = false
return result
}
/// Adds `rhs` to this instance, ignoring any signs.
mutating func _unsignedAdd(_ rhs: _BigInt) {
defer { _checkInvariants() }
let commonCount = Swift.min(_data.count, rhs._data.count)
let maxCount = Swift.max(_data.count, rhs._data.count)
_data.reserveCapacity(maxCount)
// Add the words up to the common count, carrying any overflows
var carry: Word = 0
for i in 0..<commonCount {
(carry, _data[i]) = Word.addingFullWidth(_data[i], rhs._data[i], carry)
}
// If there are leftover words in `self`, just need to handle any carries
if _data.count > rhs._data.count {
for i in commonCount..<maxCount {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there are leftover words in `rhs`, need to copy to `self` with carries
} else if _data.count < rhs._data.count {
for i in commonCount..<maxCount {
// Append remaining words if nothing to carry
if carry == 0 {
_data.append(contentsOf: rhs._data.suffix(from: i))
break
}
let sum: Word
(carry, sum) = rhs._data[i].addingFullWidth(carry)
_data.append(sum)
}
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs.magnitude <= self.magnitude` (unchecked)
/// - Precondition: `rhs._data.count <= self._data.count`
mutating func _unsignedSubtract(_ rhs: _BigInt) {
precondition(rhs._data.count <= _data.count)
var carry: Word = 0
for i in 0..<rhs._data.count {
(carry, _data[i]) = _data[i].subtractingWithBorrow(rhs._data[i], carry)
}
for i in rhs._data.count..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
assert(carry == 0)
_standardize()
}
public static func +=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
if lhs.isNegative == rhs.isNegative {
lhs._unsignedAdd(rhs)
} else {
lhs -= -rhs
}
}
public static func -=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
// Subtracting something of the opposite sign just adds magnitude.
guard lhs.isNegative == rhs.isNegative else {
lhs._unsignedAdd(rhs)
return
}
// Comare `lhs` and `rhs` so we can use `_unsignedSubtract` to subtract
// the smaller magnitude from the larger magnitude.
switch lhs._compareMagnitude(to: rhs) {
case .equal:
lhs = 0
case .greaterThan:
lhs._unsignedSubtract(rhs)
case .lessThan:
// x - y == -y + x == -(y - x)
var result = rhs
result._unsignedSubtract(lhs)
result.isNegative = !lhs.isNegative
lhs = result
}
}
public static func *=(lhs: inout _BigInt, rhs: _BigInt) {
// If either `lhs` or `rhs` is zero, the result is zero.
guard !lhs.isZero && !rhs.isZero else {
lhs = 0
return
}
var newData: [Word] = Array(repeating: 0,
count: lhs._data.count + rhs._data.count)
let (a, b) = lhs._data.count > rhs._data.count
? (lhs._data, rhs._data)
: (rhs._data, lhs._data)
assert(a.count >= b.count)
var carry: Word = 0
for ai in 0..<a.count {
carry = 0
for bi in 0..<b.count {
// Each iteration needs to perform this operation:
//
// newData[ai + bi] += (a[ai] * b[bi]) + carry
//
// However, `a[ai] * b[bi]` produces a double-width result, and both
// additions can overflow to a higher word. The following two lines
// capture the low word of the multiplication and additions in
// `newData[ai + bi]` and any addition overflow in `carry`.
let product = a[ai].multipliedFullWidth(by: b[bi])
(carry, newData[ai + bi]) = Word.addingFullWidth(
newData[ai + bi], product.low, carry)
// Now we combine the high word of the multiplication with any addition
// overflow. It is safe to add `product.high` and `carry` here without
// checking for overflow, because if `product.high == .max - 1`, then
// `carry <= 1`. Otherwise, `carry <= 2`.
//
// Worst-case (aka 9 + 9*9 + 9):
//
// newData a[ai] b[bi] carry
// 0b11111111 + (0b11111111 * 0b11111111) + 0b11111111
// 0b11111111 + (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000) + 0b11111111
// (0b11111111_____11111111)
//
// Second-worse case:
//
// 0b11111111 + (0b11111111 * 0b11111110) + 0b11111111
// 0b11111111 + (0b11111101_____00000010) + 0b11111111
// (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000)
assert(!product.high.addingReportingOverflow(carry).overflow)
carry = product.high &+ carry
}
// Leftover `carry` is inserted in new highest word.
assert(newData[ai + b.count] == 0)
newData[ai + b.count] = carry
}
lhs._data = newData
lhs.isNegative = lhs.isNegative != rhs.isNegative
lhs._standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func _internalDivide(by rhs: _BigInt) -> _BigInt {
precondition(!rhs.isZero, "Divided by zero")
defer { _checkInvariants() }
// Handle quick cases that don't require division:
// If `abs(self) < abs(rhs)`, the result is zero, remainder = self
// If `abs(self) == abs(rhs)`, the result is 1 or -1, remainder = 0
switch _compareMagnitude(to: rhs) {
case .lessThan:
defer { self = 0 }
return self
case .equal:
self = isNegative != rhs.isNegative ? -1 : 1
return 0
default:
break
}
var tempSelf = self.magnitude
let n = tempSelf.bitWidth - rhs.magnitude.bitWidth
var quotient: _BigInt = 0
var tempRHS = rhs.magnitude << n
var tempQuotient: _BigInt = 1 << n
for _ in (0...n).reversed() {
if tempRHS._compareMagnitude(to: tempSelf) != .greaterThan {
tempSelf -= tempRHS
quotient += tempQuotient
}
tempRHS >>= 1
tempQuotient >>= 1
}
// `tempSelf` is the remainder - match sign of original `self`
tempSelf.isNegative = self.isNegative
tempSelf._standardize()
quotient.isNegative = isNegative != rhs.isNegative
self = quotient
_standardize()
return tempSelf
}
public static func /=(lhs: inout _BigInt, rhs: _BigInt) {
lhs._internalDivide(by: rhs)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs %= rhs
return lhs
}
//===--- BinaryInteger --------------------------------------------------===//
/// Creates a new instance using the given data array in two's complement
/// representation.
init(_twosComplementData: [Word]) {
guard _twosComplementData.count > 0 else {
self = 0
return
}
// Is the highest bit set?
isNegative = _twosComplementData.last!.leadingZeroBitCount == 0
if isNegative {
_data = _twosComplementData.map(~)
self._unsignedAdd(1 as Word)
} else {
_data = _twosComplementData
}
_standardize()
}
/// Returns an array of the value's data using two's complement representation.
func _dataAsTwosComplement() -> [Word] {
// Special cases:
// * Nonnegative values are already in 2's complement
if !isNegative {
// Positive values need to have a leading zero bit
if _data.last?.leadingZeroBitCount == 0 {
return _data + [0]
} else {
return _data
}
}
// * -1 will get zeroed out below, easier to handle here
if _data.count == 1 && _data.first == 1 { return [~0] }
var x = self
x._unsignedSubtract(1 as Word)
if x._data.last!.leadingZeroBitCount == 0 {
// The highest bit is set to 1, which moves to 0 after negation.
// We need to add another word at the high end so the highest bit is 1.
return x._data.map(~) + [Word.max]
} else {
// The highest bit is set to 0, which moves to 1 after negation.
return x._data.map(~)
}
}
public var words: [UInt] {
assert(UInt.bitWidth % Word.bitWidth == 0)
let twosComplementData = _dataAsTwosComplement()
var words: [UInt] = []
words.reserveCapacity((twosComplementData.count * Word.bitWidth
+ UInt.bitWidth - 1) / UInt.bitWidth)
var word: UInt = 0
var shift = 0
for w in twosComplementData {
word |= UInt(truncatingIfNeeded: w) << shift
shift += Word.bitWidth
if shift == UInt.bitWidth {
words.append(word)
word = 0
shift = 0
}
}
if shift != 0 {
if isNegative {
word |= ~((1 << shift) - 1)
}
words.append(word)
}
return words
}
/// The number of bits used for storage of this value. Always a multiple of
/// `Word.bitWidth`.
public var bitWidth: Int {
if isZero {
return 0
} else {
let twosComplementData = _dataAsTwosComplement()
// If negative, it's okay to have 1s padded on high end
if isNegative {
return twosComplementData.count * Word.bitWidth
}
// If positive, need to make space for at least one zero on high end
return twosComplementData.count * Word.bitWidth
- twosComplementData.last!.leadingZeroBitCount + 1
}
}
/// The number of sequential zeros in the least-significant position of this
/// value's binary representation.
///
/// The numbers 1 and zero have zero trailing zeros.
public var trailingZeroBitCount: Int {
guard !isZero else {
return 0
}
let i = _data.firstIndex(where: { $0 != 0 })!
assert(_data[i] != 0)
return i * Word.bitWidth + _data[i].trailingZeroBitCount
}
public static func %=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
lhs = lhs._internalDivide(by: rhs)
}
public func quotientAndRemainder(dividingBy rhs: _BigInt) ->
(_BigInt, _BigInt)
{
var x = self
let r = x._internalDivide(by: rhs)
return (x, r)
}
public static func &=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s
// * If `rhs >= 0`, length is extended with 0s, which crops `lhsTemp`
if lhsTemp.count > rhsTemp.count && !rhs.isNegative {
lhsTemp.removeLast(lhsTemp.count - rhsTemp.count)
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so `lhs` should get extra
// bits from `rhs`
// * If `lhs >= 0`, length is extended with 0s
if lhsTemp.count < rhsTemp.count && lhs.isNegative {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
// Perform bitwise & on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] &= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func |=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be 1
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
lhsTemp.replaceSubrange(rhsTemp.count..<lhsTemp.count,
with: repeatElement(Word.max, count: lhsTemp.count - rhsTemp.count))
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of lhs
// should all be 1
// * If `lhs >= 0`, length is extended with 0s, so those bits should be
// copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp.append(contentsOf:
repeatElement(Word.max, count: rhsTemp.count - lhsTemp.count))
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise | on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] |= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func ^=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
for i in rhsTemp.count..<lhsTemp.count {
lhsTemp[i] = ~lhsTemp[i]
}
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped copies of `rhs`
// * If `lhs >= 0`, length is extended with 0s, so those bits should
// be copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp += rhsTemp.suffix(from: lhsTemp.count).map(~)
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise ^ on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] ^= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static prefix func ~(x: _BigInt) -> _BigInt {
return -x - 1
}
//===--- SignedNumeric --------------------------------------------------===//
public static prefix func -(x: inout _BigInt) {
defer { x._checkInvariants() }
guard x._data.count > 0 else { return }
x.isNegative = !x.isNegative
}
//===--- Strideable -----------------------------------------------------===//
public func distance(to other: _BigInt) -> _BigInt {
return other - self
}
public func advanced(by n: _BigInt) -> _BigInt {
return self + n
}
//===--- Other arithmetic -----------------------------------------------===//
/// Returns the greatest common divisor for this value and `other`.
public func greatestCommonDivisor(with other: _BigInt) -> _BigInt {
// Quick return if either is zero
if other.isZero {
return magnitude
}
if isZero {
return other.magnitude
}
var (x, y) = (self.magnitude, other.magnitude)
let (xLSB, yLSB) = (x.trailingZeroBitCount, y.trailingZeroBitCount)
// Remove any common factor of two
let commonPower = Swift.min(xLSB, yLSB)
x >>= commonPower
y >>= commonPower
// Remove any remaining factor of two
if xLSB != commonPower {
x >>= xLSB - commonPower
}
if yLSB != commonPower {
y >>= yLSB - commonPower
}
while !x.isZero {
// Swap values to ensure that `x >= y`.
if x._compareMagnitude(to: y) == .lessThan {
swap(&x, &y)
}
// Subtract smaller and remove any factors of two
x._unsignedSubtract(y)
x >>= x.trailingZeroBitCount
}
// Add original common factor of two back into result
y <<= commonPower
return y
}
/// Returns the lowest common multiple for this value and `other`.
public func lowestCommonMultiple(with other: _BigInt) -> _BigInt {
let gcd = greatestCommonDivisor(with: other)
if _compareMagnitude(to: other) == .lessThan {
return ((self / gcd) * other).magnitude
} else {
return ((other / gcd) * self).magnitude
}
}
//===--- String methods ------------------------------------------------===//
/// Creates a new instance from the given string.
///
/// - Parameters:
/// - source: The string to parse for the new instance's value. If a
/// character in `source` is not in the range `0...9` or `a...z`, case
/// insensitive, or is not less than `radix`, the result is `nil`.
/// - radix: The radix to use when parsing `source`. `radix` must be in the
/// range `2...36`. The default is `10`.
public init?(_ source: String, radix: Int = 10) {
assert(2...36 ~= radix, "radix must be in range 2...36")
let radix = Word(radix)
func valueForCodeUnit(_ unit: Unicode.UTF16.CodeUnit) -> Word? {
switch unit {
// "0"..."9"
case 48...57: return Word(unit - 48)
// "a"..."z"
case 97...122: return Word(unit - 87)
// "A"..."Z"
case 65...90: return Word(unit - 55)
// invalid character
default: return nil
}
}
var source = source
// Check for a single prefixing hyphen
let negative = source.hasPrefix("-")
if negative {
source = String(source.dropFirst())
}
// Loop through characters, multiplying
for v in source.utf16.map(valueForCodeUnit) {
// Character must be valid and less than radix
guard let v = v else { return nil }
guard v < radix else { return nil }
self.multiply(by: radix)
self.add(v)
}
self.isNegative = negative
}
/// Returns a string representation of this instance.
///
/// - Parameters:
/// - radix: The radix to use when converting this instance to a string.
/// The value passed as `radix` must be in the range `2...36`. The
/// default is `10`.
/// - lowercase: Whether to use lowercase letters to represent digits
/// greater than 10. The default is `true`.
public func toString(radix: Int = 10, lowercase: Bool = true) -> String {
assert(2...36 ~= radix, "radix must be in range 2...36")
let digitsStart = ("0" as Unicode.Scalar).value
let lettersStart = ((lowercase ? "a" : "A") as Unicode.Scalar).value - 10
func toLetter(_ x: UInt32) -> Unicode.Scalar {
return x < 10
? Unicode.Scalar(digitsStart + x)!
: Unicode.Scalar(lettersStart + x)!
}
let radix = _BigInt(radix)
var result: [Unicode.Scalar] = []
var x = self.magnitude
while !x.isZero {
let remainder: _BigInt
(x, remainder) = x.quotientAndRemainder(dividingBy: radix)
result.append(toLetter(UInt32(remainder)))
}
let sign = isNegative ? "-" : ""
let rest = result.count == 0
? "0"
: String(String.UnicodeScalarView(result.reversed()))
return sign + rest
}
public var description: String {
return decimalString
}
public var debugDescription: String {
return "_BigInt(\(hexString), words: \(_data.count))"
}
/// A string representation of this instance's value in base 2.
public var binaryString: String {
return toString(radix: 2)
}
/// A string representation of this instance's value in base 10.
public var decimalString: String {
return toString(radix: 10)
}
/// A string representation of this instance's value in base 16.
public var hexString: String {
return toString(radix: 16, lowercase: false)
}
/// A string representation of this instance's value in base 36.
public var compactString: String {
return toString(radix: 36, lowercase: false)
}
//===--- Comparable -----------------------------------------------------===//
enum _ComparisonResult {
case lessThan, equal, greaterThan
}
/// Returns whether this instance is less than, greather than, or equal to
/// the given value.
func _compare(to rhs: _BigInt) -> _ComparisonResult {
// Negative values are less than positive values
guard isNegative == rhs.isNegative else {
return isNegative ? .lessThan : .greaterThan
}
switch _compareMagnitude(to: rhs) {
case .equal:
return .equal
case .lessThan:
return isNegative ? .greaterThan : .lessThan
case .greaterThan:
return isNegative ? .lessThan : .greaterThan
}
}
/// Returns whether the magnitude of this instance is less than, greather
/// than, or equal to the magnitude of the given value.
func _compareMagnitude(to rhs: _BigInt) -> _ComparisonResult {
guard _data.count == rhs._data.count else {
return _data.count < rhs._data.count ? .lessThan : .greaterThan
}
// Equal number of words: compare from most significant word
for i in (0..<_data.count).reversed() {
if _data[i] < rhs._data[i] { return .lessThan }
if _data[i] > rhs._data[i] { return .greaterThan }
}
return .equal
}
public static func ==(lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .equal
}
public static func < (lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .lessThan
}
//===--- Hashable -------------------------------------------------------===//
public var hashValue: Int {
#if arch(i386) || arch(arm)
let p: UInt = 16777619
let h: UInt = (2166136261 &* p) ^ (isNegative ? 1 : 0)
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
let p: UInt = 1099511628211
let h: UInt = (14695981039346656037 &* p) ^ (isNegative ? 1 : 0)
#else
fatalError("Unimplemented")
#endif
return Int(bitPattern: _data.reduce(h, { ($0 &* p) ^ UInt($1) }))
}
//===--- Bit shifting operators -----------------------------------------===//
static func _shiftLeft(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.insert(contentsOf: repeatElement(0, count: words), at: 0)
}
static func _shiftRight(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.removeFirst(Swift.min(data.count, words))
}
public static func <<= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs >>= 0 - rhs
return
}
let wordWidth = RHS(Word.bitWidth)
// We can add `rhs / bits` extra words full of zero at the low end.
let extraWords = Int(rhs / wordWidth)
lhs._data.reserveCapacity(lhs._data.count + extraWords + 1)
_BigInt._shiftLeft(&lhs._data, byWords: extraWords)
// Each existing word will need to be shifted left by `rhs % bits`.
// For each pair of words, we'll use the high `offset` bits of the
// lower word and the low `Word.bitWidth - offset` bits of the higher
// word.
let highOffset = Int(rhs % wordWidth)
let lowOffset = Word.bitWidth - highOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard highOffset != 0 else { return }
// Add new word at the end, then shift everything left by `offset` bits.
lhs._data.append(0)
for i in ((extraWords + 1)..<lhs._data.count).reversed() {
lhs._data[i] = lhs._data[i] << highOffset
| lhs._data[i - 1] >> lowOffset
}
// Finally, shift the lowest word.
lhs._data[extraWords] = lhs._data[extraWords] << highOffset
lhs._standardize()
}
public static func >>= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs <<= 0 - rhs
return
}
var tempData = lhs._dataAsTwosComplement()
let wordWidth = RHS(Word.bitWidth)
// We can remove `rhs / bits` full words at the low end.
// If that removes the entirety of `_data`, we're done.
let wordsToRemove = Int(rhs / wordWidth)
_BigInt._shiftRight(&tempData, byWords: wordsToRemove)
guard tempData.count != 0 else {
lhs = lhs.isNegative ? -1 : 0
return
}
// Each existing word will need to be shifted right by `rhs % bits`.
// For each pair of words, we'll use the low `offset` bits of the
// higher word and the high `_BigInt.Word.bitWidth - offset` bits of
// the lower word.
let lowOffset = Int(rhs % wordWidth)
let highOffset = Word.bitWidth - lowOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard lowOffset != 0 else {
lhs = _BigInt(_twosComplementData: tempData)
return
}
// Shift everything right by `offset` bits.
for i in 0..<(tempData.count - 1) {
tempData[i] = tempData[i] >> lowOffset |
tempData[i + 1] << highOffset
}
// Finally, shift the highest word and standardize the result.
tempData[tempData.count - 1] >>= lowOffset
lhs = _BigInt(_twosComplementData: tempData)
}
}
//===--- Bit --------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A one-bit fixed width integer.
struct Bit : FixedWidthInteger, UnsignedInteger {
typealias Magnitude = Bit
var value: UInt8 = 0
// Initializers
init(integerLiteral value: Int) {
self = Bit(value)
}
init(bigEndian value: Bit) {
self = value
}
init(littleEndian value: Bit) {
self = value
}
init?<T: BinaryFloatingPoint>(exactly source: T) {
switch source {
case T(0): value = 0
case T(1): value = 1
default:
return nil
}
}
init<T: BinaryFloatingPoint>(_ source: T) {
self = Bit(exactly: source.rounded(.down))!
}
init<T: BinaryInteger>(_ source: T) {
switch source {
case 0: value = 0
case 1: value = 1
default:
fatalError("Can't represent \(source) as a Bit")
}
}
init<T: BinaryInteger>(truncatingIfNeeded source: T) {
value = UInt8(source & 1)
}
init(_truncatingBits bits: UInt) {
value = UInt8(bits & 1)
}
init<T: BinaryInteger>(clamping source: T) {
value = source >= 1 ? 1 : 0
}
// FixedWidthInteger, BinaryInteger
static var bitWidth: Int {
return 1
}
var bitWidth: Int {
return 1
}
var trailingZeroBitCount: Int {
return Int(~value & 1)
}
static var max: Bit {
return 1
}
static var min: Bit {
return 0
}
static var isSigned: Bool {
return false
}
var nonzeroBitCount: Int {
return value.nonzeroBitCount
}
var leadingZeroBitCount: Int {
return Int(~value & 1)
}
var bigEndian: Bit {
return self
}
var littleEndian: Bit {
return self
}
var byteSwapped: Bit {
return self
}
var words: UInt.Words {
return UInt(value).words
}
// Hashable, CustomStringConvertible
var hashValue: Int {
return Int(value)
}
var description: String {
return "\(value)"
}
// Arithmetic Operations / Operators
func _checkOverflow(_ v: UInt8) -> Bool {
let mask: UInt8 = ~0 << 1
return v & mask != 0
}
func addingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &+ rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func subtractingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &- rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func multipliedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &* rhs.value
return (Bit(result), false)
}
func dividedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
return (self, rhs != 0)
}
func remainderReportingOverflow(dividingBy rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
fatalError()
}
static func +=(lhs: inout Bit, rhs: Bit) {
let result = lhs.addingReportingOverflow(rhs)
assert(!result.overflow, "Addition overflow")
lhs = result.partialValue
}
static func -=(lhs: inout Bit, rhs: Bit) {
let result = lhs.subtractingReportingOverflow(rhs)
assert(!result.overflow, "Subtraction overflow")
lhs = result.partialValue
}
static func *=(lhs: inout Bit, rhs: Bit) {
let result = lhs.multipliedReportingOverflow(by: rhs)
assert(!result.overflow, "Multiplication overflow")
lhs = result.partialValue
}
static func /=(lhs: inout Bit, rhs: Bit) {
let result = lhs.dividedReportingOverflow(by: rhs)
assert(!result.overflow, "Division overflow")
lhs = result.partialValue
}
static func %=(lhs: inout Bit, rhs: Bit) {
assert(rhs != 0, "Modulo sum overflow")
lhs.value = 0 // No remainders with bit division!
}
func multipliedFullWidth(by other: Bit) -> (high: Bit, low: Bit) {
return (0, self * other)
}
func dividingFullWidth(_ dividend: (high: Bit, low: Bit)) ->
(quotient: Bit, remainder: Bit) {
assert(self != 0, "Division overflow")
assert(dividend.high == 0, "Quotient overflow")
return (dividend.low, 0)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs %= rhs
return lhs
}
// Bitwise operators
static prefix func ~(x: Bit) -> Bit {
return Bit(~x.value & 1)
}
// Why doesn't the type checker complain about these being missing?
static func &=(lhs: inout Bit, rhs: Bit) {
lhs.value &= rhs.value
}
static func |=(lhs: inout Bit, rhs: Bit) {
lhs.value |= rhs.value
}
static func ^=(lhs: inout Bit, rhs: Bit) {
lhs.value ^= rhs.value
}
static func ==(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value == rhs.value
}
static func <(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value < rhs.value
}
static func <<(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func >>(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func <<=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
static func >>=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
}
//===--- Tests ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
typealias BigInt = _BigInt<UInt>
typealias BigInt8 = _BigInt<UInt8>
typealias BigIntBit = _BigInt<Bit>
func testBinaryInit<T: BinaryInteger>(_ x: T) -> BigInt {
return BigInt(x)
}
func randomBitLength() -> Int {
return Int(arc4random_uniform(1000) + 2)
}
var BitTests = TestSuite("Bit")
BitTests.test("Basics") {
let x = Bit.max
let y = Bit.min
expectTrue(x == 1 as Int)
expectTrue(y == 0 as Int)
expectTrue(x < Int.max)
expectGT(x, y)
expectEqual(x, x)
expectEqual(x, x ^ 0)
expectGT(x, x & 0)
expectEqual(x, x | 0)
expectLT(y, y | 1)
expectEqual(x, ~y)
expectEqual(y, ~x)
expectEqual(x, x + y)
expectGT(x, x &+ x)
expectEqual(1, x.nonzeroBitCount)
expectEqual(0, y.nonzeroBitCount)
expectEqual(0, x.leadingZeroBitCount)
expectEqual(1, y.leadingZeroBitCount)
expectEqual(0, x.trailingZeroBitCount)
expectEqual(1, y.trailingZeroBitCount)
}
var BigIntTests = TestSuite("BigInt")
BigIntTests.test("Initialization") {
let x = testBinaryInit(1_000_000 as Int)
expectEqual(x._data[0], 1_000_000)
let y = testBinaryInit(1_000 as UInt16)
expectEqual(y._data[0], 1_000)
let z = testBinaryInit(-1_000_000 as Int)
expectEqual(z._data[0], 1_000_000)
expectTrue(z.isNegative)
let z6 = testBinaryInit(z * z * z * z * z * z)
expectEqual(z6._data, [12919594847110692864, 54210108624275221])
expectFalse(z6.isNegative)
}
BigIntTests.test("Identity/Fixed point") {
let x = BigInt(repeatElement(UInt.max, count: 20))
let y = -x
expectEqual(x / x, 1)
expectEqual(x / y, -1)
expectEqual(y / x, -1)
expectEqual(y / y, 1)
expectEqual(x % x, 0)
expectEqual(x % y, 0)
expectEqual(y % x, 0)
expectEqual(y % y, 0)
expectEqual(x * 1, x)
expectEqual(y * 1, y)
expectEqual(x * -1, y)
expectEqual(y * -1, x)
expectEqual(-x, y)
expectEqual(-y, x)
expectEqual(x + 0, x)
expectEqual(y + 0, y)
expectEqual(x - 0, x)
expectEqual(y - 0, y)
expectEqual(x - x, 0)
expectEqual(y - y, 0)
}
BigIntTests.test("Max arithmetic") {
let x = BigInt(repeatElement(UInt.max, count: 50))
let y = BigInt(repeatElement(UInt.max, count: 35))
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
BigIntTests.test("Zero arithmetic") {
let zero: BigInt = 0
expectTrue(zero.isZero)
expectFalse(zero.isNegative)
let x: BigInt = 1
expectTrue((x - x).isZero)
expectFalse((x - x).isNegative)
let y: BigInt = -1
expectTrue(y.isNegative)
expectTrue((y - y).isZero)
expectFalse((y - y).isNegative)
expectEqual(x * zero, zero)
expectCrashLater()
_ = x / zero
}
BigIntTests.test("Conformances") {
// Comparable
let x = BigInt(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntTests.test("BinaryInteger interop") {
let x: BigInt = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
// should be: expectTrue(y < yComp + 1), but:
// warning: '+' is deprecated: Mixed-type addition is deprecated.
// Please use explicit type conversion.
let zComp = Int.min + 1
let z = BigInt(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
// should be:
// expectTrue(wComp - 1 < w)
// expectTrue(w > wComp - 1)
// but crashes at runtime
}
BigIntTests.test("Huge") {
let x = BigInt(randomBits: 1_000_000)
expectGT(x, x - 1)
let y = -x
expectGT(y, y - 1)
}
BigIntTests.test("Numeric").forEach(in: [
("3GFWFN54YXNBS6K2ST8K9B89Q2AMRWCNYP4JAS5ZOPPZ1WU09MXXTIT27ZPVEG2Y",
"9Y1QXS4XYYDSBMU4N3LW7R3R1WKK",
"CIFJIVHV0K4MSX44QEX2US0MFFEAWJVQ8PJZ",
"26HILZ7GZQN8MB4O17NSPO5XN1JI"),
("7PM82EHP7ZN3ZL7KOPB7B8KYDD1R7EEOYWB6M4SEION47EMS6SMBEA0FNR6U9VAM70HPY4WKXBM8DCF1QOR1LE38NJAVOPOZEBLIU1M05",
"-202WEEIRRLRA9FULGA15RYROVW69ZPDHW0FMYSURBNWB93RNMSLRMIFUPDLP5YOO307XUNEFLU49FV12MI22MLCVZ5JH",
"-3UNIZHA6PAL30Y",
"1Y13W1HYB0QV2Z5RDV9Z7QXEGPLZ6SAA2906T3UKA46E6M4S6O9RMUF5ETYBR2QT15FJZP87JE0W06FA17RYOCZ3AYM3"),
("-ICT39SS0ONER9Z7EAPVXS3BNZDD6WJA791CV5LT8I4POLF6QYXBQGUQG0LVGPVLT0L5Z53BX6WVHWLCI5J9CHCROCKH3B381CCLZ4XAALLMD",
"6T1XIVCPIPXODRK8312KVMCDPBMC7J4K0RWB7PM2V4VMBMODQ8STMYSLIXFN9ORRXCTERWS5U4BLUNA4H6NG8O01IM510NJ5STE",
"-2P2RVZ11QF",
"-3YSI67CCOD8OI1HFF7VF5AWEQ34WK6B8AAFV95U7C04GBXN0R6W5GM5OGOO22HY0KADIUBXSY13435TW4VLHCKLM76VS51W5Z9J"),
("-326JY57SJVC",
"-8H98AQ1OY7CGAOOSG",
"0",
"-326JY57SJVC"),
("-XIYY0P3X9JIDF20ZQG2CN5D2Q5CD9WFDDXRLFZRDKZ8V4TSLE2EHRA31XL3YOHPYLE0I0ZAV2V9RF8AGPCYPVWEIYWWWZ3HVDR64M08VZTBL85PR66Z2F0W5AIDPXIAVLS9VVNLNA6I0PKM87YW4T98P0K",
"-BUBZEC4NTOSCO0XHCTETN4ROPSXIJBTEFYMZ7O4Q1REOZO2SFU62KM3L8D45Z2K4NN3EC4BSRNEE",
"2TX1KWYGAW9LAXUYRXZQENY5P3DSVXJJXK4Y9DWGNZHOWCL5QD5PLLZCE6D0G7VBNP9YGFC0Z9XIPCB",
"-3LNPZ9JK5PUXRZ2Y1EJ4E3QRMAMPKZNI90ZFOBQJM5GZUJ84VMF8EILRGCHZGXJX4AXZF0Z00YA"),
("AZZBGH7AH3S7TVRHDJPJ2DR81H4FY5VJW2JH7O4U7CH0GG2DSDDOSTD06S4UM0HP1HAQ68B2LKKWD73UU0FV5M0H0D0NSXUJI7C2HW3P51H1JM5BHGXK98NNNSHMUB0674VKJ57GVVGY4",
"1LYN8LRN3PY24V0YNHGCW47WUWPLKAE4685LP0J74NZYAIMIBZTAF71",
"6TXVE5E9DXTPTHLEAG7HGFTT0B3XIXVM8IGVRONGSSH1UC0HUASRTZX8TVM2VOK9N9NATPWG09G7MDL6CE9LBKN",
"WY37RSPBTEPQUA23AXB3B5AJRIUL76N3LXLP3KQWKFFSR7PR4E1JWH"),
("1000000000000000000000000000000000000000000000",
"1000000000000000000000000000000000000",
"1000000000",
"0"),
])
{ strings in
let x = BigInt(strings.0, radix: 36)!
let y = BigInt(strings.1, radix: 36)!
let q = BigInt(strings.2, radix: 36)!
let r = BigInt(strings.3, radix: 36)!
let (testQ, testR) = x.quotientAndRemainder(dividingBy: y)
expectEqual(testQ, q)
expectEqual(testR, r)
expectEqual(x, y * q + r)
}
BigIntTests.test("Strings") {
let x = BigInt("-3UNIZHA6PAL30Y", radix: 36)!
expectEqual(x.binaryString, "-1000111001110110011101001110000001011001110110011011110011000010010010")
expectEqual(x.decimalString, "-656993338084259999890")
expectEqual(x.hexString, "-239D9D3816766F3092")
expectEqual(x.compactString, "-3UNIZHA6PAL30Y")
expectTrue(BigInt("12345") == 12345)
expectTrue(BigInt("-12345") == -12345)
expectTrue(BigInt("-3UNIZHA6PAL30Y", radix: 10) == nil)
expectTrue(BigInt("---") == nil)
expectTrue(BigInt(" 123") == nil)
}
BigIntTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
var BigInt8Tests = TestSuite("BigInt<UInt8>")
BigInt8Tests.test("BinaryInteger interop") {
let x: BigInt8 = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt8 = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
let zComp = Int.min + 1
let z = BigInt8(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt8(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
}
BigInt8Tests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigInt8Tests.test("Bitshift") {
expectEqual(BigInt8(255) << 1, 510)
expectTrue(BigInt(UInt32.max) << 16 == UInt(UInt32.max) << 16)
var (x, y) = (1 as BigInt, 1 as UInt)
for i in 0..<64 { // don't test 64-bit shift, UInt64 << 64 == 0
expectTrue(x << i == y << i)
}
(x, y) = (BigInt(UInt.max), UInt.max)
for i in 0...64 { // test 64-bit shift, should both be zero
expectTrue(x >> i == y >> i,
"\(x) as \(type(of:x)) >> \(i) => \(x >> i) != \(y) as \(type(of:y)) >> \(i) => \(y >> i)")
}
x = BigInt(-1)
let z = -1 as Int
for i in 0..<64 {
expectTrue(x << i == z << i)
}
}
BigInt8Tests.test("Bitwise").forEach(in: [
BigInt8(Int.max - 2),
BigInt8(255),
BigInt8(256),
BigInt8(UInt32.max),
])
{ value in
for x in [value, -value] {
expectTrue(x | 0 == x)
expectTrue(x & 0 == 0)
expectTrue(x & ~0 == x)
expectTrue(x ^ 0 == x)
expectTrue(x ^ ~0 == ~x)
expectTrue(x == BigInt8(Int(truncatingIfNeeded: x)))
expectTrue(~x == BigInt8(~Int(truncatingIfNeeded: x)))
}
}
var BigIntBitTests = TestSuite("BigInt<Bit>")
BigIntBitTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigIntBitTests.test("Conformances") {
// Comparable
let x = BigIntBit(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntBitTests.test("words") {
expectEqualSequence([1], (1 as BigIntBit).words)
expectEqualSequence([UInt.max, 0], BigIntBit(UInt.max).words)
expectEqualSequence([UInt.max >> 1], BigIntBit(UInt.max >> 1).words)
expectEqualSequence([0, 1], (BigIntBit(UInt.max) + 1).words)
expectEqualSequence([UInt.max], (-1 as BigIntBit).words)
}
runAllTests()
BigIntTests.test("isMultiple") {
// Test that these do not crash.
expectTrue((0 as _BigInt<UInt>).isMultiple(of: 0))
expectFalse((1 as _BigInt<UInt>).isMultiple(of: 0))
}
| 24daed84bf14ceef9c6cca05649c964f | 28.2208 | 161 | 0.607549 | false | false | false | false |
wess/reddift | refs/heads/master | reddift/Extension/NSMutableURLRequest+reddift.swift | mit | 1 | //
// NSMutableURLRequest+reddift.swift
// reddift
//
// Created by sonson on 2015/04/13.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
func parameterString(dictionary:[String:String])-> String {
var buf = ""
for (key, value) in dictionary {
buf += "\(key)=\(value)&"
}
if count(buf) > 0 {
var range = Range<String.Index>(start: advance(buf.endIndex, -1), end: buf.endIndex)
buf.removeRange(range)
}
return buf
}
extension NSMutableURLRequest {
func setRedditBasicAuthentication() {
var basicAuthenticationChallenge = Config.sharedInstance.clientID + ":"
let data = basicAuthenticationChallenge.dataUsingEncoding(NSUTF8StringEncoding)!
let base64Str = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
setValue("Basic " + base64Str, forHTTPHeaderField:"Authorization")
}
func setRedditBasicAuthentication(#username:String, password:String) {
var basicAuthenticationChallenge = username + ":" + password
let data = basicAuthenticationChallenge.dataUsingEncoding(NSUTF8StringEncoding)!
let base64Str = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
setValue("Basic " + base64Str, forHTTPHeaderField:"Authorization")
}
func setOAuth2Token(token:Token) {
setValue("bearer " + token.accessToken, forHTTPHeaderField:"Authorization")
}
func setUserAgentForReddit() {
self.setValue(Config.sharedInstance.userAgent, forHTTPHeaderField: "User-Agent")
}
class func mutableOAuthRequestWithBaseURL(baseURL:String, path:String, method:String, token:Token) -> NSMutableURLRequest {
let URL = NSURL(string:baseURL + path)!
var URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.setOAuth2Token(token)
URLRequest.HTTPMethod = method
URLRequest.setUserAgentForReddit()
return URLRequest
}
class func mutableOAuthRequestWithBaseURL(baseURL:String, path:String, parameter:[String:String]?, method:String, token:Token) -> NSMutableURLRequest {
var params:[String:String] = [:]
if let parameter = parameter {
params = parameter
}
if method == "POST" {
return self.mutableOAuthPostRequestWithBaseURL(baseURL, path:path, parameter:params, method:method, token:token)
}
else {
return self.mutableOAuthGetRequestWithBaseURL(baseURL, path:path, parameter:params, method:method, token:token)
}
}
class func mutableOAuthGetRequestWithBaseURL(baseURL:String, path:String, parameter:[String:String], method:String, token:Token) -> NSMutableURLRequest {
var param = parameterString(parameter)
let URL = isEmpty(param) ? NSURL(string:baseURL + path)! : NSURL(string:baseURL + path + "?" + param)!
var URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.setOAuth2Token(token)
URLRequest.HTTPMethod = method
URLRequest.setUserAgentForReddit()
return URLRequest
}
class func mutableOAuthPostRequestWithBaseURL(baseURL:String, path:String, parameter:[String:String], method:String, token:Token) -> NSMutableURLRequest {
let URL = NSURL(string:baseURL + path)!
var URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.setOAuth2Token(token)
URLRequest.HTTPMethod = method
let data = parameterString(parameter).dataUsingEncoding(NSUTF8StringEncoding)
URLRequest.HTTPBody = data
URLRequest.setUserAgentForReddit()
return URLRequest
}
} | 2e89d6940c87f19426080e54bd201064 | 40.897727 | 158 | 0.699946 | false | false | false | false |
ArchimboldiMao/remotex-iOS | refs/heads/master | remotex-iOS/Model/CategoryModel.swift | apache-2.0 | 2 | //
// CategoryModel.swift
// remotex-iOS
//
// Created by archimboldi on 10/05/2017.
// Copyright © 2017 me.archimboldi. All rights reserved.
//
import UIKit
struct CategoryModel {
let categoryID: Int
let categoryName: String
let summaryText: String
init?(dictionary: JSONDictionary) {
guard let categoryID = dictionary["id"] as? Int, let categoryName = dictionary["name"] as? String, let summaryText = dictionary["summary"] as? String else {
print("error parsing JSON within CategoryModel Init")
return nil
}
self.categoryID = categoryID
self.categoryName = categoryName
self.summaryText = summaryText
}
}
extension CategoryModel {
func attrStringForCategoryName(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: Constants.CellLayout.TagForegroundColor,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
return NSAttributedString.init(string: categoryName, attributes: attr)
}
func attrStringForSummaryText(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: Constants.CellLayout.TitleForegroundColor,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
return NSAttributedString.init(string: summaryText, attributes: attr)
}
}
| 11f4154842edffe22f3c980a97dddecd | 31.613636 | 164 | 0.678746 | false | false | false | false |
aronse/Hero | refs/heads/master | Examples/Examples/ImageGallery/ImageGalleryCollectionViewController.swift | mit | 2 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Hero
class ImageGalleryViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var columns = 3
lazy var cellSize: CGSize = CGSize(width: self.view.bounds.width/CGFloat(self.columns),
height: self.view.bounds.width/CGFloat(self.columns))
override func viewDidLoad() {
super.viewDidLoad()
collectionView.reloadData()
collectionView.indicatorStyle = .white
}
@IBAction func switchLayout(_ sender: Any) {
// just replace the root view controller with the same view controller
// animation is automatic! Holy
let next = (UIStoryboard(name: "ImageGallery", bundle: nil).instantiateViewController(withIdentifier: "imageGallery") as? ImageGalleryViewController)!
next.columns = columns == 3 ? 5 : 3
hero_replaceViewController(with: next)
}
}
extension ImageGalleryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = (viewController(forStoryboardName: "ImageViewer") as? ImageViewController)!
vc.selectedIndex = indexPath
if let navigationController = navigationController {
navigationController.pushViewController(vc, animated: true)
} else {
present(vc, animated: true, completion: nil)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImageLibrary.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let imageCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as? ImageCell)!
imageCell.imageView.image = ImageLibrary.thumbnail(index:indexPath.item)
imageCell.imageView.heroID = "image_\(indexPath.item)"
imageCell.imageView.heroModifiers = [.fade, .scale(0.8)]
imageCell.imageView.isOpaque = true
return imageCell
}
}
extension ImageGalleryViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
}
extension ImageGalleryViewController: HeroViewControllerDelegate {
func heroWillStartAnimatingTo(viewController: UIViewController) {
if (viewController as? ImageGalleryViewController) != nil {
collectionView.heroModifiers = [.cascade(delta:0.015, direction:.bottomToTop, delayMatchedViews:true)]
} else if (viewController as? ImageViewController) != nil {
let cell = collectionView.cellForItem(at: collectionView.indexPathsForSelectedItems!.first!)!
collectionView.heroModifiers = [.cascade(delta: 0.015, direction: .radial(center: cell.center), delayMatchedViews: true)]
} else {
collectionView.heroModifiers = [.cascade(delta:0.015)]
}
}
func heroWillStartAnimatingFrom(viewController: UIViewController) {
view.heroModifiers = nil
if (viewController as? ImageGalleryViewController) != nil {
collectionView.heroModifiers = [.cascade(delta:0.015), .delay(0.25)]
} else {
collectionView.heroModifiers = [.cascade(delta:0.015)]
}
if let vc = viewController as? ImageViewController,
let originalCellIndex = vc.selectedIndex,
let currentCellIndex = vc.collectionView?.indexPathsForVisibleItems[0],
let targetAttribute = collectionView.layoutAttributesForItem(at: currentCellIndex) {
collectionView.heroModifiers = [.cascade(delta:0.015, direction:.inverseRadial(center:targetAttribute.center))]
if !collectionView.indexPathsForVisibleItems.contains(currentCellIndex) {
// make the cell visible
collectionView.scrollToItem(at: currentCellIndex,
at: originalCellIndex < currentCellIndex ? .bottom : .top,
animated: false)
}
}
}
}
| a25a165cd83cc2b4be004feee56adfb3 | 46.422018 | 158 | 0.739215 | false | false | false | false |
hmx101607/mhweibo | refs/heads/master | weibo/weibo/App/viewcontrollers/main/WBWelcomeViewController.swift | mit | 1 | //
// WBWelcomeViewController.swift
// weibo
//
// Created by mason on 2017/8/18.
// Copyright © 2017年 mason. All rights reserved.
//
import UIKit
import SDWebImage
class WBWelcomeViewController: UIViewController {
@IBOutlet weak var headerBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var headerImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
headerImageView.layer.cornerRadius = headerImageView.frame.size.width / 2.0
headerImageView.layer.masksToBounds = true
let urlStr = WBAccountViewModel.shareIntance.account?.avatar_large
let url = NSURL(string: urlStr ?? "")
headerImageView.setImageWith(url! as URL)
headerBottomConstraint.constant = UIScreen.main.bounds.size.height - 200.0
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: [], animations: {
self.view.layoutIfNeeded()
}) { (_) in
UIApplication.shared.keyWindow?.rootViewController = WBTabbarViewController()
}
}
}
| f464824cee19ffa3456b8b73f4c18285 | 27.925 | 133 | 0.659464 | false | false | false | false |
hagmas/APNsKit | refs/heads/master | APNsKit/APNsPayload.swift | mit | 1 | import Foundation
public struct APNsPayload {
let title: String?
let body: String
let titleLocKey: String?
let titleLocArgs: [String]?
let actionLocKey: String?
let locKey: String?
let locArgs: [String]?
let launchImage: String?
let badge: Int?
let sound: String?
let contentAvailable: Int?
let mutableContent: Int?
let category: String?
let threadId: String?
let custom: [String: Any]?
public init(
title: String? = nil,
body: String,
titleLocKey: String? = nil,
titleLocArgs: [String]? = nil,
actionLocKey: String? = nil,
locKey: String? = nil,
locArgs: [String]? = nil,
launchImage: String? = nil,
badge: Int? = nil,
sound: String? = nil,
contentAvailable: Int? = nil,
mutableContent: Int? = nil,
category: String? = nil,
threadId: String? = nil,
custom: [String: Any]? = nil) {
self.title = title
self.body = body
self.titleLocKey = titleLocKey
self.titleLocArgs = titleLocArgs
self.actionLocKey = actionLocKey
self.locKey = locKey
self.locArgs = locArgs
self.launchImage = launchImage
self.badge = badge
self.sound = sound
self.contentAvailable = contentAvailable
self.mutableContent = mutableContent
self.category = category
self.threadId = threadId
self.custom = custom
}
public var dictionary: [String: Any] {
// Alert
var alert: [String: Any] = ["body": body]
if let title = title {
alert["title"] = title
}
if let titleLocKey = titleLocKey {
alert["title-loc-key"] = titleLocKey
}
if let titleLocArgs = titleLocArgs {
alert["title-loc-args"] = titleLocArgs
}
if let actionLocKey = actionLocKey {
alert["action-loc-key"] = actionLocKey
}
if let locKey = locKey {
alert["loc-key"] = locKey
}
if let locArgs = locArgs {
alert["loc-args"] = locArgs
}
if let launchImage = launchImage {
alert["launch-image"] = launchImage
}
// APS
var dictionary: [String: Any] = ["alert": alert]
if let badge = badge {
dictionary["badge"] = badge
}
if let sound = sound {
dictionary["sound"] = sound
}
if let contentAvailable = contentAvailable {
dictionary["content-available"] = contentAvailable
}
if let mutableContent = mutableContent {
dictionary["mutable-content"] = mutableContent
}
if let category = category {
dictionary["category"] = category
}
if let threadId = threadId {
dictionary["thread-id"] = threadId
}
var payload: [String: Any] = ["aps": dictionary]
// Custom
custom?.forEach {
payload[$0] = $1
}
return payload
}
public static func convert(parameters: Any) -> String {
if let dictionary = parameters as? [String: Any] {
return "{" + dictionary.map { "\"\($0.key)\":" + convert(parameters: $0.value) }.joined(separator: ",") + "}"
} else if let array = parameters as? [String] {
return "[" + array.joined(separator: ",") + "]"
} else if let int = parameters as? Int {
return "\(int)"
} else {
return "\"\(parameters)\""
}
}
public var data: Data? {
return APNsPayload.convert(parameters: dictionary).data(using: .unicode)
}
}
| 3d986945f92b6db18464176774c0695d | 26.496503 | 121 | 0.513733 | false | false | false | false |
inoity/nariko | refs/heads/master | Nariko/Classes/Views/OnboardingSecond.swift | mit | 1 | //
// OnboardingSecond.swift
// Pods
//
// Created by Zsolt Papp on 2016. 10. 17..
//
//
import UIKit
class OnboardingSecond: DynamicSizeView {
@IBOutlet weak var bgView: UIView!
override class var nibName: String {
get {
return "OnboardingSecond"
}
}
var on = false
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
let gradientLayer = CAGradientLayer()
gradientLayer.frame.size = self.layer.frame.size
gradientLayer.colors = [UIColor.gradTop.cgColor, UIColor.gradBottom.cgColor]
gradientLayer.locations = [0.0, 1.0]
bgView.layer.addSublayer(gradientLayer)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 366732c54c74ed4107ef616aee99802d | 20.956522 | 84 | 0.607921 | false | false | false | false |
Derek316x/iOS8-day-by-day | refs/heads/master | 08-today-extension/GitHubToday/GitHubTodayCommon/GitHubDataProvider.swift | apache-2.0 | 21 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@objc public class GitHubEvent: NSObject, Printable, Equatable, NSCoding {
public var id: Int
public var eventType: GitHubEventType
public var repoName: String?
public var time: NSDate?
private class var dateFormatter : NSDateFormatter {
struct Static {
static let instance : NSDateFormatter = NSDateFormatter()
}
return Static.instance
}
public init(id: Int, eventType: GitHubEventType, repoName: String?, time: NSDate?) {
self.id = id
self.eventType = eventType
self.repoName = repoName
self.time = time
}
// NSCoding
public required init(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeIntegerForKey("id")
self.eventType = GitHubEventType(rawValue: aDecoder.decodeObjectForKey("eventType") as! String)!
self.repoName = aDecoder.decodeObjectForKey("repoName") as? String
self.time = aDecoder.decodeObjectForKey("time") as? NSDate
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(id, forKey: "id")
aCoder.encodeObject(eventType.rawValue, forKey: "eventType")
aCoder.encodeObject(repoName!, forKey: "repoName")
aCoder.encodeObject(time!, forKey: "time")
}
public convenience init(json: JSON) {
let data = GitHubEvent.extractDataFromJson(json)
self.init(id: data.id, eventType: data.eventType, repoName: data.repoName, time: data.time)
}
public class func extractDataFromJson(jsonEvent: JSON) -> (id: Int, eventType: GitHubEventType, repoName: String?, time: NSDate?) {
let id = jsonEvent["id"].string!.toInt()!
var repoName = jsonEvent["repo"]["name"].string
var eventType: GitHubEventType = .Other
if let eventString = jsonEvent["type"].string {
switch eventString {
case "CreateEvent":
eventType = .Create
case "DeleteEvent":
eventType = .Delete
case "ForkEvent":
eventType = .Fork
case "PushEvent":
eventType = .Push
case "WatchEvent":
eventType = .Watch
case "FollowEvent":
eventType = .Follow
case "IssuesEvent":
eventType = .Issues
case "IssueCommentEvent":
eventType = .IssueComment
default:
eventType = .Other
}
}
var date: NSDate?
if let createdString = jsonEvent["created_at"].string {
GitHubEvent.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
date = GitHubEvent.dateFormatter.dateFromString(createdString)
}
return (id, eventType, repoName, date)
}
// Printable
override public var description: String {
return "[\(id)] \(time) : \(eventType.rawValue)) \(repoName)"
}
}
// Equatable
public func ==(lhs: GitHubEvent, rhs: GitHubEvent) -> Bool {
return lhs.id == rhs.id
}
public enum GitHubEventType: String {
case Create = "create"
case Delete = "delete"
case Fork = "fork"
case Push = "push"
case Watch = "watch"
case Follow = "follow"
case Issues = "issues"
case IssueComment = "comment"
case Other = "other"
public var icon: String {
switch self {
case .Create:
return ""
case .Delete:
return ""
case .Follow:
return ""
case .Fork:
return ""
case .IssueComment:
return ""
case .Issues:
return ""
case .Other:
return ""
case .Push:
return ""
case .Watch:
return ""
default:
return ""
}
}
}
public class GitHubDataProvider {
public init() { }
public func getEvents(user: String, callback: ([GitHubEvent])->()) {
let url = NSURL(string: "https://api.github.com/users/\(user)/events")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
(data, response, error) in
if (error != nil) {
println("Error: \(error.localizedDescription)")
return
}
let json = JSON(data: data, options: .allZeros, error: nil)
let events = self.convertJSONToEvents(json)
callback(events)
})
task.resume()
}
private func convertJSONToEvents(data: JSON) -> [GitHubEvent] {
let json = data.array
var ghEvents = [GitHubEvent]()
if let events = json {
for event in events {
let ghEvent = GitHubEvent(json: event)
ghEvents.append(ghEvent)
}
}
return ghEvents
}
}
let mostRecentEventCacheKey = "GitHubToday.mostRecentEvent"
public class GitHubEventCache {
private var userDefaults: NSUserDefaults
public init(userDefaults: NSUserDefaults) {
self.userDefaults = userDefaults
}
public var mostRecentEvent: GitHubEvent? {
get {
if let data = userDefaults.objectForKey(mostRecentEventCacheKey) as? NSData {
if let event = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? GitHubEvent {
return event
}
}
return nil
}
set(newEvent) {
if let event = newEvent {
let data = NSKeyedArchiver.archivedDataWithRootObject(event)
userDefaults.setObject(data, forKey: mostRecentEventCacheKey)
} else {
userDefaults.removeObjectForKey(mostRecentEventCacheKey)
}
}
}
} | 526003e9cfd877748022cb1fdf824a3b | 26.421053 | 133 | 0.65637 | false | false | false | false |
El-Fitz/ImageSlideshow | refs/heads/master | Pod/Classes/Core/ImageSlideshow.swift | mit | 1 | //
// ImageSlideshow.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import UIKit
public enum PageControlPosition {
case hidden
case insideScrollView
case underScrollView
case custom(padding: CGFloat)
var bottomPadding: CGFloat {
switch self {
case .hidden, .insideScrollView:
return 0.0
case .underScrollView:
return 30.0
case .custom(let padding):
return padding
}
}
}
public enum ImagePreload {
case fixed(offset: Int)
case all
}
open class ImageSlideshow: UIView {
open let scrollView = UIScrollView()
open let pageControl = UIPageControl()
// MARK: - State properties
/// Page control position
open var pageControlPosition = PageControlPosition.insideScrollView {
didSet {
setNeedsLayout()
layoutScrollView()
}
}
/// Current page
open fileprivate(set) var currentPage: Int = 0 {
didSet {
pageControl.currentPage = currentPage
if oldValue != currentPage {
currentPageChanged?(currentPage)
loadImages(for: currentPage)
}
}
}
/// Called on each currentPage change
open var currentPageChanged: ((_ page: Int) -> ())?
/// Called on scrollViewWillBeginDragging
open var willBeginDragging: (() -> ())?
/// Called on scrollViewDidEndDecelerating
open var didEndDecelerating: (() -> ())?
/// Currenlty displayed slideshow item
open var currentSlideshowItem: ImageSlideshowItem? {
if slideshowItems.count > scrollViewPage {
return slideshowItems[scrollViewPage]
} else {
return nil
}
}
open fileprivate(set) var scrollViewPage: Int = 0
open fileprivate(set) var images = [InputSource]()
open fileprivate(set) var slideshowItems = [ImageSlideshowItem]()
// MARK: - Preferences
/// Enables/disables infinite scrolling between images
open var circular = true
/// Enables/disables user interactions
open var draggingEnabled = true {
didSet {
self.scrollView.isUserInteractionEnabled = draggingEnabled
}
}
/// Enables/disables zoom
open var zoomEnabled = false
/// Image change interval, zero stops the auto-scrolling
open var slideshowInterval = 0.0 {
didSet {
self.slideshowTimer?.invalidate()
self.slideshowTimer = nil
setTimerIfNeeded()
}
}
/// Image preload configuration, can be sed to .fixed to enable lazy load or .all
open var preload = ImagePreload.all
/// Content mode of each image in the slideshow
open var contentScaleMode: UIViewContentMode = UIViewContentMode.scaleAspectFit {
didSet {
for view in slideshowItems {
view.imageView.contentMode = contentScaleMode
}
}
}
fileprivate var slideshowTimer: Timer?
fileprivate var scrollViewImages = [InputSource]()
open fileprivate(set) var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate?
// MARK: - Life cycle
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
autoresizesSubviews = true
clipsToBounds = true
// scroll view configuration
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - 50.0)
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.bounces = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.autoresizingMask = self.autoresizingMask
addSubview(scrollView)
addSubview(pageControl)
setTimerIfNeeded()
layoutScrollView()
}
override open func layoutSubviews() {
super.layoutSubviews()
// fixes the case when automaticallyAdjustsScrollViewInsets on parenting view controller is set to true
scrollView.contentInset = UIEdgeInsets.zero
if case .hidden = self.pageControlPosition {
pageControl.isHidden = true
} else {
pageControl.isHidden = false
}
pageControl.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: 10)
pageControl.center = CGPoint(x: frame.size.width / 2, y: frame.size.height - 12.0)
layoutScrollView()
}
/// updates frame of the scroll view and its inner items
func layoutScrollView() {
let scrollViewBottomPadding: CGFloat = pageControlPosition.bottomPadding
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - scrollViewBottomPadding)
scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(scrollViewImages.count), height: scrollView.frame.size.height)
for (index, view) in self.slideshowItems.enumerated() {
if !view.zoomInInitially {
view.zoomOut()
}
view.frame = CGRect(x: scrollView.frame.size.width * CGFloat(index), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
}
setCurrentPage(currentPage, animated: false)
}
/// reloads scroll view with latest slideshow items
func reloadScrollView() {
// remove previous slideshow items
for view in self.slideshowItems {
view.removeFromSuperview()
}
self.slideshowItems = []
var i = 0
for image in scrollViewImages {
let item = ImageSlideshowItem(image: image, zoomEnabled: self.zoomEnabled)
item.imageView.contentMode = self.contentScaleMode
slideshowItems.append(item)
scrollView.addSubview(item)
i += 1
}
if circular && (scrollViewImages.count > 1) {
scrollViewPage = 1
scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: false)
} else {
scrollViewPage = 0
}
loadImages(for: 0)
}
private func loadImages(for page: Int) {
let totalCount = slideshowItems.count
for i in 0..<totalCount {
let item = slideshowItems[i]
switch self.preload {
case .all:
item.loadImage()
case .fixed(let offset):
// load image if page is in range of loadOffset, else release image
let shouldLoad = abs(page-i) <= offset || abs(page-i) > totalCount-offset
shouldLoad ? item.loadImage() : item.releaseImage()
}
}
}
// MARK: - Image setting
open func setImageInputs(_ inputs: [InputSource]) {
self.images = inputs
self.pageControl.numberOfPages = inputs.count;
// in circular mode we add dummy first and last image to enable smooth scrolling
if circular && images.count > 1 {
var scImages = [InputSource]()
if let last = images.last {
scImages.append(last)
}
scImages += images
if let first = images.first {
scImages.append(first)
}
self.scrollViewImages = scImages
} else {
self.scrollViewImages = images;
}
reloadScrollView()
layoutScrollView()
setTimerIfNeeded()
}
// MARK: paging methods
open func setCurrentPage(_ currentPage: Int, animated: Bool) {
var pageOffset = currentPage
if circular {
pageOffset += 1
}
self.setScrollViewPage(pageOffset, animated: animated)
}
open func setScrollViewPage(_ scrollViewPage: Int, animated: Bool) {
if scrollViewPage < scrollViewImages.count {
self.scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(scrollViewPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: animated)
self.setCurrentPageForScrollViewPage(scrollViewPage)
}
}
fileprivate func setTimerIfNeeded() {
if slideshowInterval > 0 && scrollViewImages.count > 1 && slideshowTimer == nil {
slideshowTimer = Timer.scheduledTimer(timeInterval: slideshowInterval, target: self, selector: #selector(ImageSlideshow.slideshowTick(_:)), userInfo: nil, repeats: true)
}
}
func slideshowTick(_ timer: Timer) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
var nextPage = page + 1
if !circular && page == scrollViewImages.count - 1 {
nextPage = 0
}
self.scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(nextPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: true)
self.setCurrentPageForScrollViewPage(nextPage);
}
open func setCurrentPageForScrollViewPage(_ page: Int) {
if scrollViewPage != page {
// current page has changed, zoom out this image
if slideshowItems.count > scrollViewPage {
slideshowItems[scrollViewPage].zoomOut()
}
}
scrollViewPage = page
if circular {
if page == 0 {
// first page contains the last image
currentPage = Int(images.count) - 1
} else if page == scrollViewImages.count - 1 {
// last page contains the first image
currentPage = 0
} else {
currentPage = page - 1
}
} else {
currentPage = page
}
}
/// Stops slideshow timer
open func pauseTimerIfNeeded() {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
/// Restarts slideshow timer
open func unpauseTimerIfNeeded() {
setTimerIfNeeded()
}
/// Open full screen slideshow
@discardableResult
open func presentFullScreenController(from controller:UIViewController) -> FullScreenSlideshowViewController {
let fullscreen = FullScreenSlideshowViewController()
fullscreen.pageSelected = {(page: Int) in
self.setCurrentPage(page, animated: false)
}
fullscreen.initialPage = self.currentPage
fullscreen.inputs = self.images
slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: self, slideshowController: fullscreen)
fullscreen.transitioningDelegate = slideshowTransitioningDelegate
controller.present(fullscreen, animated: true, completion: nil)
return fullscreen
}
}
extension ImageSlideshow: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if slideshowTimer?.isValid != nil {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
setTimerIfNeeded()
willBeginDragging?()
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
setCurrentPageForScrollViewPage(page);
didEndDecelerating?()
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if circular {
let regularContentOffset = scrollView.frame.size.width * CGFloat(images.count)
if (scrollView.contentOffset.x >= scrollView.frame.size.width * CGFloat(images.count + 1)) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x - regularContentOffset, y: 0)
} else if (scrollView.contentOffset.x < 0) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x + regularContentOffset, y: 0)
}
}
}
}
| 33367f5b8831068a1b16f39a96375fcc | 32.177546 | 213 | 0.60565 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | refs/heads/main | WhiteBoardCodingChallenges/Challenges/HackerRank/Kaprekar/Kaprekar.swift | mit | 1 | //
// Kaprekar.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 12/05/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//https://www.hackerrank.com/challenges/kaprekar-numbers
class Kaprekar: NSObject {
class func kaprekarRange(lowerBounds: Int, upperBounds: Int) -> [Int] {
var kaprekarRange = [Int]()
for i in lowerBounds...upperBounds {
let squaredValue = i * i
let squaredString = String(squaredValue)
let leftCharacterCount = squaredString.count / 2
var leftValue = 0
if squaredString.count > 1 {
leftValue = Int(String(squaredString.prefix(leftCharacterCount)))!
}
let rightValue = Int(String(squaredString.suffix((squaredString.count - leftCharacterCount))))!
if (leftValue + rightValue) == i {
kaprekarRange.append(i)
}
}
return kaprekarRange
}
}
| 55bd83e1383d0c8829f42187b6954d14 | 25.710526 | 107 | 0.592118 | false | false | false | false |
Egibide-DAM/swift | refs/heads/master | 02_ejemplos/04_colecciones/04_diccionarios/02_operaciones_diccionarios.playground/Contents.swift | apache-2.0 | 1 | var airports: [String: String] = ["TYO": "Tokyo", "DUB": "Dublin"]
var moreAirports = ["TYO": "Tokyo", "DUB": "Dublin"]
// -----
print("The dictionary of airports contains \(airports.count) items.")
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// -----
airports["LHR"] = "London" // Añadir un elemento
airports["LHR"] = "London Heathrow" // Actualizar el elemento
airports["APL"] = "Apple International"
airports["APL"] = nil // Borrar un elemento
// -----
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// -----
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
| 92e5f393d6c124d419c52d3b3371229b | 23.790698 | 73 | 0.651032 | false | false | false | false |
rossharper/raspberrysauce-ios | refs/heads/master | raspberrysauce-ios/App/WatchSessionDelegate.swift | apache-2.0 | 1 | //
// WatchSessionDelegate.swift
// raspberrysauce-ios
//
// Created by Ross Harper on 21/12/2016.
// Copyright © 2016 rossharper.net. All rights reserved.
//
import Foundation
import WatchConnectivity
class WatchSessionDelegate : NSObject, WCSessionDelegate, AuthObserver {
let authManager = AuthManagerFactory.create()
var session: WCSession?
override init() {
super.init()
if WCSession.isSupported() {
session = WCSession.default
if session != nil {
session!.delegate = self
session!.activate()
}
}
authManager.setAuthObserver(observer: self)
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// TODO: handle session switching properly
print("iOS App Session Did activate")
if(authManager.isSignedIn()) {
sendToken(token: authManager.getAccessToken())
}
else {
sendSignedOut()
}
}
func sessionDidBecomeInactive(_ session: WCSession) {
print("iOS App Session Did become inactive")
}
func sessionDidDeactivate(_ session: WCSession) {
print("iOS App Session Did deactivate")
}
func onSignedIn() {
sendToken(token: authManager.getAccessToken())
}
func onSignedOut() {
sendSignedOut()
}
func onSignInFailed() {
}
func sendToken(token: Token?) {
print("send token...")
guard let token = authManager.getAccessToken() else { return }
guard let session = self.session else { return }
print("sending")
try? session.updateApplicationContext(["token" : token.value])
}
func sendSignedOut() {
print("send signed out")
guard let session = self.session else { return }
print("sending")
try? session.updateApplicationContext([:])
}
}
| b842ffa8dd4b11e4ae572e6de994bcb0 | 26.791667 | 124 | 0.606197 | false | false | false | false |
biohazardlover/ByTrain | refs/heads/master | ByTrain/TopStationsRequest.swift | mit | 1 |
import Alamofire
extension DataRequest {
@discardableResult
func responseStations(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[Station]>) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer<[Station]> { (request, response, data, error) -> Result<[Station]> in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let stringResponseSerializer = DataRequest.stringResponseSerializer()
let result = stringResponseSerializer.serializeResponse(request, response, data, nil)
guard case let .success(string) = result else {
return .failure(BackendError.stringSerialization(error: result.error!))
}
guard let response = response else {
return .failure(BackendError.objectSerialization(reason: "String could not be serialized: \(string)"))
}
let stations = Station.collection(from: response, withRepresentation: string)
return .success(stations)
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
@discardableResult
public func retrieveTopStations(
completionHandler: @escaping (DataResponse<[Station]>) -> Void)
-> DataRequest
{
return request("https://kyfw.12306.cn/otn/resources/js/framework/favorite_name.js", method: .get).responseStations(completionHandler: completionHandler)
}
| 98f34d5cd02f33229b156bdb2993db46 | 39.794872 | 156 | 0.654305 | false | false | false | false |
Norod/Filterpedia | refs/heads/swift-3 | Filterpedia/components/FilterNavigator.swift | gpl-3.0 | 1 | //
// FilterNavigator.swift
// Filterpedia
//
// Created by Simon Gladman on 29/12/2015.
// Copyright © 2015 Simon Gladman. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
import Foundation
import UIKit
class FilterNavigator: UIView
{
let filterCategories =
[
CategoryCustomFilters,
kCICategoryBlur,
kCICategoryColorAdjustment,
kCICategoryColorEffect,
kCICategoryCompositeOperation,
kCICategoryDistortionEffect,
kCICategoryGenerator,
kCICategoryGeometryAdjustment,
kCICategoryGradient,
kCICategoryHalftoneEffect,
kCICategoryReduction,
kCICategorySharpen,
kCICategoryStylize,
kCICategoryTileEffect,
kCICategoryTransition,
].sorted{ CIFilter.localizedName(forCategory: $0) < CIFilter.localizedName(forCategory: $1)}
/// Filterpedia doesn't support code generators, color cube filters, filters that require NSValue
let exclusions = ["CIQRCodeGenerator",
"CIPDF417BarcodeGenerator",
"CICode128BarcodeGenerator",
"CIAztecCodeGenerator",
"CIColorCubeWithColorSpace",
"CIColorCube",
"CIAffineTransform",
"CIAffineClamp",
"CIAffineTile",
"CICrop"] // to do: fix CICrop!
let segmentedControl = UISegmentedControl(items: [FilterNavigatorMode.Grouped.rawValue, FilterNavigatorMode.Flat.rawValue])
let tableView: UITableView =
{
let tableView = UITableView(frame: CGRect.zero,
style: UITableViewStyle.plain)
tableView.register(UITableViewHeaderFooterView.self,
forHeaderFooterViewReuseIdentifier: "HeaderRenderer")
tableView.register(UITableViewCell.self,
forCellReuseIdentifier: "ItemRenderer")
return tableView
}()
var mode: FilterNavigatorMode = .Grouped
{
didSet
{
tableView.reloadData()
}
}
weak var delegate: FilterNavigatorDelegate?
override init(frame: CGRect)
{
super.init(frame: frame)
CustomFiltersVendor.registerFilters()
tableView.dataSource = self
tableView.delegate = self
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self,
action: #selector(FilterNavigator.segmentedControlChange),
for: UIControlEvents.valueChanged)
addSubview(tableView)
addSubview(segmentedControl)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
func segmentedControlChange()
{
mode = segmentedControl.selectedSegmentIndex == 0 ? .Grouped : .Flat
}
override func layoutSubviews()
{
let segmentedControlHeight = segmentedControl.intrinsicContentSize.height
tableView.frame = CGRect(x: 0,
y: 0,
width: frame.width,
height: frame.height - segmentedControlHeight)
segmentedControl.frame = CGRect(x: 0,
y: frame.height - segmentedControlHeight,
width: frame.width,
height: segmentedControlHeight)
}
}
// MARK: UITableViewDelegate extension
extension FilterNavigator: UITableViewDelegate
{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let filterName: String
switch mode
{
case .Grouped:
filterName = supportedFilterNamesInCategory(filterCategories[(indexPath as NSIndexPath).section]).sorted()[(indexPath as NSIndexPath).row]
case .Flat:
filterName = supportedFilterNamesInCategories(nil).sorted
{
CIFilter.localizedName(forFilterName: $0) ?? $0 < CIFilter.localizedName(forFilterName: $1) ?? $1
}[(indexPath as NSIndexPath).row]
}
delegate?.filterNavigator(self, didSelectFilterName: filterName)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
switch mode
{
case .Grouped:
return 40
case .Flat:
return 0
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderRenderer")! as UITableViewHeaderFooterView
switch mode
{
case .Grouped:
cell.textLabel?.text = CIFilter.localizedName(forCategory: filterCategories[section])
case .Flat:
cell.textLabel?.text = nil
}
return cell
}
func supportedFilterNamesInCategory(_ category: String?) -> [String]
{
return CIFilter.filterNames(inCategory: category).filter
{
!exclusions.contains($0)
}
}
func supportedFilterNamesInCategories(_ categories: [String]?) -> [String]
{
return CIFilter.filterNames(inCategories: categories).filter
{
!exclusions.contains($0)
}
}
}
// MARK: UITableViewDataSource extension
extension FilterNavigator: UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int
{
switch mode
{
case .Grouped:
return filterCategories.count
case .Flat:
return 1
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
switch mode
{
case .Grouped:
return supportedFilterNamesInCategory(filterCategories[section]).count
case .Flat:
return supportedFilterNamesInCategories(nil).count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemRenderer",
for: indexPath)
let filterName: String
switch mode
{
case .Grouped:
filterName = supportedFilterNamesInCategory(filterCategories[(indexPath as NSIndexPath).section]).sorted()[(indexPath as NSIndexPath).row]
case .Flat:
filterName = supportedFilterNamesInCategories(nil).sorted
{
CIFilter.localizedName(forFilterName: $0) ?? $0 < CIFilter.localizedName(forFilterName: $1) ?? $1
}[(indexPath as NSIndexPath).row]
}
cell.textLabel?.text = CIFilter.localizedName(forFilterName: filterName) ?? (CIFilter(name: filterName)?.attributes[kCIAttributeFilterDisplayName] as? String) ?? filterName
return cell
}
}
// MARK: Filter Navigator Modes
enum FilterNavigatorMode: String
{
case Grouped
case Flat
}
// MARK: FilterNavigatorDelegate
protocol FilterNavigatorDelegate: class
{
func filterNavigator(_ filterNavigator: FilterNavigator, didSelectFilterName: String)
}
| a5fcd9d0ceba9b8a26472fecc6f7ca1c | 29.031128 | 180 | 0.641228 | false | false | false | false |
soffes/GradientView | refs/heads/master | Example/ViewController.swift | mit | 1 | //
// ViewController.swift
// GradientView
//
// Created by Sam Soffes on 7/19/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
import UIKit
import GradientView
final class ViewController: UIViewController {
// MARK: - Properties
let gradientView = GradientView()
// MARK: - UIViewController
override func loadView() {
view = gradientView
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Gradient View"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Dim", style: .plain, target: self, action: #selector(showAlert))
gradientView.colors = [
.white,
UIColor(red: 0, green: 0, blue: 0.5, alpha: 1)
]
// You can configure the locations as well
// gradientView.locations = [0.4, 0.6]
}
// MARK: - Actions
@objc private func showAlert() {
let alert = UIAlertController(title: "Dimming", message: "As part of iOS design language, views should become desaturated when an alert view appears.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Awesome", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| 140e5b8fd67ca385f05f27483eda4e7a | 23.270833 | 177 | 0.68412 | false | false | false | false |
AlexChekanov/Gestalt | refs/heads/master | Carthage/Checkouts/SwinjectStoryboard/Sources/SwinjectStoryboard.swift | apache-2.0 | 6 | //
// SwinjectStoryboard.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/31/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Swinject
#if os(iOS) || os(tvOS) || os(OSX)
/// The `SwinjectStoryboard` provides the features to inject dependencies of view/window controllers in a storyboard.
///
/// To specify a registration name of a view/window controller registered to the `Container` as a service type,
/// add a user defined runtime attribute with the following settings:
///
/// - Key Path: `swinjectRegistrationName`
/// - Type: String
/// - Value: Registration name to the `Container`
///
/// in User Defined Runtime Attributes section on Indentity Inspector pane.
/// If no name is supplied to the registration, no runtime attribute should be specified.
public class SwinjectStoryboard: _SwinjectStoryboardBase, SwinjectStoryboardProtocol {
/// A shared container used by SwinjectStoryboard instances that are instantiated without specific containers.
///
/// Typical usecases of this property are:
/// - Implicit instantiation of UIWindow and its root view controller from "Main" storyboard.
/// - Storyboard references to transit from a storyboard to another.
public static var defaultContainer = Container()
// Boxing to workaround a runtime error [Xcode 7.1.1 and Xcode 7.2 beta 4]
// If container property is Resolver type and a Resolver instance is assigned to the property,
// the program crashes by EXC_BAD_ACCESS, which looks a bug of Swift.
internal var container: Box<Resolver>!
/// Do NOT call this method explicitly. It is designed to be called by the runtime.
public override class func initialize() {
struct Static {
static var onceToken: () = {
(SwinjectStoryboard.self as SwinjectStoryboardProtocol.Type).setup?()
}()
}
let _ = Static.onceToken
}
private override init() {
super.init()
}
/// Creates the new instance of `SwinjectStoryboard`. This method is used instead of an initializer.
///
/// - Parameters:
/// - name: The name of the storyboard resource file without the filename extension.
/// - bundle: The bundle containing the storyboard file and its resources. Specify nil to use the main bundle.
/// - container: The container with registrations of the view/window controllers in the storyboard and their dependencies.
/// The shared singleton container `SwinjectStoryboard.defaultContainer` is used if no container is passed.
///
/// - Returns: The new instance of `SwinjectStoryboard`.
public class func create(
name: String,
bundle storyboardBundleOrNil: Bundle?,
container: Resolver = SwinjectStoryboard.defaultContainer) -> SwinjectStoryboard
{
// Use this factory method to create an instance because the initializer of UI/NSStoryboard is "not inherited".
let storyboard = SwinjectStoryboard._create(name, bundle: storyboardBundleOrNil)
storyboard.container = Box(container)
return storyboard
}
#if os(iOS) || os(tvOS)
/// Instantiates the view controller with the specified identifier.
/// The view controller and its child controllers have their dependencies injected
/// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`.
///
/// - Parameter identifier: The identifier set in the storyboard file.
///
/// - Returns: The instantiated view controller with its dependencies injected.
public override func instantiateViewController(withIdentifier identifier: String) -> UIViewController {
SwinjectStoryboard.pushInstantiatingStoryboard(self)
let viewController = super.instantiateViewController(withIdentifier: identifier)
SwinjectStoryboard.popInstantiatingStoryboard()
injectDependency(to: viewController)
return viewController
}
private func injectDependency(to viewController: UIViewController) {
guard !viewController.wasInjected else { return }
defer { viewController.wasInjected = true }
let registrationName = viewController.swinjectRegistrationName
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// If a future update of Xcode fixes the problem, replace the resolution with the following code and fix storyboardInitCompleted too.
// https://github.com/Swinject/Swinject/issues/10
if let container = container.value as? _Resolver {
let option = SwinjectStoryboardOption(controllerType: type(of: viewController))
typealias FactoryType = (Resolver, Container.Controller) -> Container.Controller
let _ = container._resolve(name: registrationName, option: option) { (factory: FactoryType) in factory(self.container.value, viewController) }
} else {
fatalError("A type conforming Resolver protocol must conform _Resolver protocol too.")
}
for child in viewController.childViewControllers {
injectDependency(to: child)
}
}
#elseif os(OSX)
/// Instantiates the view/Window controller with the specified identifier.
/// The view/window controller and its child controllers have their dependencies injected
/// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`.
///
/// - Parameter identifier: The identifier set in the storyboard file.
///
/// - Returns: The instantiated view/window controller with its dependencies injected.
public override func instantiateController(withIdentifier identifier: String) -> Any {
SwinjectStoryboard.pushInstantiatingStoryboard(self)
let controller = super.instantiateController(withIdentifier: identifier)
SwinjectStoryboard.popInstantiatingStoryboard()
injectDependency(to: controller)
return controller
}
private func injectDependency(to controller: Container.Controller) {
if let controller = controller as? InjectionVerifiable {
guard !controller.wasInjected else { return }
defer { controller.wasInjected = true }
}
let registrationName = (controller as? RegistrationNameAssociatable)?.swinjectRegistrationName
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// If a future update of Xcode fixes the problem, replace the resolution with the following code and fix storyboardInitCompleted too:
// https://github.com/Swinject/Swinject/issues/10
if let container = container.value as? _Resolver {
let option = SwinjectStoryboardOption(controllerType: type(of: controller))
typealias FactoryType = (Resolver, Container.Controller) -> Container.Controller
let _ = container._resolve(name: registrationName, option: option) { (factory: FactoryType) in factory(self.container.value, controller) }
} else {
fatalError("A type conforming Resolver protocol must conform _Resolver protocol too.")
}
if let windowController = controller as? NSWindowController, let viewController = windowController.contentViewController {
injectDependency(to: viewController)
}
if let viewController = controller as? NSViewController {
for child in viewController.childViewControllers {
injectDependency(to: child)
}
}
}
#endif
}
#endif
| c648b444a01ff73c9b3a1a3738483806 | 46.66875 | 154 | 0.700144 | false | false | false | false |
Malecks/PALette | refs/heads/master | Palette/Palette.swift | mit | 1 | //
// Palette.swift
// Palette1.0
//
// Created by Alexander Mathers on 2016-02-29.
// Copyright © 2016 Malecks. All rights reserved.
//
import UIKit
import IGListKit
final class Palette: NSObject, NSCoding {
private static let colorsKey = "colors"
private static let imageURLKey = "imageURL"
private static let diffIdKey = "diffId"
fileprivate var diffId: NSNumber!
var colors: [UIColor]!
var imageURL: String!
init (colors: Array<UIColor>, image: String) {
self.colors = colors
self.imageURL = image
}
override init() {
super.init()
}
required convenience init(coder decoder: NSCoder) {
self.init()
self.colors = decoder.decodeObject(forKey: Palette.colorsKey) as? [UIColor] ?? []
self.imageURL = decoder.decodeObject(forKey: Palette.imageURLKey) as? String ?? ""
self.diffId = decoder.decodeObject(forKey: Palette.diffIdKey) as? NSNumber ?? Date().timeIntervalSince1970 as NSNumber
}
func encode(with aCoder:NSCoder) {
aCoder.encode(self.colors, forKey: Palette.colorsKey)
aCoder.encode(self.imageURL, forKey: Palette.imageURLKey)
aCoder.encode(self.diffId, forKey: Palette.diffIdKey)
}
}
extension Palette {
func shareableImage() -> UIImage? {
guard let view = PaletteView.instanceFromNib() as? PaletteView else { return nil }
view.frame = CGRect(x: 0, y: 0, width: 355, height: 415)
view.update(with: self)
view.setNeedsLayout()
view.layoutIfNeeded()
UIGraphicsBeginImageContextWithOptions(view.frame.size, view.isOpaque, 0.0)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension Palette: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return self.diffId
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if let object = object as? Palette {
return colors == object.colors && imageURL == object.imageURL
}
return false
}
}
| c4ccf2ae473cd104ae17a75297718382 | 28.573333 | 126 | 0.643823 | false | false | false | false |
wheely/Bunnyhop | refs/heads/master | Bunnyhop/JSONEncodable.swift | mit | 1 | public protocol JSONEncodable {
var json: JSON { get }
}
// MARK: - JSON Conformance
extension JSON: JSONEncodable {
public var json: JSON {
return self
}
}
// MARK: - JSON Initialization With JSONEncodable
extension JSON {
public init<T: JSONEncodable>(_ value: T) {
self = value.json
}
public init<T: Collection>(_ value: T) where T.Iterator.Element: JSONEncodable {
self = .arrayValue(value.map { .some($0.json) })
}
public init<T: Collection, E: JSONEncodable>(_ value: T) where T.Iterator.Element == E? {
self = .arrayValue(value.map { $0?.json })
}
public init<T: JSONEncodable>(_ elements: [String: T]) {
self = .dictionaryValue(Dictionary(elements: elements.map { ($0, .some($1.json)) }))
}
public init<T: JSONEncodable>(_ elements: [String: T?]) {
self = .dictionaryValue(Dictionary(elements: elements.map { ($0, $1?.json) }))
}
}
extension JSON: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: JSONEncodable?...) {
self = .arrayValue(elements.map { $0?.json })
}
}
extension JSON: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, JSONEncodable?)...) {
self = .dictionaryValue(Dictionary(elements: elements.map { ($0, $1?.json) }))
}
}
| 80cbdfc2b1ebe7e80f02901a9d89cc99 | 25.84 | 93 | 0.627422 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Foundation/Helpers/NewsNotificationPermissionHelper.swift | mpl-2.0 | 2 | //
// NewsNotificationPermissionHelper.swift
// Client
//
// Created by Mahmoud Adam on 5/27/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import UIKit
class NewsNotificationPermissionHelper: NSObject {
//MARK: - Constants
fileprivate let minimumNumberOfOpenings = 4
fileprivate let minimumNumberOfDays = 8
fileprivate let askedBeforeKey = "askedBefore"
fileprivate let lastAskDayKey = "lastAskDay"
fileprivate let disableAskingKey = "disableAsking"
fileprivate let newInstallKey = "newInstall"
fileprivate let installDayKey = "installDay"
fileprivate let numberOfOpeningsKey = "numberOfOpenings"
fileprivate var askingDisabled: Bool?
//MARK: - Singltone & init
static let sharedInstance = NewsNotificationPermissionHelper()
//MARK: - Public APIs
func onAppEnterBackground() {
return
// TODO: Commented till push notifications will be available
/*
let numberOfOpenings = getNumerOfOpenings()
LocalDataStore.setObject(numberOfOpenings + 1, forKey: numberOfOpeningsKey)
askingDisabled = LocalDataStore.objectForKey(disableAskingKey) as? Bool
*/
}
func onAskForPermission() {
LocalDataStore.setObject(true, forKey: askedBeforeKey)
LocalDataStore.setObject(0, forKey: numberOfOpeningsKey)
LocalDataStore.setObject(Date.getDay(), forKey: lastAskDayKey)
}
func isAksedForPermissionBefore() -> Bool {
guard let askedBefore = LocalDataStore.objectForKey(askedBeforeKey) as? Bool else {
return false
}
return askedBefore
}
func disableAskingForPermission () {
askingDisabled = true
LocalDataStore.setObject(askingDisabled, forKey: disableAskingKey)
}
func isAskingForPermissionDisabled () -> Bool {
guard let isDisabled = askingDisabled else {
return false
}
return isDisabled
}
func shouldAskForPermission() -> Bool {
return false
// TODO: Commented till push notifications will be available
/*
if isAskingForPermissionDisabled() || UIApplication.sharedApplication().isRegisteredForRemoteNotifications() {
return false
}
var shouldAskForPermission = true
if isNewInstall() || isAksedForPermissionBefore() {
if getNumberOfDaysSinceLastAction() < minimumNumberOfDays || getNumerOfOpenings() < minimumNumberOfOpenings {
shouldAskForPermission = false
}
}
return shouldAskForPermission
*/
}
func enableNewsNotifications() {
let notificationSettings = UIUserNotificationSettings(types: [UIUserNotificationType.badge, UIUserNotificationType.sound, UIUserNotificationType.alert], categories: nil)
UIApplication.shared.registerForRemoteNotifications()
UIApplication.shared.registerUserNotificationSettings(notificationSettings)
TelemetryLogger.sharedInstance.logEvent(.NewsNotification("enable"))
}
func disableNewsNotifications() {
UIApplication.shared.unregisterForRemoteNotifications()
TelemetryLogger.sharedInstance.logEvent(.NewsNotification("disalbe"))
}
//MARK: - Private APIs
fileprivate func isNewInstall() -> Bool {
var isNewInstall = false
// check if it is calcualted before
if let isNewInstall = LocalDataStore.objectForKey(newInstallKey) as? Bool {
return isNewInstall;
}
// compare today's day with install day to determine whether it is update or new install
let todaysDay = Date.getDay()
if let installDay = TelemetryLogger.sharedInstance.getInstallDay(), todaysDay == installDay {
isNewInstall = true
LocalDataStore.setObject(todaysDay, forKey: installDayKey)
}
LocalDataStore.setObject(isNewInstall, forKey: newInstallKey)
return isNewInstall
}
fileprivate func getNumberOfDaysSinceLastAction() -> Int {
if isNewInstall() && !isAksedForPermissionBefore() {
return getNumberOfDaysSinceInstall()
} else {
return getNumberOfDaysSinceLastAsk()
}
}
fileprivate func getNumberOfDaysSinceInstall() -> Int {
guard let installDay = LocalDataStore.objectForKey(installDayKey) as? Int else {
return 0
}
let daysSinceInstal = Date.getDay() - installDay
return daysSinceInstal
}
fileprivate func getNumberOfDaysSinceLastAsk() -> Int {
guard let lastAskDay = LocalDataStore.objectForKey(lastAskDayKey) as? Int else {
return 0
}
let daysSinceLastAsk = Date.getDay() - lastAskDay
return daysSinceLastAsk
}
fileprivate func getNumerOfOpenings() -> Int {
guard let numberOfOpenings = LocalDataStore.objectForKey(numberOfOpeningsKey) as? Int else {
return 0
}
return numberOfOpenings
}
}
| a0111f04c15a387c2fc95ff978a9e550 | 31.899371 | 177 | 0.650162 | false | false | false | false |
khizkhiz/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00360-swift-parser-parseexprlist.swift | apache-2.0 | 1 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import
h
}
func e<l {
enum e {
func e
j {
}
class l: j{ k() -> ())
}
func j<o : Boolean>(l: o) {
}
func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(p: (Any, Any) -> Any) -> Any in
func n<n : l,) {
}
n(e())
struct d<f : e, g: e where g.h == f.h> {{
}
struct B<T : A> {
}
protocol C {
ty }
}
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
}
struct n : g {
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
protoc {
}
protocol f {
protocol c : b { func b
class A {
class func a() -> String {
let d: String = {
}()
}
class d<c>: NSObject {
init(b: c) {
}
}
protocol A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
class A {
class func a {
return static let d: String = {
}()
func x }
) T}
protocol A {
}
struct B<T : A> {
lett D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
struct d<f : e, g: e where g.h == f.h> {
col P {
}
}
}
i struct c {
c a(b: Int0) {
}
class A {
class func a() -> Self {
return b(self.dy
| b9ae9b50938a0566c1e43aa58d7199b0 | 12.681818 | 87 | 0.539037 | false | false | false | false |
kristoferdoman/Stormy | refs/heads/master | Stormy/DetailBackgroundView.swift | mit | 2 | //
// DetailBackgroundView.swift
// Stormy
//
// Created by Kristofer Doman on 2015-07-03.
// Copyright (c) 2015 Kristofer Doman. All rights reserved.
//
import UIKit
class DetailBackgroundView: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
//// Color Declarations
var lightPurple: UIColor = UIColor(red: 0.377, green: 0.075, blue: 0.778, alpha: 1.000)
var darkPurple: UIColor = UIColor(red: 0.060, green: 0.036, blue: 0.202, alpha: 1.000)
let context = UIGraphicsGetCurrentContext()
//// Gradient Declarations
let purpleGradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [lightPurple.CGColor, darkPurple.CGColor], [0, 1])
//// Background Drawing
let backgroundPath = UIBezierPath(rect: CGRectMake(0, 0, self.frame.width, self.frame.height))
CGContextSaveGState(context)
backgroundPath.addClip()
CGContextDrawLinearGradient(context, purpleGradient,
CGPointMake(160, 0),
CGPointMake(160, 568),
UInt32(kCGGradientDrawsBeforeStartLocation) | UInt32(kCGGradientDrawsAfterEndLocation))
CGContextRestoreGState(context)
//// Sun Path
let circleOrigin = CGPointMake(0, 0.80 * self.frame.height)
let circleSize = CGSizeMake(self.frame.width, 0.65 * self.frame.height)
let pathStrokeColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.390)
let pathFillColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.100)
//// Sun Drawing
var sunPath = UIBezierPath(ovalInRect: CGRectMake(circleOrigin.x, circleOrigin.y, circleSize.width, circleSize.height))
pathFillColor.setFill()
sunPath.fill()
pathStrokeColor.setStroke()
sunPath.lineWidth = 1
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [2, 2], 2)
sunPath.stroke()
CGContextRestoreGState(context)
}
}
| 56721b80ce4cbcaf00121afb20b9b9c0 | 37.928571 | 137 | 0.650459 | false | false | false | false |
Shivam0911/IOS-Training-Projects | refs/heads/master | webServiceHitDemo/webServiceHitDemo/ImagesSearchVC.swift | mit | 1 | //
// ImagesSearchVC.swift
// WebServiceHitDemo
//
// Created by MAC on 21/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class ImagesSearchVC: UIViewController {
//MARK: Outlets
//==================
@IBOutlet weak var imagesCollectionOutlet: UICollectionView!
@IBOutlet weak var searchBarOutlet: UISearchBar!
var ImagesList = [ImagesModel]()
var searchItem : String? = nil
//MARK: View life Cycle
//==================
override func viewDidLoad() {
super.viewDidLoad()
self.doSubViewLoad()
}
//MARK: doSubViewLoad Method
//==================
private func doSubViewLoad() {
imagesCollectionOutlet.dataSource = self
imagesCollectionOutlet.delegate = self
let imageCollectioncellnib = UINib(nibName: "ImageCollectionViewCell", bundle: nil)
imagesCollectionOutlet.register(imageCollectioncellnib, forCellWithReuseIdentifier: "ImageCollectionViewCellID")
imagesCollectionOutlet.backgroundColor = UIColor.clear
searchBarOutlet.delegate = self
}
// func touchesBegan used to auto hide keyboard On event touchesBegan
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: UICollectionView DataSource , UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
//==========================================================================
extension ImagesSearchVC : UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
// Returns numberOfItemsInSection
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImagesList.count
}
//MARK: collectionView cellForItemAt Method
//================================
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCellID", for: indexPath) as? ImageCollectionViewCell
else{
fatalError("Cell Not Found !")
}
//MARK: Image Load From URL
//=====================
if let url = URL(string: ImagesList[indexPath.row].previewURL) {
// gets preview Url and sets the image of each cell
cell.imageVIewToLoadOutlet.af_setImage(withURL : url)
}
cell.imageVIewToLoadOutlet.contentMode = .scaleAspectFill
return cell
}
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width:180.0,height:180.0)
}
//MARK: didSelectItemAt Method
//=======================
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let url = URL(string: ImagesList[indexPath.row].webformatURL) else {
fatalError("no webformat URL")
}
//MARK: Navigation Insatantiation
//========================
let storyBoardScene = UIStoryboard(name: "Main", bundle: Bundle.main)
let navi = storyBoardScene.instantiateViewController(withIdentifier : "PreviewVCID") as! PreviewVC
navi.imageUrl = url // sends high pixel rated URL of Selected Cell
navi.title = self.title
self.navigationController?.pushViewController(navi, animated: true)
}
}
//MARK: UISearchBarDelegate
//=====================
extension ImagesSearchVC : UISearchBarDelegate{
//MARK: searchBarSearchButtonClicked Method
//==================================
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if searchBar.text != "" {
self.title = searchBar.text
//MARK : Service Hit
//==============
WebServices().fetchDataFromPixabay(withQuery: searchItem!, success: { (images : [ImagesModel]) in
self.ImagesList = images
self.imagesCollectionOutlet.reloadData()
}) { (error : Error) in print(error)}
}
else{
let myAlert = UIAlertController(nibName : "TextField Empty!", bundle : nil)
myAlert.addAction(UIAlertAction(title : "Ok",style : UIAlertActionStyle.default,handler:nil))
}
}
}
| e5f0d97beb4dcf7f51c070660e2b8898 | 29.429448 | 153 | 0.5875 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/maximum-subarray.swift | mit | 2 | /**
* https://leetcode.com/problems/maximum-subarray/
*
*
*/
class Solution {
/// - Complexity: O(n), n is the number of elements in the array.
///
/// - Description:
/// Here,
/// 1. sum is the maximum sum ending with element n, inclusive.
/// 2. compare the maxSum with current sum ending with element n.
/// 3. if sum is negtive, it will not be helpful for the maximum possible element ending with next element. Then, clear it to zero, 0.
///
///
func maxSubArray(_ nums: [Int]) -> Int {
var sum = 0
var maxSum = Int.min
for n in nums {
sum += n
maxSum = max(maxSum, sum)
sum = max(0, sum)
}
return maxSum
}
}
| 490b1352a2d2e4f5dee8f9c3b905c0cd | 28.076923 | 142 | 0.53836 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Services/CryptoFeeRepository.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Errors
import ToolKit
/// Type alias representing fees data for specific crypto currencies.
public typealias CryptoFeeType = TransactionFee & Decodable
/// Service that provides fees of its associated type.
public protocol CryptoFeeRepositoryAPI {
associatedtype FeeType: CryptoFeeType
/// Streams a single CryptoFeeType of the associated type.
/// This represent current fees to transact a crypto currency.
/// Never fails, uses default Fee values if network call fails.
var fees: AnyPublisher<FeeType, Never> { get }
}
public final class CryptoFeeRepository<FeeType: TransactionFee & Decodable>: CryptoFeeRepositoryAPI {
private struct Key: Hashable {}
// MARK: - CryptoFeeRepositoryAPI
public var fees: AnyPublisher<FeeType, Never> {
cachedValue.get(key: Key())
.replaceError(with: FeeType.default)
.eraseToAnyPublisher()
}
// MARK: - Private Properties
private let client: CryptoFeeClient<FeeType>
private let cachedValue: CachedValueNew<
Key,
FeeType,
NetworkError
>
// MARK: - Init
init(client: CryptoFeeClient<FeeType>) {
self.client = client
let feeCache = InMemoryCache<Key, FeeType>(
configuration: .onLoginLogout(),
refreshControl: PeriodicCacheRefreshControl(
refreshInterval: .minutes(1)
)
)
.eraseToAnyCache()
cachedValue = CachedValueNew(
cache: feeCache,
fetch: { [client] _ in
client.fees
}
)
}
public convenience init() {
self.init(client: CryptoFeeClient<FeeType>())
}
}
/// Type-erasure for CryptoFeeRepository.
public struct AnyCryptoFeeRepository<FeeType: CryptoFeeType>: CryptoFeeRepositoryAPI {
public var fees: AnyPublisher<FeeType, Never> {
_fees()
}
private let _fees: () -> AnyPublisher<FeeType, Never>
public init<API: CryptoFeeRepositoryAPI>(repository: API) where API.FeeType == FeeType {
_fees = { repository.fees }
}
}
| a4a9db2350915beba2e1be55e0618a29 | 26.08642 | 101 | 0.656791 | false | false | false | false |
LightD/ivsa-server | refs/heads/master | Sources/App/Web/AdminWebRouter.swift | mit | 1 | //
// AdminWebRouter.swift
// ivsa
//
// Created by Light Dream on 26/02/2017.
//
//
import Foundation
import Vapor
import Fluent
import HTTP
import Turnstile
import Routing
struct AdminWebRouter {
typealias Wrapped = HTTP.Responder
private let drop: Droplet
init(droplet: Droplet) {
self.drop = droplet
}
static func buildRouter(droplet: Droplet) -> AdminWebRouter {
return AdminWebRouter(droplet: droplet)
}
func registerRoutes(authMiddleware: AdminSessionAuthMiddleware) {
let adminBuilder = drop.grouped("admin")
let authBuilder = adminBuilder.grouped(authMiddleware)
self.buildIndex(adminBuilder)
self.buildAuth(adminBuilder)
self.buildHome(authBuilder)
}
private func buildIndex<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
builder.get { request in
do {
guard let _ = try request.adminSessionAuth.admin() else {
throw "redirect to auth page"
}
return Response(redirect: "/admin/registration")
}
catch {
return Response(redirect: "/admin/login")
}
}
}
private func buildAuth<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
builder.get("login") { request in
return try self.drop.view.make("admin/login")
}
builder.post("login") { request in
guard let username = request.formURLEncoded?["username"]?.string,
let password = request.formURLEncoded?["password"]?.string else {
return try self.drop.view.make("admin/login", ["flash": "Missing username or password"])
}
let credentials = UsernamePassword(username: username, password: password)
do {
_ = try request.adminSessionAuth.login(credentials)
return Response(redirect: "/admin")
} catch let e as Abort {
switch e {
case .custom(_, let message):
return try self.drop.view.make("admin/login", ["flash": message])
default:
return try self.drop.view.make("admin/login", ["flash": "Something went wrong. Please try again later!"])
}
}
}
}
private func buildHome<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
self.buildRegistration(builder)
}
private func buildRegistration<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
builder.get("register_delegate") { request in
guard var admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
if admin.accessToken == nil {
admin.generateAccessToken()
try admin.save()
}
let adminNode = try Node(node: admin.makeNode())
return try self.drop.view.make("admin/register_delegate", ["register_delegate": true, "user": adminNode])
}
builder.get("registration") { request in
guard var admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
if admin.accessToken == nil {
admin.generateAccessToken()
try admin.save()
}
let adminNode = try Node(node: admin.makeNode())
return try self.drop.view.make("admin/registration", ["registration": true, "user": adminNode])
}
builder.get("applicant_details", String.self) { request, applicantID in
guard var admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
if admin.accessToken == nil {
admin.generateAccessToken()
try admin.save()
}
// let data = Node(value: ["accessToken": admin.accessToken!, "applicantID": applicantID])
return try self.drop.view.make("admin/applicant_details", ["accessToken": admin.accessToken!, "applicantID": applicantID])
}
builder.get("waiting_list") { request in
guard let admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
print("before making the node with admin: \(admin)")
let node = try Node(node: ["waitlist": true, "user": admin.makeNode()])
print("after making the node: \(node)")
return try self.drop.view.make("admin/waitinglist", node)
}
builder.get("new_applicants") { request in
guard let admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
print("before making the node with admin: \(admin)")
let node = try Node(node: ["newapplicants": true, "user": admin.makeNode()])
print("after making the node: \(node)")
return try self.drop.view.make("admin/new_applicants", node)
}
builder.get("rejected") { request in
guard let admin = try request.adminSessionAuth.admin() else {
throw "admin not found"
}
print("before making the node with admin: \(admin)")
let node = try Node(node: ["rejected": true, "user": admin.makeNode()])
print("after making the node: \(node)")
return try self.drop.view.make("admin/rejected", node)
}
}
}
| 222bc12d3ab7787f94a746092253ad89 | 32.790419 | 134 | 0.558923 | false | false | false | false |
rogertjr/chatty | refs/heads/master | Chatty/Chatty/Controller/LaunchVC.swift | gpl-3.0 | 1 | //
// LaunchVC.swift
// Chatty
//
// Created by Roger on 31/08/17.
// Copyright © 2017 Decodely. All rights reserved.
//
import UIKit
class LaunchVC: UIViewController {
//MARK: Properties
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get {
return UIInterfaceOrientationMask.portrait
}
}
//MARK: Push to relevant ViewController
func pushTo(viewController: ViewControllerType){
switch viewController {
case .conversations:
let navVC = self.storyboard?.instantiateViewController(withIdentifier: "navVc") as! NavVC
self.show(navVC, sender: nil)
case .welcome:
let vc = self.storyboard?.instantiateViewController(withIdentifier: "welcomeVC") as! WelcomeVC
self.present(vc, animated: false, completion: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let userInformation = UserDefaults.standard.dictionary(forKey: "userInformation") {
let userEmail = userInformation["email"] as! String
let userPassword = userInformation["password"] as! String
AuthService.instance.loginUser(withEmail: userEmail, andPassword: userPassword, loginComplete: { [weak weakSelf = self] (status, error) in
DispatchQueue.main.async {
if status == true {
weakSelf?.pushTo(viewController: .conversations)
} else {
weakSelf?.pushTo(viewController: .welcome)
}
weakSelf = nil
}
})
} else {
self.pushTo(viewController: .welcome)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 206f56e0f2ffb4345a83907169173537 | 24.983333 | 141 | 0.710071 | false | false | false | false |
li-wenxue/Weibo | refs/heads/master | 新浪微博/新浪微博/Class/View/Home/TitleButton/WBTitleButton.swift | mit | 1 | //
// WBTitleButton.swift
// 新浪微博
//
// Created by win_学 on 16/8/31.
// Copyright © 2016年 win_学. All rights reserved.
//
import UIKit
class WBTitleButton: UIButton {
/// ’重载‘ 构造函数
/// - title如果为 nil ,就显示 ’首页‘
/// - 如果不为 nil ,显示 title 和 箭头图像
init(title: String?) {
super.init(frame: CGRect())
if title == nil {
setTitle("首页", for: .normal)
} else {
// 添加一个空格 是为了调整 label 和 image 之间的间距,这属于 技巧性的 代码
setTitle(title!+" ", for: .normal)
// 设置箭头图像
setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
}
// 2> 设置字体和颜色
titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
setTitleColor(UIColor.darkGray, for: .normal)
// 3> 调整大小
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 纯代码自定义控件最常用的一个系统方法
/// 重新布局子视图
override func layoutSubviews() {
super.layoutSubviews()
// 判断 titlelabel 和 imageview 同时存在
guard let titleLabel = titleLabel, let imageView = imageView else {
return
}
print("titlebutton---- \(titleLabel) \(imageView)")
// 将 label 的 x 向左移动 imageview 的宽度
// titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0) 效果并不好
titleEdgeInsets = UIEdgeInsetsMake(0, -imageView.bounds.width, 0, 0)
// 将 imageview 的 x 向右移动 label 的宽度
// imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.width, dy: 0)
imageEdgeInsets = UIEdgeInsetsMake(0, titleLabel.bounds.width, 0, 0)
}
}
| ca65253abb0b67c6f7dd8e500f8f1f3b | 28.238095 | 97 | 0.564061 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | ThirdParty/UIImageColors.swift | mpl-2.0 | 7 | //
// UIImageColors.swift
// https://github.com/jathu/UIImageColors
//
// Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto
// Original Cocoa version by Panic Inc. - Portland
//
import UIKit
public struct UIImageColors {
public var background: UIColor!
public var primary: UIColor!
public var secondary: UIColor!
public var detail: UIColor!
}
class PCCountedColor {
let color: UIColor
let count: Int
init(color: UIColor, count: Int) {
self.color = color
self.count = count
}
}
extension CGColor {
var components: [CGFloat] {
get {
var red = CGFloat()
var green = CGFloat()
var blue = CGFloat()
var alpha = CGFloat()
UIColor(cgColor: self).getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return [red,green,blue,alpha]
}
}
}
extension UIColor {
var isDarkColor: Bool {
let RGB = self.cgColor.components
return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5
}
var isBlackOrWhite: Bool {
let RGB = self.cgColor.components
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
func isDistinct(compareColor: UIColor) -> Bool {
let bg = self.cgColor.components
let fg = compareColor.cgColor.components
let threshold: CGFloat = 0.25
if fabs(bg[0] - fg[0]) > threshold || fabs(bg[1] - fg[1]) > threshold || fabs(bg[2] - fg[2]) > threshold {
if fabs(bg[0] - bg[1]) < 0.03 && fabs(bg[0] - bg[2]) < 0.03 {
if fabs(fg[0] - fg[1]) < 0.03 && fabs(fg[0] - fg[2]) < 0.03 {
return false
}
}
return true
}
return false
}
func colorWithMinimumSaturation(minSaturation: CGFloat) -> UIColor {
var hue: CGFloat = 0.0
var saturation: CGFloat = 0.0
var brightness: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if saturation < minSaturation {
return UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha)
} else {
return self
}
}
func isContrastingColor(compareColor: UIColor) -> Bool {
let bg = self.cgColor.components
let fg = compareColor.cgColor.components
let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2]
let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2]
let bgGreater = bgLum > fgLum
let nom = bgGreater ? bgLum : fgLum
let denom = bgGreater ? fgLum : bgLum
let contrast = (nom + 0.05) / (denom + 0.05)
return 1.6 < contrast
}
}
extension UIImage {
private func resizeForUIImageColors(newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
self.draw(in: CGRect(width: newSize.width, height: newSize.height))
guard let result = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("UIImageColors.resizeForUIImageColors failed: UIGraphicsGetImageFromCurrentImageContext returned nil")
}
return result
}
/**
Get `UIImageColors` from the image asynchronously (in background thread).
Discussion: Use smaller sizes for better performance at the cost of quality colors. Use larger sizes for better color sampling and quality at the cost of performance.
- parameter scaleDownSize: Downscale size of image for sampling, if `CGSize.zero` is provided, the sample image is rescaled to a width of 250px and the aspect ratio height.
- parameter completionHandler: `UIImageColors` for this image.
*/
public func getColors(scaleDownSize: CGSize = .zero, completionHandler: @escaping (UIImageColors) -> Void) {
DispatchQueue.global().async {
let result = self.getColors(scaleDownSize: scaleDownSize)
DispatchQueue.main.async {
completionHandler(result)
}
}
}
/**
Get `UIImageColors` from the image synchronously (in main thread).
Discussion: Use smaller sizes for better performance at the cost of quality colors. Use larger sizes for better color sampling and quality at the cost of performance.
- parameter scaleDownSize: Downscale size of image for sampling, if `CGSize.zero` is provided, the sample image is rescaled to a width of 250px and the aspect ratio height.
- returns: `UIImageColors` for this image.
*/
public func getColors(scaleDownSize: CGSize = .zero) -> UIImageColors {
var scaleDownSize = scaleDownSize
if scaleDownSize == .zero {
let ratio = self.size.width/self.size.height
let r_width: CGFloat = 250
scaleDownSize = CGSize(width: r_width, height: r_width/ratio)
}
var result = UIImageColors()
let cgImage = self.resizeForUIImageColors(newSize: scaleDownSize).cgImage!
let width: Int = cgImage.width
let height: Int = cgImage.height
let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
let randomColorsThreshold = Int(CGFloat(height)*0.01)
let sortedColorComparator: Comparator = { (main, other) -> ComparisonResult in
let m = main as! PCCountedColor, o = other as! PCCountedColor
if m.count < o.count {
return .orderedDescending
} else if m.count == o.count {
return .orderedSame
} else {
return .orderedAscending
}
}
guard let data = CFDataGetBytePtr(cgImage.dataProvider!.data) else {
fatalError("UIImageColors.getColors failed: could not get cgImage data")
}
// Filter out and collect pixels from image
let imageColors = NSCountedSet(capacity: width * height)
for x in 0..<width {
for y in 0..<height {
let pixel: Int = ((width * y) + x) * 4
// Only consider pixels with 50% opacity or higher
if 127 <= data[pixel+3] {
imageColors.add(UIColor(
red: CGFloat(data[pixel+2])/255,
green: CGFloat(data[pixel+1])/255,
blue: CGFloat(data[pixel])/255,
alpha: 1.0
))
}
}
}
// Get background color
var enumerator = imageColors.objectEnumerator()
var sortedColors = NSMutableArray(capacity: imageColors.count)
while let kolor = enumerator.nextObject() as? UIColor {
let colorCount = imageColors.count(for: kolor)
if randomColorsThreshold < colorCount {
sortedColors.add(PCCountedColor(color: kolor, count: colorCount))
}
}
sortedColors.sort(comparator: sortedColorComparator)
var proposedEdgeColor: PCCountedColor
if 0 < sortedColors.count {
proposedEdgeColor = sortedColors.object(at: 0) as! PCCountedColor
} else {
proposedEdgeColor = PCCountedColor(color: blackColor, count: 1)
}
if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count {
for i in 1..<sortedColors.count {
let nextProposedEdgeColor = sortedColors.object(at: i) as! PCCountedColor
if (CGFloat(nextProposedEdgeColor.count)/CGFloat(proposedEdgeColor.count)) > 0.3 {
if !nextProposedEdgeColor.color.isBlackOrWhite {
proposedEdgeColor = nextProposedEdgeColor
break
}
} else {
break
}
}
}
result.background = proposedEdgeColor.color
// Get foreground colors
enumerator = imageColors.objectEnumerator()
sortedColors.removeAllObjects()
sortedColors = NSMutableArray(capacity: imageColors.count)
let findDarkTextColor = !result.background.isDarkColor
while var kolor = enumerator.nextObject() as? UIColor {
kolor = kolor.colorWithMinimumSaturation(minSaturation: 0.15)
if kolor.isDarkColor == findDarkTextColor {
let colorCount = imageColors.count(for: kolor)
sortedColors.add(PCCountedColor(color: kolor, count: colorCount))
}
}
sortedColors.sort(comparator: sortedColorComparator)
for curContainer in sortedColors {
let kolor = (curContainer as! PCCountedColor).color
if result.primary == nil {
if kolor.isContrastingColor(compareColor: result.background) {
result.primary = kolor
}
} else if result.secondary == nil {
if !result.primary.isDistinct(compareColor: kolor) || !kolor.isContrastingColor(compareColor: result.background) {
continue
}
result.secondary = kolor
} else if result.detail == nil {
if !result.secondary.isDistinct(compareColor: kolor) || !result.primary.isDistinct(compareColor: kolor) || !kolor.isContrastingColor(compareColor: result.background) {
continue
}
result.detail = kolor
break
}
}
let isDarkBackgound = result.background.isDarkColor
if result.primary == nil {
result.primary = isDarkBackgound ? whiteColor:blackColor
}
if result.secondary == nil {
result.secondary = isDarkBackgound ? whiteColor:blackColor
}
if result.detail == nil {
result.detail = isDarkBackgound ? whiteColor:blackColor
}
return result
}
}
| 931b73c43bea958656f23d81df2bc26e | 35.604317 | 183 | 0.588542 | false | false | false | false |
garricn/secret | refs/heads/master | FLYR/FlyrCell.swift | mit | 1 | //
// FlyrCell.swift
// FLYR
//
// Created by Garric Nahapetian on 8/14/16.
// Copyright © 2016 Garric Nahapetian. All rights reserved.
//
import UIKit
import Cartography
class FlyrCell: UITableViewCell {
let _imageView = UIImageView()
static let identifier = FlyrCell.description()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
imageView?.contentMode = .ScaleAspectFit
addSubview(_imageView)
constrain(_imageView) { imageView in
imageView.edges == imageView.superview!.edges
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 0e729eb618e8b1b5c8027942c2e2e307 | 23.4 | 74 | 0.672131 | false | false | false | false |
ricardo0100/previsaodotempo | refs/heads/master | PrevisaoDoTempo/PrevisaoDoTempo/ListOfCitiesTableViewController.swift | unlicense | 1 | //
// ListOfCitiesTableViewController.swift
// PrevisaoDoTempo
//
// Created by Ricardo Gehrke Filho on 03/02/16.
// Copyright © 2016 Ricardo Gehrke Filho. All rights reserved.
//
import UIKit
import JGProgressHUD
class ListOfCitiesTableViewController: UITableViewController, UISearchBarDelegate, SearchCityDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var hud: JGProgressHUD?
var controller = APIController()
var cities: [City]? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
controller.searchCitydelegate = self
searchBar.delegate = self
hud = JGProgressHUD(style: .Dark)
hud!.textLabel!.text = "Buscando"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
searchBar.resignFirstResponder()
if segue.identifier == "Show Weather For City" {
let vc = segue.destinationViewController as! CityWeatherViewController
let index = tableView.indexPathForSelectedRow!.row
let city = cities![index]
vc.city = city
}
}
func listCitiesWith(cities: [City]) {
self.cities = cities
}
func hideActivityIndicator() {
hud!.dismiss()
}
func showActivityIndicator() {
hud!.showInView(self.view)
searchBar.resignFirstResponder()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let list = cities {
return list.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("City Cell", forIndexPath: indexPath)
let city = cities![indexPath.row]
cell.textLabel!.text = city.name
cell.detailTextLabel!.text = city.state
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
self.controller.searchForCitiesWith(searchBar.text!)
self.navigationController!.setNavigationBarHidden(false, animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
searchBar.resignFirstResponder()
}
}
| cb1c4fd3f8e1277ac75041d795e0eb89 | 27.4 | 118 | 0.638498 | false | false | false | false |
omnypay/omnypay-sdk-ios | refs/heads/master | ExampleApp/OmnyPayAPIDemo/OmnyPayAPIDemo/AddCard.swift | apache-2.0 | 2 | //
// AddCard.swift
// OmnyPayDemoApp
//
// Copyright © 2016 OmnyPay. All rights reserved.
//
import UIKit
import OmnyPayAPI
import Eureka
/* To be used later */
class AddCard: UIViewController {
// override func viewDidLoad() {
// super.viewDidLoad()
//
// form
// +++ Section()
// <<< AlertRow<String>() {
// $0.title = OPGlobals.OMNYPAY_HOST
// $0.selectorTitle = "Choose OmnyPay Host"
// $0.options = ["Pantheon Demo","Pantheon Dev"]
// $0.value = OPUserDefaults.omnypayHost
// $0.tag = "omnypayHost"
// }.onChange { row in
// self.validationRequired = true
// }.cellSetup{ cell, row in
// OPUserDefaults.previousOmnypayHost = OPUserDefaults.omnypayHost
// }
//
//
// <<< TextRow() {
// $0.title = OPGlobals.MERCHANT_NAME
// $0.value = OPUserDefaults.merchantName
// $0.tag = "merchantName"
// }.cellSetup{ cell, row in
// OPUserDefaults.previousMerchantName = OPUserDefaults.merchantName
// }.onChange{ row in
// self.validationRequired = true
// }
// }
}
| 8d07baa2f8e540d16e9d22b54cf51682 | 22.04 | 77 | 0.568576 | false | false | false | false |
PrinceChen/DouYu | refs/heads/master | DouYu/DouYu/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | mit | 1 | //
// UIBarButtonItem-Extension.swift
// DouYu
//
// Created by prince.chen on 2017/3/1.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
class func createItem(imageName: String, highlightedImageName: String, size: CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: highlightedImageName), for: .highlighted)
btn.frame = CGRect(origin: .zero, size: size)
return UIBarButtonItem(customView: btn)
}
convenience init(imageName: String, highlightedImageName: String = "", size: CGSize = .zero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
if highlightedImageName != "" {
btn.setImage(UIImage(named: highlightedImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: .zero, size: size)
}
self.init(customView: btn)
}
}
| 9f21a6a158c3c58374ce6b450d05b8db | 25.422222 | 109 | 0.579479 | false | false | false | false |
YangChing/YCRateView | refs/heads/master | Example/YCRateView/ViewController.swift | mit | 1 | //
// ViewController.swift
// YCRateView
//
// Created by [email protected] on 08/27/2018.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import YCRateView
class ViewController: UIViewController {
@IBOutlet weak var ycRateView: YCRateView!
override func viewDidLoad() {
super.viewDidLoad()
ycRateView.yc_InitValue = 2
ycRateView.yc_IsTextHidden = false
ycRateView.yc_IsSliderEnabled = true
ycRateView.yc_TextSize = 20
ycRateView.yc_TextColor = UIColor.blue
// Do any additional setup after loading the view, typically from a nib.
ycRateView.sliderAddTarget(target: self, selector: #selector(doSomething), event: .valueChanged)
// add call back
ycRateView.yc_FrontImageView.image = #imageLiteral(resourceName: "gray_star_full")
ycRateView.yc_BackImageView.image = #imageLiteral(resourceName: "gray_star_space")
ycRateView.yc_RateViewChanged = { slider, frontImageView, backImageView, text in
if slider.value <= 2.5 {
backImageView.image = #imageLiteral(resourceName: "gray_star_space")
frontImageView.image = #imageLiteral(resourceName: "gray_star_full")
} else {
backImageView.image = #imageLiteral(resourceName: "gold_star_space")
frontImageView.image = #imageLiteral(resourceName: "gold_star_full")
}
}
}
@objc func doSomething(sender: UISlider) {
print("slider value: \(sender.value)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 77b25111e7622a80faee8ff1496d9a1b | 33.020408 | 102 | 0.686263 | false | false | false | false |
wess/reddift | refs/heads/master | reddift/Network/Session+listings.swift | mit | 1 | //
// Session+listings.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
/**
The sort method for listing Link object, "/r/[subreddit]/[sort]" or "/[sort]".
*/
enum PrivateLinkSortBy {
case Controversial
case Top
var path:String {
switch self{
case .Controversial:
return "/controversial"
case .Top:
return "/hot"
}
}
}
extension Session {
/**
Returns object which is generated from JSON object from reddit.com.
Originally, response object is [Listing].
This method filters Listing object at index 0, and returns onlly an array such as [Comment].
:param: response NSURLResponse object is passed from NSURLSession.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func handleRequestFilteringLinkObject(request:NSMutableURLRequest, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
if let response = response {
self.updateRateLimitWithURLResponse(response)
}
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON >>> filterArticleResponse
completion(result)
})
task.resume()
return task
}
/**
Get the comment tree for a given Link article.
If supplied, comment is the ID36 of a comment in the comment tree for article. This comment will be the (highlighted) focal point of the returned view and context will be the number of parents shown.
:param: link Link from which comment will be got.
:param: sort The type of sorting.
:param: comments If supplied, comment is the ID36 of a comment in the comment tree for article.
:param: depth The maximum depth of subtrees in the thread. Default is 4.
:param: limit The maximum number of comments to return. Default is 100.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
public func getArticles(link:Link, sort:CommentSort, comments:[String]? = nil, withoutLink:Bool = false, depth:Int = 4, limit:Int = 100, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = ["sort":sort.type, "depth":"\(depth)", "showmore":"True", "limit":"\(limit)"]
if let comments = comments {
var commaSeparatedIDString = commaSeparatedStringFromList(comments)
parameter["comment"] = commaSeparatedIDString
}
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/comments/" + link.id, parameter:parameter, method:"GET", token:token)
if withoutLink {
return handleRequestFilteringLinkObject(request, completion: completion)
}
return handleRequest(request, completion: completion)
}
/**
Get Links from all subreddits or user specified subreddit.
:param: paginator Paginator object for paging contents.
:param: subreddit Subreddit from which Links will be gotten.
:param: integratedSort The original type of sorting a list, .Controversial, .Top, .Hot, or .New.
:param: TimeFilterWithin The type of filtering contents. When integratedSort is .Hot or .New, this parameter is ignored.
:param: limit The maximum number of comments to return. Default is 25.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
public func getList(paginator:Paginator, subreddit:SubredditURLPath?, sort:LinkSortType, timeFilterWithin:TimeFilterWithin, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
switch sort {
case .Controversial:
return getList(paginator, subreddit: subreddit, privateSortType: PrivateLinkSortBy.Controversial, timeFilterWithin: timeFilterWithin, limit: limit, completion: completion)
case .Top:
return getList(paginator, subreddit: subreddit, privateSortType: PrivateLinkSortBy.Top, timeFilterWithin: timeFilterWithin, limit: limit, completion: completion)
case .New:
return getNewOrHotList(paginator, subreddit: subreddit, type: "new", limit:limit, completion: completion)
case .Hot:
return getNewOrHotList(paginator, subreddit: subreddit, type: "hot", limit:limit, completion: completion)
}
}
/**
Get Links from all subreddits or user specified subreddit.
:param: paginator Paginator object for paging contents.
:param: subreddit Subreddit from which Links will be gotten.
:param: sort The type of sorting a list.
:param: TimeFilterWithin The type of filtering contents.
:param: limit The maximum number of comments to return. Default is 25.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getList(paginator:Paginator, subreddit:SubredditURLPath?, privateSortType:PrivateLinkSortBy, timeFilterWithin:TimeFilterWithin, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var parameter = ["t":timeFilterWithin.param];
parameter["limit"] = "\(limit)"
parameter["show"] = "all"
// parameter["sr_detail"] = "true"
parameter.update(paginator.parameters())
var path = privateSortType.path
if let subreddit = subreddit {
path = "\(subreddit.path)\(privateSortType.path).json"
}
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:path, parameter:parameter, method:"GET", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON
completion(result)
})
task.resume()
return task
}
/**
Get hot Links from all subreddits or user specified subreddit.
:param: paginator Paginator object for paging contents.
:param: subreddit Subreddit from which Links will be gotten.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getHotList(paginator:Paginator, subreddit:SubredditURLPath?, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
return getNewOrHotList(paginator, subreddit: subreddit, type: "hot", limit:limit, completion: completion)
}
/**
Get new Links from all subreddits or user specified subreddit.
:param: paginator Paginator object for paging contents.
:param: subreddit Subreddit from which Links will be gotten.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getNewList(paginator:Paginator, subreddit:SubredditURLPath?, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
return getNewOrHotList(paginator, subreddit: subreddit, type: "new", limit:limit, completion: completion)
}
/**
Get hot or new Links from all subreddits or user specified subreddit.
:param: paginator Paginator object for paging contents.
:param: subreddit Subreddit from which Links will be gotten.
:param: type "new" or "hot" as type.
:param: limit The maximum number of comments to return. Default is 25.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getNewOrHotList(paginator:Paginator, subreddit:SubredditURLPath?, type:String, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["limit"] = "\(limit)"
parameter["show"] = "all"
// parameter["sr_detail"] = "true"
parameter.update(paginator.parameters())
var path = type
if let subreddit = subreddit {
path = "\(subreddit.path)/\(type).json"
}
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:path, parameter:parameter, method:"GET", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON
completion(result)
})
task.resume()
return task
}
/**
The Serendipity content.
But this endpoints return invalid redirect URL...
I don't know how this URL should be handled....
:param: subreddit Specified subreddit to which you would like to get random link
:returns: Data task which requests search to reddit.com.
*/
public func getRandom(subreddit:Subreddit?, withoutLink:Bool = false, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
if let subreddit = subreddit {
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:subreddit.url + "/random", method:"GET", token:token)
if withoutLink {
return handleRequestFilteringLinkObject(request, completion: completion)
}
return handleRequest(request, completion: completion)
}
else {
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/random", method:"GET", token:token)
if withoutLink {
return handleRequestFilteringLinkObject(request, completion: completion)
}
return handleRequest(request, completion: completion)
}
}
// MARK: BDT does not cover following methods.
/**
Related page: performs a search using title of article as the search query.
:param: paginator Paginator object for paging contents.
:param: thing Thing object to which you want to obtain the contents that are related.
:param: limit The maximum number of comments to return. Default is 25.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
public func getRelatedArticles(paginator:Paginator, thing:Thing, withoutLink:Bool = false, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["limit"] = "\(limit)"
parameter["show"] = "all"
// parameter["sr_detail"] = "true"
parameter.update(paginator.parameters())
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/related/" + thing.id, parameter:parameter, method:"GET", token:token)
if withoutLink {
return handleRequestFilteringLinkObject(request, completion: completion)
}
return handleRequest(request, completion: completion)
}
/**
Return a list of other submissions of the same URL.
:param: paginator Paginator object for paging contents.
:param: thing Thing object by which you want to obtain the same URL is mentioned.
:param: limit The maximum number of comments to return. Default is 25.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
public func getDuplicatedArticles(paginator:Paginator, thing:Thing, withoutLink:Bool = false, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["limit"] = "\(limit)"
parameter["show"] = "all"
// parameter["sr_detail"] = "true"
parameter.update(paginator.parameters())
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/duplicates/" + thing.id, parameter:parameter, method:"GET", token:token)
if withoutLink {
return handleRequestFilteringLinkObject(request, completion: completion)
}
return handleRequest(request, completion: completion)
}
/**
Get a listing of links by fullname.
:params: links A list of Links
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
public func getLinksById(links:[Link], completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let fullnameList = links.map({ (link: Link) -> String in link.name })
var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/by_id/" + commaSeparatedStringFromList(fullnameList), method:"GET", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON
completion(result)
})
task.resume()
return task
}
} | f1622a24cbf5c66d32099179c60ab932 | 50.329787 | 219 | 0.686127 | false | false | false | false |
SteveBarnegren/SBAutoLayout | refs/heads/master | Example/SBAutoLayout/AutoLayoutActions.swift | mit | 1 | //
// AutoLayoutActions.swift
// SBAutoLayout
//
// Created by Steven Barnegren on 24/10/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
extension String {
func paddingMultiLineMethodSignatures() -> String {
var string = self
// Add padding to multi-line methods
let lines = string.components(separatedBy: "\n")
if lines.count > 1 {
string = lines[0]
let padding = lines[0].components(separatedBy: "(")[0].count + 1
var paddingString = String();
for _ in 0..<padding {
paddingString.append(" ")
}
for i in 1..<lines.count {
string.append("\n")
string.append(paddingString + lines[i])
}
}
return string
}
}
protocol AutoLayoutAction {
func name() -> String
func apply(superview: UIView, subviews: [UIView])
}
// MARK: - Pin Width / Height
struct PinWidth : AutoLayoutAction {
let viewNum: Int
let width: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinWidth(\(width))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinWidth(CGFloat(width))
}
}
struct PinHeight : AutoLayoutAction {
let viewNum: Int
let height: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinHeight(\(height))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinHeight(CGFloat(height))
}
}
struct PinAspectRatio : AutoLayoutAction {
let viewNum: Int
let width: Int
let height: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinAspectRatio(width: \(width), height: \(height))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinAspectRatio(width: CGFloat(width), height: CGFloat(height))
}
}
// MARK: - Pin To Superview edges
struct PinToSuperviewEdges : AutoLayoutAction {
let viewNum: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewEdges()"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewEdges()
}
}
struct PinToSuperviewEdgesTBLT : AutoLayoutAction {
let viewNum: Int
let top: Int
let bottom: Int
let leading: Int
let trailing: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewEdges(top: \(top), bottom: \(bottom), leading: \(leading), trailing: \(trailing))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewEdges(top: CGFloat(top),
bottom: CGFloat(bottom),
leading: CGFloat(leading),
trailing: CGFloat(trailing))
}
}
struct PinToSuperviewTop : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewTop(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewTop(CGFloat(margin))
}
}
struct PinToSuperviewBottom : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewBottom(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewBottom(CGFloat(margin))
}
}
struct PinToSuperviewLeft : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewLeft(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewLeft(CGFloat(margin))
}
}
struct PinToSuperviewRight : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewRight(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewRight(CGFloat(margin))
}
}
struct PinToSuperviewLeading : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewLeading(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewLeading(CGFloat(margin))
}
}
struct PinToSuperviewTrailing : AutoLayoutAction {
let viewNum: Int
let margin: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewTrailing(\(margin))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewTrailing(CGFloat(margin))
}
}
// MARK: - Pin to superview and strip
struct PinToSuperviewAsTopStrip : AutoLayoutAction {
let viewNum: Int
let height: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsTopStrip(height: \(height))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsTopStrip(height: CGFloat(height))
}
}
struct PinToSuperviewAsBottomStrip : AutoLayoutAction {
let viewNum: Int
let height: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsBottomStrip(height: \(height))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsBottomStrip(height: CGFloat(height))
}
}
struct PinToSuperviewAsLeftStrip : AutoLayoutAction {
let viewNum: Int
let width: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsLeftStrip(width: \(width))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsLeftStrip(width: CGFloat(width))
}
}
struct PinToSuperviewAsRightStrip : AutoLayoutAction {
let viewNum: Int
let width: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsRightStrip(width: \(width))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsRightStrip(width: CGFloat(width))
}
}
struct PinToSuperviewAsLeadingStrip : AutoLayoutAction {
let viewNum: Int
let width: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsLeadingStrip(width: \(width))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsLeadingStrip(width: CGFloat(width))
}
}
struct PinToSuperviewAsTrailingStrip : AutoLayoutAction {
let viewNum: Int
let width: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewAsTrailingStrip(width: \(width))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewAsTrailingStrip(width: CGFloat(width))
}
}
// MARK: - Pin to superview center
struct PinToSuperviewCenter : AutoLayoutAction {
let viewNum: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
return "\(viewName).pinToSuperviewCenter()"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinToSuperviewCenter()
}
}
struct PinToSuperviewCenterX : AutoLayoutAction {
let viewNum: Int
let offset: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
if let offset = offset {
return "\(viewName).pinToSuperviewCenterX(offset: \(offset))"
}
else{
return "\(viewName).pinToSuperviewCenterX()"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let offset = offset {
subviews[viewNum].pinToSuperviewCenterX(offset: CGFloat(offset))
}
else{
subviews[viewNum].pinToSuperviewCenterX()
}
}
}
struct PinToSuperviewCenterY : AutoLayoutAction {
let viewNum: Int
let offset: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
if let offset = offset {
return "\(viewName).pinToSuperviewCenterY(offset: \(offset))"
}
else{
return "\(viewName).pinToSuperviewCenterY()"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let offset = offset {
subviews[viewNum].pinToSuperviewCenterY(offset: CGFloat(offset))
}
else{
subviews[viewNum].pinToSuperviewCenterY()
}
}
}
// MARK: - Pin to other views
struct PinAboveView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinAboveView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinAboveView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinAboveView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinAboveView(subviews[otherViewNum])
}
}
}
struct PinBelowView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinBelowView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinBelowView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinBelowView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinBelowView(subviews[otherViewNum])
}
}
}
struct PinToLeftOfView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinToLeftOfView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinToLeftOfView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinToLeftOfView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinToLeftOfView(subviews[otherViewNum])
}
}
}
struct PinToRightOfView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinToRightOfView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinToRightOfView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinToRightOfView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinToRightOfView(subviews[otherViewNum])
}
}
}
struct PinLeadingToView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinLeadingToView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinLeadingToView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinLeadingToView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinLeadingToView(subviews[otherViewNum])
}
}
}
struct PinTrailingFromView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
let separation: Int?
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
if let separation = separation {
return "\(viewName).pinTrailingFromView(\(otherViewName), separation: \(separation))"
}
else{
return "\(viewName).pinTrailingFromView(\(otherViewName))"
}
}
func apply(superview: UIView, subviews: [UIView]) {
if let separation = separation {
subviews[viewNum].pinTrailingFromView(subviews[otherViewNum], separation: CGFloat(separation))
}
else{
subviews[viewNum].pinTrailingFromView(subviews[otherViewNum])
}
}
}
struct PinWidthToSameAsView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
return "\(viewName).pinWidthToSameAsView(\(otherViewName))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinWidthToSameAsView(subviews[otherViewNum])
}
}
struct PinHeightToSameAsView : AutoLayoutAction {
let viewNum: Int
let otherViewNum: Int
func name() -> String {
let viewName = ViewNamesAndColors.nameForView(number: viewNum)
let otherViewName = ViewNamesAndColors.nameForView(number: otherViewNum)
return "\(viewName).pinHeightToSameAsView(\(otherViewName))"
}
func apply(superview: UIView, subviews: [UIView]) {
subviews[viewNum].pinHeightToSameAsView(subviews[otherViewNum])
}
}
| 4ce74530e2aa1d45f4568c397400d8c2 | 26.818182 | 124 | 0.619584 | false | false | false | false |
abelondev/JSchemaForm | refs/heads/master | Example/Pods/Eureka/Source/Rows/SelectableRows/ListCheckRow.swift | apache-2.0 | 7 | //
// ListCheckRow.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
public class ListCheckCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func update() {
super.update()
accessoryType = row.value != nil ? .Checkmark : .None
editingAccessoryType = accessoryType
selectionStyle = .Default
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if row.isDisabled {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3)
selectionStyle = .None
}
else {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
public override func setup() {
super.setup()
accessoryType = .Checkmark
editingAccessoryType = accessoryType
}
public override func didSelect() {
row.deselect()
row.updateCell()
}
}
public final class ListCheckRow<T: Equatable>: Row<T, ListCheckCell<T>>, SelectableRowType, RowType {
public var selectableValue: T?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
} | d99845ace91830f276f140231e3b172c | 27.509434 | 101 | 0.612583 | false | false | false | false |
kripple/bti-watson | refs/heads/master | ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloud/LanguageTranslation/Models/TranslateRequest.swift | mit | 1 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import ObjectMapper
extension LanguageTranslation {
// A translation request
internal struct TranslateRequest: Mappable {
var modelID: String?
var source: String?
var target: String?
var text: [String]?
init(text: [String], modelID: String) {
self.text = text
self.modelID = modelID
}
init(text: [String], source: String, target: String) {
self.text = text
self.source = source
self.target = target
}
init?(_ map: Map) {}
mutating func mapping(map: Map) {
modelID <- map["model_id"]
source <- map["source"]
target <- map["target"]
text <- map["text"]
}
}
} | 4c856f86dbd1bf6eba3c293d0504de85 | 28.142857 | 75 | 0.597758 | false | false | false | false |
mssun/pass-ios | refs/heads/master | pass/Controllers/AboutTableViewController.swift | mit | 2 | //
// AboutTableViewController.swift
// pass
//
// Created by Mingshen Sun on 8/2/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import UIKit
class AboutTableViewController: BasicStaticTableViewController {
override func viewDidLoad() {
tableData = [
// section 0
[
[.title: "Website".localize(), .action: "link", .link: "https://github.com/mssun/pass-ios.git"],
[.title: "Help".localize(), .action: "link", .link: "https://github.com/mssun/passforios/wiki"],
[.title: "ContactDeveloper".localize(), .action: "link", .link: "mailto:[email protected]?subject=Pass%20for%20iOS"],
],
// section 1,
[
[.title: "OpenSourceComponents".localize(), .action: "segue", .link: "showOpenSourceComponentsSegue"],
[.title: "SpecialThanks".localize(), .action: "segue", .link: "showSpecialThanksSegue"],
],
]
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == tableData.count - 1 {
let view = UIView()
let footerLabel = UILabel(frame: CGRect(x: 8, y: 15, width: tableView.frame.width, height: 60))
footerLabel.numberOfLines = 0
footerLabel.text = "PassForIos".localize() + " \(Bundle.main.releaseVersionNumber!) (\(Bundle.main.buildVersionNumber!))"
footerLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
footerLabel.textColor = UIColor.lightGray
footerLabel.textAlignment = .center
view.addSubview(footerLabel)
return view
}
return nil
}
override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 {
return "Acknowledgements".localize().uppercased()
}
return nil
}
}
| 68b15522b121d14e3335b18c74b0a561 | 38.137255 | 145 | 0.595691 | false | false | false | false |
hibento/MessagePack.swift | refs/heads/master | MessagePack/MessagePack.swift | mit | 1 | /// The MessagePackValue enum encapsulates one of the following types: Nil, Bool, Int, UInt, Float, Double, String, Binary, Array, Map, and Extended.
public enum MessagePackValue {
case nothing
case bool(Swift.Bool)
case int(Int64)
case uint(UInt64)
case float(Swift.Float)
case double(Swift.Double)
case string(Swift.String)
case binary([UInt8])
case array([MessagePackValue])
case map([MessagePackValue : MessagePackValue])
case extended(Int8, [UInt8])
}
extension MessagePackValue: Hashable {
public var hashValue: Swift.Int {
switch self {
case .nothing: return 0
case .bool(let value): return value.hashValue
case .int(let value): return value.hashValue
case .uint(let value): return value.hashValue
case .float(let value): return value.hashValue
case .double(let value): return value.hashValue
case .string(let string): return string.hashValue
case .binary(let data): return data.count
case .array(let array): return array.count
case .map(let dict): return dict.count
case .extended(let type, let data): return type.hashValue ^ data.count
}
}
}
public func ==(lhs: MessagePackValue, rhs: MessagePackValue) -> Bool {
switch (lhs, rhs) {
case (.nothing, .nothing):
return true
case let (.bool(lhv), .bool(rhv)):
return lhv == rhv
case let (.int(lhv), .int(rhv)):
return lhv == rhv
case let (.uint(lhv), .uint(rhv)):
return lhv == rhv
case let (.int(lhv), .uint(rhv)):
return lhv >= 0 && numericCast(lhv) == rhv
case let (.uint(lhv), .int(rhv)):
return rhv >= 0 && lhv == numericCast(rhv)
case let (.float(lhv), .float(rhv)):
return lhv == rhv
case let (.double(lhv), .double(rhv)):
return lhv == rhv
case let (.string(lhv), .string(rhv)):
return lhv == rhv
case let (.binary(lhv), .binary(rhv)):
return lhv == rhv
case let (.array(lhv), .array(rhv)):
return lhv == rhv
case let (.map(lhv), .map(rhv)):
return lhv == rhv
case let (.extended(lht, lhb), .extended(rht, rhb)):
return lht == rht && lhb == rhb
default:
return false
}
}
extension MessagePackValue: CustomStringConvertible {
public var description: Swift.String {
switch self {
case .nothing:
return "Nil"
case let .bool(value):
return "Bool(\(value))"
case let .int(value):
return "Int(\(value))"
case let .uint(value):
return "UInt(\(value))"
case let .float(value):
return "Float(\(value))"
case let .double(value):
return "Double(\(value))"
case let .string(string):
return "String(\(string))"
case let .binary(data):
return "Data(\(dataDescription(data)))"
case let .array(array):
return "Array(\(array.description))"
case let .map(dict):
return "Map(\(dict.description))"
case let .extended(type, data):
return "Extended(\(type), \(dataDescription(data)))"
}
}
}
public enum MessagePackError: Error {
case insufficientData
case invalidData
}
func dataDescription(_ data: [UInt8]) -> String {
let bytes = data.map { byte -> String in
let prefix: String
if byte < 0x10 {
prefix = "0x0"
} else {
prefix = "0x"
}
return prefix + String(byte, radix: 16)
}
return "[" + bytes.joined(separator: ", ") + "]"
}
| cf9a36c57d6af73c78087628c970787e | 30.921053 | 149 | 0.576532 | false | false | false | false |
firebase/quickstart-ios | refs/heads/master | admob/AdMobExampleSwift/ViewController.swift | apache-2.0 | 1 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ViewController.swift
// AdMobExampleSwift
//
// [START firebase_banner_example]
import UIKit
import FirebaseCore
import GoogleMobileAds
/**
* AdMob ad unit IDs are not currently stored inside the google-services.plist file. Developers
* using AdMob can store them as custom values in another plist, or simply use constants. Note that
* these ad units are configured to return only test ads, and should not be used outside this sample.
*/
let kBannerAdUnitID = "ca-app-pub-3940256099942544/2934735716"
let kInterstitialAdUnitID = "ca-app-pub-3940256099942544/4411468910"
// Makes ViewController available to Objc classes.
@objc(ViewController)
class ViewController: UIViewController, GADFullScreenContentDelegate {
@IBOutlet var bannerView: GADBannerView!
var interstitial: GADInterstitialAd?
@IBOutlet var interstitialButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.adUnitID = kBannerAdUnitID
bannerView.rootViewController = self
bannerView.load(GADRequest())
// [END firebase_banner_example]
// [START firebase_interstitial_example]
createAndLoadInterstitial()
}
func createAndLoadInterstitial() {
GADInterstitialAd.load(
withAdUnitID: kInterstitialAdUnitID,
request: GADRequest()
) { ad, error in
if let error = error {
// For more fine-grained error handling, take a look at the values in GADErrorCode.
print("Error loading ad: \(error)")
}
self.interstitial = ad
self.interstitialButton.isEnabled = true
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
interstitialButton.isEnabled = false
createAndLoadInterstitial()
}
func ad(_ ad: GADFullScreenPresentingAd,
didFailToPresentFullScreenContentWithError error: Error) {
print("Error presenting ad: \(error)")
}
@IBAction func didTapInterstitialButton(_ sender: AnyObject) {
interstitial?.present(fromRootViewController: self)
}
}
// [END firebase_interstitial_example]
| 5a0ee97e09ba589d7ebaa47c04bbcb7e | 31.666667 | 101 | 0.736961 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/Home/Themes/Default/Renderers/PhotoRenderer.swift | mit | 1 | //
// PhotoRenderer.swift
// Accented
//
// Created by Tiangong You on 4/22/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
import SDWebImage
protocol PhotoRendererDelegate : NSObjectProtocol {
func photoRendererDidReceiveTap(_ renderer : PhotoRenderer)
}
class PhotoRenderer: UIView {
var imageView : UIImageView
weak var delegate : PhotoRendererDelegate?
required convenience init(coder aDecoder: NSCoder) {
self.init()
}
init(_ coder: NSCoder? = nil) {
imageView = UIImageView()
if let coder = coder {
super.init(coder: coder)!
}
else {
super.init(frame: CGRect.zero)
}
initialize()
}
private var photoModel : PhotoModel?
var photo : PhotoModel? {
get {
return photoModel
}
set(value) {
if value != photoModel {
photoModel = value
if photoModel != nil {
let url = PhotoRenderer.preferredImageUrl(photoModel)
if url != nil {
imageView.sd_setImage(with: url!)
} else {
imageView.image = nil
}
} else {
imageView.image = nil
}
}
}
}
// MARK: - Private
static func preferredImageUrl(_ photo : PhotoModel?) -> URL? {
guard photo != nil else { return nil }
if let url = photo!.imageUrls[.Large] {
return URL(string: url)
} else if let url = photo!.imageUrls[.Medium] {
return URL(string: url)
} else if let url = photo!.imageUrls[.Small] {
return URL(string: url)
} else {
return nil
}
}
func initialize() -> Void {
imageView.contentMode = .scaleAspectFill
self.addSubview(imageView)
// Gestures
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didReceiveTap(_:)))
self.addGestureRecognizer(tapGesture)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
}
@objc private func didReceiveTap(_ tap :UITapGestureRecognizer) {
delegate?.photoRendererDidReceiveTap(self)
}
}
| fbec0d3b3f8bcfbd235e4c8864941e9b | 24.8 | 99 | 0.528356 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | Classes/Watchdog.swift | mit | 3 | import Foundation
/// Class for logging excessive blocking on the main thread.
final public class Watchdog: NSObject {
fileprivate let pingThread: PingThread
@objc public static let defaultThreshold = 0.4
/// Convenience initializer that allows you to construct a `WatchDog` object with default behavior.
/// - parameter threshold: number of seconds that must pass to consider the main thread blocked.
/// - parameter strictMode: boolean value that stops the execution whenever the threshold is reached.
@objc public convenience init(threshold: Double = Watchdog.defaultThreshold, strictMode: Bool = false) {
let message = "👮 Main thread was blocked for " + String(format: "%.2f", threshold) + "s 👮"
self.init(threshold: threshold) {
if strictMode {
fatalError(message)
} else {
NSLog("%@", message)
}
}
}
/// Default initializer that allows you to construct a `WatchDog` object specifying a custom callback.
/// - parameter threshold: number of seconds that must pass to consider the main thread blocked.
/// - parameter watchdogFiredCallback: a callback that will be called when the the threshold is reached
@objc public init(threshold: Double = Watchdog.defaultThreshold, watchdogFiredCallback: @escaping () -> Void) {
self.pingThread = PingThread(threshold: threshold, handler: watchdogFiredCallback)
self.pingThread.start()
super.init()
}
deinit {
pingThread.cancel()
}
}
private final class PingThread: Thread {
fileprivate var pingTaskIsRunning: Bool {
get {
objc_sync_enter(pingTaskIsRunningLock)
let result = _pingTaskIsRunning;
objc_sync_exit(pingTaskIsRunningLock)
return result
}
set {
objc_sync_enter(pingTaskIsRunningLock)
_pingTaskIsRunning = newValue
objc_sync_exit(pingTaskIsRunningLock)
}
}
private var _pingTaskIsRunning = false
private let pingTaskIsRunningLock = NSObject()
fileprivate var semaphore = DispatchSemaphore(value: 0)
fileprivate let threshold: Double
fileprivate let handler: () -> Void
init(threshold: Double, handler: @escaping () -> Void) {
self.threshold = threshold
self.handler = handler
super.init()
self.name = "WatchDog"
}
override func main() {
while !isCancelled {
pingTaskIsRunning = true
DispatchQueue.main.async {
self.pingTaskIsRunning = false
self.semaphore.signal()
}
Thread.sleep(forTimeInterval: threshold)
if pingTaskIsRunning {
handler()
}
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
}
}
}
| fe6fda612ee15343e9fc45787705e336 | 34.670732 | 115 | 0.625641 | false | false | false | false |
Armanoide/ApiNetWork | refs/heads/master | DEMO/ApiNetWork/ViewController.swift | mit | 1 | //
// ViewController.swift
// ApiNetWork
//
// Created by norbert on 06/11/14.
// Copyright (c) 2014 norbert billa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
ApiNetWork.launchRequestDownloading("http://dealerdemusique.fr/wp-content/uploads/2012/11/flume-700x422.jpeg", didReceived: nil)
{ (response) -> Void in
if response.errors == nil {
if let data = response.getResponseData() {
self.imageView.image = UIImage(data: data)
}
} else if response.didFailNotConnectedToInternet() == true {
print("not connection to internet")
}
}
}
}
| 1368220348d1db8f1eec0d55e44d61a9 | 25.558824 | 136 | 0.54928 | false | false | false | false |
pawel-sp/VIPERModules | refs/heads/master | VIPERModules/VIPERModuleExtensions.swift | mit | 1 | //
// VIPERModuleExtensions.swift
// VIPERModules
//
// Created by Paweł Sporysz on 13.06.2017.
// Copyright © 2017 Paweł Sporysz. All rights reserved.
// https://github.com/pawel-sp/VIPERModules
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
public extension VIPERModuleBuilderInterface {
public static func module(
wireframe: WireframeInterface,
viewInterface: ViewInterace,
presenter: PresenterInterface,
eventHandler: EventHandlerInterface,
interactorDataSource: InteractorDataSourceInterface,
interactorEvents: InteractorEventsInterface,
interactorEventsDelegate: InteractorEventsDelegate,
dataManager: DataManagerInterface
) -> Module {
guard let viperWireframe = wireframe as? VIPERWireframeInterface else {
VIPERLogger.fatal("WireframeInterface needs to conform to protocol VIPERWireframeInterface")
}
guard let viperViewInteface = viewInterface as? VIPERViewInterface else {
VIPERLogger.fatal("ViewInterface needs to conform to protocol VIPERViewInterface")
}
guard let viperPresenter = presenter as? VIPERPresenterInterface else {
VIPERLogger.fatal("PresenterInterface needs to conform to protocol VIPERPresenterInterface")
}
guard let viperEventHandler = eventHandler as? VIPEREventHandlerInterface else {
VIPERLogger.fatal("EventHandlerInterface needs to conform to protocol VIPEREventHandlerInterface")
}
guard let viperInteractorEvents = interactorEvents as? VIPERInteractorEventsInterface else {
VIPERLogger.fatal("InteractorEventsInterface needs to conform to protocol VIPERInteractorEventsInterface")
}
guard let viperInteractorDelegate = interactorEventsDelegate as? VIPERInteractorEventsDelegate else {
VIPERLogger.fatal("InteractorEventsDelegate needs to conform to protocol VIPERInteractorEventsDelegate")
}
guard let viperInteractorDataSource = interactorDataSource as? VIPERInteractorDataSourceInterface else {
VIPERLogger.fatal("InteractorDataSourceInterface needs to conform to protocol VIPERInteractorDataSourceInterface")
}
guard let viperDataManager = dataManager as? VIPERDataManagerInterface else {
VIPERLogger.fatal("DataManagerInterface needs to conform to protocol VIPERDataManagerInterface")
}
viperWireframe._viewController = viperViewInteface as? UIViewController
viperViewInteface._presenter = viperPresenter
viperViewInteface._eventHandler = viperEventHandler
viperPresenter._viewInterface = viperViewInteface
viperPresenter._wireframe = viperWireframe
viperPresenter._interactorDataSource = viperInteractorDataSource
viperEventHandler._presenter = viperPresenter
viperEventHandler._interactorEvents = viperInteractorEvents
viperInteractorDataSource._dataManager = viperDataManager
viperInteractorEvents._delegate = viperInteractorDelegate
return (wireframe, presenter)
}
public static func module
<
W: VIPERWireframeInterface,
V: VIPERViewInterface,
P: VIPERPresenterInterface & VIPERInteractorEventsDelegate,
E: VIPEREventHandlerInterface,
I: VIPERInteractorEventsInterface & VIPERInteractorDataSourceInterface,
D: VIPERDataManagerInterface
>
(
wireframeType: W.Type,
viewInterfaceType: V.Type,
presenterType: P.Type,
eventHandlerType: E.Type,
interactorType: I.Type,
dataManagerType: D.Type,
wireframeInitBlock: ((W.Type) -> W)? = nil,
viewInterfaceInitBlock: ((V.Type) -> V)? = nil,
presenterInitBlock: ((P.Type) -> P)? = nil,
eventHandlerInitBlock: ((E.Type) -> E)? = nil,
interactorInitBlock: ((I.Type) -> I)? = nil,
dataManagerInitBlock: ((D.Type) -> D)? = nil
) -> Module {
let wireframe = wireframeInitBlock?(wireframeType) ?? wireframeType.init()
let viewInterface = viewInterfaceInitBlock?(viewInterfaceType) ?? wireframe.storyboard.instantiateViewController(withIdentifier: wireframe.viewControllerID) as! V
let presenter = presenterInitBlock?(presenterType) ?? presenterType.init()
let eventHandler = eventHandlerInitBlock?(eventHandlerType) ?? eventHandlerType.init()
let interactor = interactorInitBlock?(interactorType) ?? interactorType.init()
let dataManager = dataManagerInitBlock?(dataManagerType) ?? dataManagerType.init()
return module(
wireframe: wireframe as! WireframeInterface,
viewInterface: viewInterface as! ViewInterace,
presenter: presenter as! PresenterInterface,
eventHandler: eventHandler as! EventHandlerInterface,
interactorDataSource: interactor as! InteractorDataSourceInterface,
interactorEvents: interactor as! InteractorEventsInterface,
interactorEventsDelegate: presenter as! InteractorEventsDelegate,
dataManager: dataManager as! DataManagerInterface
)
}
}
| 19a6ed41136a0cf08385768192ec8dbf | 50.867769 | 170 | 0.716699 | false | false | false | false |
jpsim/Yams | refs/heads/main | Sources/Yams/Node.swift | mit | 1 | //
// Node.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
import Foundation
/// YAML Node.
public enum Node: Hashable {
/// Scalar node.
case scalar(Scalar)
/// Mapping node.
case mapping(Mapping)
/// Sequence node.
case sequence(Sequence)
}
extension Node {
/// Create a `Node.scalar` with a string, tag & scalar style.
///
/// - parameter string: String value for this node.
/// - parameter tag: Tag for this node.
/// - parameter style: Style to use when emitting this node.
public init(_ string: String, _ tag: Tag = .implicit, _ style: Scalar.Style = .any) {
self = .scalar(.init(string, tag, style))
}
/// Create a `Node.mapping` with a sequence of node pairs, tag & scalar style.
///
/// - parameter pairs: Pairs of nodes to use for this node.
/// - parameter tag: Tag for this node.
/// - parameter style: Style to use when emitting this node.
public init(_ pairs: [(Node, Node)], _ tag: Tag = .implicit, _ style: Mapping.Style = .any) {
self = .mapping(.init(pairs, tag, style))
}
/// Create a `Node.sequence` with a sequence of nodes, tag & scalar style.
///
/// - parameter nodes: Sequence of nodes to use for this node.
/// - parameter tag: Tag for this node.
/// - parameter style: Style to use when emitting this node.
public init(_ nodes: [Node], _ tag: Tag = .implicit, _ style: Sequence.Style = .any) {
self = .sequence(.init(nodes, tag, style))
}
}
// MARK: - Public Node Members
extension Node {
/// The tag for this node.
///
/// - note: Accessing this property causes the tag to be resolved by tag.resolver.
public var tag: Tag {
switch self {
case let .scalar(scalar): return scalar.resolvedTag
case let .mapping(mapping): return mapping.resolvedTag
case let .sequence(sequence): return sequence.resolvedTag
}
}
/// The location for this node.
public var mark: Mark? {
switch self {
case let .scalar(scalar): return scalar.mark
case let .mapping(mapping): return mapping.mark
case let .sequence(sequence): return sequence.mark
}
}
// MARK: - Typed accessor properties
/// This node as an `Any`, if convertible.
public var any: Any {
return tag.constructor.any(from: self)
}
/// This node as a `String`, if convertible.
public var string: String? {
return String.construct(from: self)
}
/// This node as a `Bool`, if convertible.
public var bool: Bool? {
return scalar.flatMap(Bool.construct)
}
/// This node as a `Double`, if convertible.
public var float: Double? {
return scalar.flatMap(Double.construct)
}
/// This node as an `NSNull`, if convertible.
public var null: NSNull? {
return scalar.flatMap(NSNull.construct)
}
/// This node as an `Int`, if convertible.
public var int: Int? {
return scalar.flatMap(Int.construct)
}
/// This node as a `Data`, if convertible.
public var binary: Data? {
return scalar.flatMap(Data.construct)
}
/// This node as a `Date`, if convertible.
public var timestamp: Date? {
return scalar.flatMap(Date.construct)
}
/// This node as a `UUID`, if convertible.
public var uuid: UUID? {
return scalar.flatMap(UUID.construct)
}
// MARK: Typed accessor methods
/// Returns this node mapped as an `Array<Node>`. If the node isn't a `Node.sequence`, the array will be
/// empty.
public func array() -> [Node] {
return sequence.map(Array.init) ?? []
}
/// Typed Array using type parameter: e.g. `array(of: String.self)`.
///
/// - parameter type: Type conforming to `ScalarConstructible`.
///
/// - returns: Array of `Type`.
public func array<Type: ScalarConstructible>(of type: Type.Type = Type.self) -> [Type] {
return sequence?.compactMap { $0.scalar.flatMap(type.construct) } ?? []
}
/// If the node is a `.sequence` or `.mapping`, set or get the specified `Node`.
/// If the node is a `.scalar`, this is a no-op.
public subscript(node: Node) -> Node? {
get {
switch self {
case .scalar: return nil
case let .mapping(mapping):
return mapping[node]
case let .sequence(sequence):
guard let index = node.int, sequence.indices ~= index else { return nil }
return sequence[index]
}
}
set {
guard let newValue = newValue else { return }
switch self {
case .scalar: return
case .mapping(var mapping):
mapping[node] = newValue
self = .mapping(mapping)
case .sequence(var sequence):
guard let index = node.int, sequence.indices ~= index else { return}
sequence[index] = newValue
self = .sequence(sequence)
}
}
}
/// If the node is a `.sequence` or `.mapping`, set or get the specified parameter's `Node`
/// representation.
/// If the node is a `.scalar`, this is a no-op.
public subscript(representable: NodeRepresentable) -> Node? {
get {
guard let node = try? representable.represented() else { return nil }
return self[node]
}
set {
guard let node = try? representable.represented() else { return }
self[node] = newValue
}
}
/// If the node is a `.sequence` or `.mapping`, set or get the specified string's `Node` representation.
/// If the node is a `.scalar`, this is a no-op.
public subscript(string: String) -> Node? {
get {
return self[Node(string, tag.copy(with: .implicit))]
}
set {
self[Node(string, tag.copy(with: .implicit))] = newValue
}
}
}
// MARK: Comparable
extension Node: Comparable {
/// Returns true if `lhs` is ordered before `rhs`.
///
/// - parameter lhs: The left hand side Node to compare.
/// - parameter rhs: The right hand side Node to compare.
///
/// - returns: True if `lhs` is ordered before `rhs`.
public static func < (lhs: Node, rhs: Node) -> Bool {
switch (lhs, rhs) {
case let (.scalar(lhs), .scalar(rhs)):
return lhs < rhs
case let (.mapping(lhs), .mapping(rhs)):
return lhs < rhs
case let (.sequence(lhs), .sequence(rhs)):
return lhs < rhs
default:
return false
}
}
}
extension Array where Element: Comparable {
static func < (lhs: Array, rhs: Array) -> Bool {
for (lhs, rhs) in zip(lhs, rhs) {
if lhs < rhs {
return true
} else if lhs > rhs {
return false
}
}
return lhs.count < rhs.count
}
}
// MARK: - ExpressibleBy*Literal
extension Node: ExpressibleByArrayLiteral {
/// Create a `Node.sequence` from an array literal of `Node`s.
public init(arrayLiteral elements: Node...) {
self = .sequence(.init(elements))
}
/// Create a `Node.sequence` from an array literal of `Node`s and a default `Style` to use for the array literal
public init(arrayLiteral elements: Node..., style: Sequence.Style) {
self = .sequence(.init(elements, .implicit, style))
}
}
extension Node: ExpressibleByDictionaryLiteral {
/// Create a `Node.mapping` from a dictionary literal of `Node`s.
public init(dictionaryLiteral elements: (Node, Node)...) {
self = Node(elements)
}
/// Create a `Node.mapping` from a dictionary literal of `Node`s and a default `Style` to use for the dictionary literal
public init(dictionaryLiteral elements: (Node, Node)..., style: Mapping.Style) {
self = Node(elements, .implicit, style)
}
}
extension Node: ExpressibleByFloatLiteral {
/// Create a `Node.scalar` from a float literal.
public init(floatLiteral value: Double) {
self.init(String(value), Tag(.float))
}
}
extension Node: ExpressibleByIntegerLiteral {
/// Create a `Node.scalar` from an integer literal.
public init(integerLiteral value: Int) {
self.init(String(value), Tag(.int))
}
}
extension Node: ExpressibleByStringLiteral {
/// Create a `Node.scalar` from a string literal.
public init(stringLiteral value: String) {
self.init(value)
}
}
// MARK: - internal
extension Node {
// MARK: Internal convenience accessors
var isMapping: Bool {
if case .mapping = self {
return true
}
return false
}
var isSequence: Bool {
if case .sequence = self {
return true
}
return false
}
}
| ecc2082b84fc805261c7699d92c2950b | 29.773973 | 124 | 0.5858 | false | false | false | false |
eneko/SourceDocs | refs/heads/main | Sources/SourceDocsCLI/GenerateCommand.swift | mit | 1 | //
// GenerateCommand.swift
// SourceDocs
//
// Created by Eneko Alonso on 10/19/17.
//
import Foundation
import ArgumentParser
import SourceDocsLib
extension SourceDocs {
struct GenerateCommand: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "generate",
abstract: "Generates the Markdown documentation"
)
@Flag(name: .shortAndLong,
help: "Generate documentation for all modules in a Swift package")
var allModules = false
@Option(help: "Generate documentation for Swift Package Manager module")
var spmModule: String?
@Option(help: "Generate documentation for a Swift module")
var moduleName: String?
@Option(help: "The text to begin links with")
var linkBeginning = SourceDocs.defaultLinkBeginning
@Option(help: "The text to end links with")
var linkEnding = SourceDocs.defaultLinkEnding
@Option(name: .shortAndLong, help: "Path to the input directory")
var inputFolder = FileManager.default.currentDirectoryPath
@Option(name: .shortAndLong, help: "Output directory to clean")
var outputFolder = SourceDocs.defaultOutputPath
@Option(help: "Access level to include in documentation [private, fileprivate, internal, public, open]")
var minACL = AccessLevel.public
@Flag(name: .shortAndLong, help: "Include the module name as part of the output folder path")
var moduleNamePath = false
@Flag(name: .shortAndLong, help: "Delete output folder before generating documentation")
var clean = false
@Flag(name: [.long, .customShort("l")],
help: "Put methods, properties and enum cases inside collapsible blocks")
var collapsible = false
@Flag(name: .shortAndLong,
help: "Generate a table of contents with properties and methods for each type")
var tableOfContents = false
@Argument(help: "List of arguments to pass to xcodebuild")
var xcodeArguments: [String] = []
@Flag(
name: .shortAndLong,
help: """
Generate documentation that is reproducible: only depends on the sources.
For example, this will avoid adding timestamps on the generated files.
"""
)
var reproducibleDocs = false
func run() throws {
let options = DocumentOptions(allModules: allModules, spmModule: spmModule, moduleName: moduleName,
linkBeginningText: linkBeginning, linkEndingText: linkEnding,
inputFolder: inputFolder, outputFolder: outputFolder,
minimumAccessLevel: minACL, includeModuleNameInPath: moduleNamePath,
clean: clean, collapsibleBlocks: collapsible,
tableOfContents: tableOfContents, xcodeArguments: xcodeArguments,
reproducibleDocs: reproducibleDocs)
try DocumentationGenerator(options: options).run()
}
}
}
extension AccessLevel: ExpressibleByArgument {}
| 2c02d7915b26edab55f30b712bbf909d | 37.702381 | 112 | 0.627499 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | KsApi/models/lenses/ActivityLenses.swift | apache-2.0 | 1 | import Foundation
import Prelude
extension Activity {
public enum lens {
public static let category = Lens<Activity, Activity.Category>(
view: { $0.category },
set: { Activity(
category: $0, comment: $1.comment, createdAt: $1.createdAt, id: $1.id,
memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user
) }
)
public static let comment = Lens<Activity, ActivityComment?>(
view: { $0.comment },
set: { Activity(
category: $1.category, comment: $0, createdAt: $1.createdAt, id: $1.id,
memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user
) }
)
public static let createdAt = Lens<Activity, TimeInterval>(
view: { $0.createdAt },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $0, id: $1.id,
memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user
) }
)
public static let id = Lens<Activity, Int>(
view: { $0.id },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $0,
memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user
) }
)
public static let memberData = Lens<Activity, MemberData>(
view: { $0.memberData },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id,
memberData: $0, project: $1.project, update: $1.update, user: $1.user
) }
)
public static let project = Lens<Activity, Project?>(
view: { $0.project },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id,
memberData: $1.memberData, project: $0, update: $1.update, user: $1.user
) }
)
public static let update = Lens<Activity, Update?>(
view: { $0.update },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id,
memberData: $1.memberData, project: $1.project, update: $0, user: $1.user
) }
)
public static let user = Lens<Activity, User?>(
view: { $0.user },
set: { Activity(
category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id,
memberData: $1.memberData, project: $1.project, update: $1.update, user: $0
) }
)
}
}
extension Lens where Whole == Activity, Part == Activity.MemberData {
public var amount: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.amount
}
public var backing: Lens<Activity, Backing?> {
return Activity.lens.memberData .. Activity.MemberData.lens.backing
}
public var oldAmount: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.oldAmount
}
public var oldRewardId: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.oldRewardId
}
public var newAmount: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.newAmount
}
public var newRewardId: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.newRewardId
}
public var rewardId: Lens<Activity, Int?> {
return Activity.lens.memberData .. Activity.MemberData.lens.rewardId
}
}
| b9b587e100804f47f3b6d005f812fb40 | 33.06 | 88 | 0.628009 | false | false | false | false |
C4Framework/C4iOS | refs/heads/master | C4/UI/Gradient.swift | mit | 4 | // Copyright © 2015 C4
//
// 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
///The Gradient class draws a color gradient over its background color, filling the shape of the view (including rounded corners).
public class Gradient: View {
class GradientView: UIView {
var gradientLayer: GradientLayer {
return self.layer as! GradientLayer // swiftlint:disable:this force_cast
}
override class var layerClass: AnyClass {
return GradientLayer.self
}
}
///The background layer of the receiver.
public var gradientLayer: GradientLayer {
return gradientView.gradientLayer
}
internal var gradientView: GradientView {
return view as! GradientView // swiftlint:disable:this force_cast
}
///An array of Color objects defining the color of each gradient stop. Animatable.
public var colors: [Color] {
get {
if let cgcolors = gradientLayer.colors as? [CGColor] {
return cgcolors.map({ Color($0) })
}
return [C4Blue, C4Pink]
} set {
assert(newValue.count >= 2, "colors must have at least 2 elements")
let cgcolors = newValue.map({ $0.cgColor })
self.gradientLayer.colors = cgcolors
}
}
///An optional array of Double values defining the location of each gradient stop. Animatable.
///
///Defaults to [0,1]
public var locations: [Double] {
get {
if let locations = gradientLayer.locations as? [Double] {
return locations
}
return []
} set {
let numbers = newValue.map({ NSNumber(value: $0) })
gradientLayer.locations = numbers
}
}
///The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
///
///Defaults to the top-left corner of the frame {0.0,0.0}
public var startPoint: Point {
get {
return Point(gradientLayer.startPoint)
} set {
gradientLayer.startPoint = CGPoint(newValue)
}
}
///The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
///
///Defaults to the top-right corner of the frame {1.0,0.0}
public var endPoint: Point {
get {
return Point(gradientLayer.endPoint)
} set {
gradientLayer.endPoint = CGPoint(newValue)
}
}
/// The current rotation value of the view. Animatable.
/// - returns: A Double value representing the cumulative rotation of the view, measured in Radians.
public override var rotation: Double {
get {
if let number = gradientLayer.value(forKeyPath: Layer.rotationKey) as? NSNumber {
return number.doubleValue
}
return 0.0
}
set {
gradientLayer.setValue(newValue, forKeyPath: Layer.rotationKey)
}
}
/// Initializes a new Gradient.
///
/// - parameter frame: A Rect that defines the frame for the gradient's view.
/// - parameter colors: An array of Color objects that define the gradient's colors. Defaults to [C4Blue, C4Purple].
/// - parameter locations: An array of Double values that define the location of each gradient stop. Defaults to [0,1]
public convenience override init(frame: Rect) {
self.init()
self.view = GradientView(frame: CGRect(frame))
self.colors = [C4Pink, C4Purple]
self.locations = [0, 1]
self.startPoint = Point()
self.endPoint = Point(0, 1)
}
public convenience init(copy original: Gradient) {
self.init(frame: original.frame)
self.colors = original.colors
self.locations = original.locations
copyViewStyle(original)
}
}
| 2745b9386fa0637bee0bb65321832114 | 36.906977 | 130 | 0.643967 | false | false | false | false |
iOSDevLog/iOSDevLog | refs/heads/master | 102. Psychologist Popover/Psychologist/DiagnosedHappinessViewController.swift | apache-2.0 | 2 | //
// DiagnosedHappinessViewController.swift
// Psychologist
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
class DiagnosedHappinessViewController : HappinessViewController, UIPopoverPresentationControllerDelegate
{
override var happiness: Int {
didSet {
diagnosticHistory += [happiness]
}
}
private let defaults = NSUserDefaults.standardUserDefaults()
var diagnosticHistory: [Int] {
get { return defaults.objectForKey(History.DefaultsKey) as? [Int] ?? [] }
set { defaults.setObject(newValue, forKey: History.DefaultsKey) }
}
private struct History {
static let SegueIdentifier = "Show Diagnostic History"
static let DefaultsKey = "DiagnosedHappinessViewController.History"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case History.SegueIdentifier:
if let tvc = segue.destinationViewController as? TextViewController {
if let ppc = tvc.popoverPresentationController {
ppc.delegate = self
}
tvc.text = "\(diagnosticHistory)"
}
default: break
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
| ee6e810b1773e374edfdc281ae05e97e | 31.44898 | 127 | 0.642767 | false | false | false | false |
jtauber/minilight-swift | refs/heads/master | Minilight/surfacepoint.swift | bsd-3-clause | 1 | //
// surfacepoint.swift
// Minilight
//
// Created by James Tauber on 6/15/14.
// Copyright (c) 2014 James Tauber. See LICENSE.
//
import Foundation
struct SurfacePoint {
let triangle: Triangle
let position: Vector
func getEmission(toPosition: Vector, outDirection: Vector, isSolidAngle: Bool) -> Vector {
let ray = toPosition - position
let distance2 = ray.dot(ray)
let cosArea = outDirection.dot(triangle.normal) * self.triangle.area
let solidAngle = isSolidAngle ? cosArea / max(distance2, 1e-6) : 1.0
return (cosArea > 0.0) ? triangle.emitivity * solidAngle : ZERO
}
func getReflection(#inDirection: Vector, inRadiance: Vector, outDirection: Vector) -> Vector {
let inDot = inDirection.dot(triangle.normal)
let outDot = outDirection.dot(triangle.normal)
return ((inDot < 0.0) ^ (outDot < 0.0)) ? ZERO : inRadiance * triangle.reflectivity * (abs(inDot) / M_PI)
}
func getNextDirection(inDirection: Vector) -> (Vector?, Vector) {
let reflectivityMean = triangle.reflectivity.dot(ONE) / 3.0
if drand48() < reflectivityMean {
let color = triangle.reflectivity * (1.0 / reflectivityMean)
let _2pr1 = M_PI * 2.0 * drand48()
let sr2 = sqrt(drand48())
let x = (cos(_2pr1) * sr2)
let y = (sin(_2pr1) * sr2)
let z = sqrt(1.0 - (sr2 * sr2))
var normal = triangle.normal
let tangent = triangle.tangent
if normal.dot(inDirection) < 0.0 {
normal = -normal
}
let outDirection = (tangent * x) + (normal.cross(tangent) * y) + (normal * z)
return (outDirection, color)
} else {
return (nil, ZERO)
}
}
}
| bb68693912495e47df490c9589bde889 | 30.766667 | 113 | 0.555089 | false | false | false | false |
kevinup7/S4HeaderExtensions | refs/heads/master | Sources/S4HeaderExtensions/MessageHeaders/Connection.swift | mit | 1 | import S4
extension Headers {
/**
The `Connection` header field allows the sender to indicate desired
control options for the current connection. In order to avoid
confusing downstream recipients, a proxy or gateway MUST remove or
replace any received connection options before forwarding the
message.
When a header field aside from `Connection` is used to supply control
information for or about the current connection, the sender MUST list
the corresponding field-name within the Connection header field. A
proxy or gateway MUST parse a received Connection header field before
a message is forwarded and, for each connection-option in this field,
remove any header field(s) from the message with the same name as the
connection-option, and then remove the Connection header field itself
(or replace it with the intermediary's own connection options for the
forwarded message).
## Example Headers
`Connection: keep-alive`
`Connection: upgrade`
## Examples
var request = Request()
request.headers.connection = [.keepAlive]
var response = Response()
response.headers.headers.connection = [.close]
- seealso: [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)
*/
public var connection: [ConnectionType]? {
get {
return ConnectionType.values(fromHeader: headers["Connection"])
}
set {
headers["Connection"] = newValue?.headerValue
}
}
}
/**
Values that can be used in the `Connection` header field.
- close: close `Connection` value
- keepAlive: keep-alive `Connection` value
- customHeader: Another header field that should be used in place of `Connection`
- note: When a header field aside from `Connection` is used to supply control
information for or about the current connection, the sender MUST list
the corresponding field-name within the Connection header field by using the
customHeader value.
- seealso: [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)
*/
public enum ConnectionType: Equatable {
case close
case keepAlive
case customHeader(CaseInsensitiveString)
}
extension ConnectionType: HeaderValueInitializable {
public init(headerValue: String) {
let lower = CaseInsensitiveString(headerValue)
switch lower {
case "close":
self = .close
case "keep-alive":
self = .keepAlive
default:
self = .customHeader(lower)
}
}
}
extension ConnectionType: HeaderValueRepresentable {
public var headerValue: String {
switch self {
case .close:
return "close"
case .keepAlive:
return "keep-alive"
case .customHeader(let headerName):
return headerName.description
}
}
}
public func ==(lhs: ConnectionType, rhs: ConnectionType) -> Bool {
return lhs.headerValue == rhs.headerValue
}
| 8c71e9c0e8a1f122870625e04a234c26 | 30.525253 | 85 | 0.652996 | false | false | false | false |
gmilos/swift | refs/heads/master | test/IRGen/local_types.swift | apache-2.0 | 1 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module %S/Inputs/local_types_helper.swift -o %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -parse-as-library %s -I %t > %t.ll
// RUN: %FileCheck %s < %t.ll
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.ll
// XFAIL: linux
import local_types_helper
public func singleFunc() {
// CHECK-DAG: @_TWVVF11local_types10singleFuncFT_T_L_16SingleFuncStruct = hidden constant
struct SingleFuncStruct {
let i: Int
}
}
public let singleClosure: () -> () = {
// CHECK-DAG: @_TWVVFIv11local_types13singleClosureFT_T_iU_FT_T_L_19SingleClosureStruct = hidden constant
struct SingleClosureStruct {
let i: Int
}
}
public struct PatternStruct {
public var singlePattern: Int = ({
// CHECK-DAG: @_TWVVFIvV11local_types13PatternStruct13singlePatternSiiU_FT_SiL_19SinglePatternStruct = hidden constant
struct SinglePatternStruct {
let i: Int
}
return 1
})()
}
public func singleDefaultArgument(i: Int = {
// CHECK-DAG: @_TWVVFIF11local_types21singleDefaultArgumentFT1iSi_T_A_U_FT_SiL_27SingleDefaultArgumentStruct = hidden constant
struct SingleDefaultArgumentStruct {
let i: Int
}
return 2
}()){
print(i)
}
#if COMPILED_OUT
public func topLevelIfConfig() {
class LocalClassDisabled {}
}
#else
public func topLevelIfConfig() {
// CHECK-DAG: @_TMmCF11local_types16topLevelIfConfigFT_T_L_17LocalClassEnabled = hidden global %objc_class
class LocalClassEnabled {}
}
#endif
public struct NominalIfConfig {
#if COMPILED_OUT
public func method() {
class LocalClassDisabled {}
}
#else
public func method() {
// CHECK-DAG: @_TMmCFV11local_types15NominalIfConfig6methodFT_T_L_17LocalClassEnabled = hidden global %objc_class
class LocalClassEnabled {}
}
#endif
}
public func innerIfConfig() {
#if COMPILED_OUT
class LocalClassDisabled {}
func inner() {
class LocalClassDisabled {}
}
#else
// CHECK-DAG: @_TMmCF11local_types13innerIfConfigFT_T_L_17LocalClassEnabled = hidden global %objc_class
class LocalClassEnabled {}
func inner() {
// CHECK-DAG: @_TMmCFF11local_types13innerIfConfigFT_T_L0_5innerFT_T_L_17LocalClassEnabled = hidden global %objc_class
class LocalClassEnabled {}
}
#endif
}
// CHECK-LABEL: define{{( protected)?}} void @_TF11local_types8callTestFT_T_() {{.*}} {
public func callTest() {
test()
} // CHECK: {{^[}]$}}
// NEGATIVE-NOT: LocalClassDisabled
| a35e200bed1f931a5ab08564cb123378 | 26.258065 | 128 | 0.70927 | false | true | false | false |
moyazi/SwiftDayList | refs/heads/master | SwiftDayList/Days/Day8/Day8MainViewController.swift | mit | 1 | //
// Day8MainViewController.swift
// SwiftDayList
//
// Created by leoo on 2017/6/28.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
import AVFoundation
class Day8MainViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
let gradientLayer = CAGradientLayer()
var timer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playMusicButtonDidTouch(_ sender: UIButton) {
let bgMusic = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Ecstasy", ofType: "mp3")!)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: bgMusic as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
catch let audioError as NSError {
print(audioError)
}
if (timer == nil) {
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(Day8MainViewController.randomColor), userInfo: nil, repeats: true)
}
let redValue = CGFloat(drand48())
let blueValue = CGFloat(drand48())
let greenValue = CGFloat(drand48())
self.view.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
//graditent color
gradientLayer.frame = view.bounds
let color1 = UIColor(white: 0.5, alpha: 0.2).cgColor as CGColor
let color2 = UIColor(red: 1.0, green: 0, blue: 0, alpha: 0.4).cgColor as CGColor
let color3 = UIColor(red: 0, green: 1, blue: 0, alpha: 0.3).cgColor as CGColor
let color4 = UIColor(red: 0, green: 0, blue: 1, alpha: 0.3).cgColor as CGColor
let color5 = UIColor(white: 0.4, alpha: 0.2).cgColor as CGColor
gradientLayer.colors = [color1, color2, color3, color4, color5]
gradientLayer.locations = [0.10, 0.30, 0.50, 0.70, 0.90]
gradientLayer.startPoint = CGPoint(x:0, y:0)
gradientLayer.endPoint = CGPoint(x:1, y:1)
self.view.layer.addSublayer(gradientLayer)
}
func randomColor() {
let redValue = CGFloat(drand48())
let blueValue = CGFloat(drand48())
let greenValue = CGFloat(drand48())
self.view.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
}
}
| 65e8c39f37a3c9183120ae0e96ffec8a | 34.653846 | 160 | 0.619921 | false | false | false | false |
chenhaigang888/CHGGridView_swift | refs/heads/master | SwiftTest/SwiftTest/ViewViewController.swift | apache-2.0 | 1 | //
// ViewViewController.swift
// SwiftTest
//
// Created by Hogan on 2017/2/23.
// Copyright © 2017年 Hogan. All rights reserved.
//
import UIKit
class ViewViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
override func viewDidLoad() {
super.viewDidLoad()
self.restoresFocusAfterTransition = true
// Do any additional setup after loading the view.
self.title = "CHGGridView Demo"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell:UITableViewCell = UITableViewCell()
let array:NSArray = ["CHGGridView基础控件Demo",
"CHGTabPageView控件展示Demo",
"菜单、广告、首页导航展示"]
cell.textLabel?.text = array.object(at: indexPath.row) as? String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
var vc:UIViewController!
if indexPath.row == 0 {
vc = MyViewController(nibName: "MyViewController", bundle: nil)
} else if indexPath.row == 1 {
vc = CHGTabPageDemoViewController(nibName: "CHGTabPageDemoViewController", bundle: nil)
} else {
vc = CHGGridMenuViewController(nibName: "CHGGridMenuViewController", bundle: nil)
}
let array:NSArray = ["CHGGridView基础控件Demo",
"CHGTabPageView控件展示Demo",
"菜单、广告、首页导航展示"]
vc.title = array.object(at: indexPath.row) as? String
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 73917d66f00103b667929f05575ea4bd | 32.377049 | 106 | 0.623281 | false | false | false | false |
hgl888/firefox-ios | refs/heads/master | Providers/Profile.swift | mpl-2.0 | 1 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
private let log = Logger.syncLogger
public let ProfileDidStartSyncingNotification = "ProfileDidStartSyncingNotification"
public let ProfileDidFinishSyncingNotification = "ProfileDidFinishSyncingNotification"
public let ProfileRemoteTabsSyncDelay: NSTimeInterval = 0.1
public protocol SyncManager {
var isSyncing: Bool { get }
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
func syncEverything() -> Success
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func applicationDidEnterBackground()
func applicationDidBecomeActive()
func onNewProfile()
func onRemovedAccount(account: FirefoxAccount?) -> Success
func onAddedAccount() -> Success
}
typealias EngineIdentifier = String
typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult
class ProfileFileAccessor: FileAccessor {
convenience init(profile: Profile) {
self.init(localName: profile.localName())
}
init(localName: String) {
let profileDirName = "profile.\(localName)"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: NSString
if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path as NSString
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString
}
super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName))
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init() {
profile = BrowserProfile(localName: "profile", app: nil)
}
func displaySentTabForURL(URL: NSURL, title: String) {
let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil)
self.profile.queue.addToQueue(item)
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
if let currentSettings = app.currentUserNotificationSettings() {
if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
if Logger.logPII {
log.info("Displaying notification for URL \(URL.absoluteString)")
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString)
notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title]
notification.alertAction = nil
notification.category = TabSendCategory
app.presentLocalNotificationNow(notification)
}
}
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> { get }
func shutdown()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
// Do we have an account at all?
func hasAccount() -> Bool
// Do we have an account that (as far as we know) is in a syncable state?
func hasSyncableAccount() -> Bool
func getAccount() -> FirefoxAccount?
func removeAccount()
func setAccount(account: FirefoxAccount)
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func sendItems(items: [ShareItem], toClients clients: [RemoteClient])
var syncManager: SyncManager { get }
}
public class BrowserProfile: Profile {
private let name: String
internal let files: FileAccessor
weak private var app: UIApplication?
/**
* N.B., BrowserProfile is used from our extensions, often via a pattern like
*
* BrowserProfile(…).foo.saveSomething(…)
*
* This can break if BrowserProfile's initializer does async work that
* subsequently — and asynchronously — expects the profile to stick around:
* see Bug 1218833. Be sure to only perform synchronous actions here.
*/
init(localName: String, app: UIApplication?) {
self.name = localName
self.files = ProfileFileAccessor(localName: localName)
self.app = app
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil)
notificationCenter.addObserver(self, selector: Selector("onProfileDidFinishSyncing:"), name: ProfileDidFinishSyncingNotification, object: nil)
notificationCenter.addObserver(self, selector: Selector("onPrivateDataClearedHistory:"), name: NotificationPrivateDataClearedHistory, object: nil)
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
KeychainWrapper.serviceName = baseBundleIdentifier
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
}
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account metadata.")
self.removeAccountMetadata()
self.syncManager.onNewProfile()
prefs.clearAll()
}
// Always start by needing invalidation.
// This is the same as self.history.setTopSitesNeedsInvalidation, but without the
// side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread.
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func shutdown() {
if self.dbCreated {
db.close()
}
if self.loginsDBCreated {
loginsDB.close()
}
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString {
// Only record local vists if the change notification originated from a non-private tab
if !(notification.userInfo!["isPrivate"] as? Bool ?? false) {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType)
history.addLocalVisit(visit)
}
history.setTopSitesNeedsInvalidation()
} else {
log.debug("Ignoring navigation.")
}
}
// These selectors run on which ever thread sent the notifications (not the main thread)
@objc
func onProfileDidFinishSyncing(notification: NSNotification) {
history.setTopSitesNeedsInvalidation()
}
@objc
func onPrivateDataClearedHistory(notification: NSNotification) {
// Immediately invalidate the top sites cache
history.refreshTopSitesCache()
}
deinit {
self.syncManager.endTimedSyncs()
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationOnLocationChange, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil)
}
func localName() -> String {
return name
}
lazy var queue: TabQueue = {
withExtendedLifetime(self.history) {
return SQLiteQueue(db: self.db)
}
}()
private var dbCreated = false
var db: BrowserDB {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "browser.db", files: self.files)
self.dbCreated = true
}
return Singleton.instance
}
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = {
return SQLiteHistory(db: self.db, prefs: self.prefs)!
}()
var favicons: Favicons {
return self.places
}
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> {
return self.places
}
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
withExtendedLifetime(self.places) {
return MergedSQLiteBookmarks(db: self.db)
}
}()
lazy var mirrorBookmarks: BookmarkMirrorStorage = {
// Yeah, this is lazy. Sorry.
return self.bookmarks as! MergedSQLiteBookmarks
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy var remoteClientsAndTabs: protocol<RemoteClientsAndTabs, ResettableSyncStorage, AccountRemovalDelegate> = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var syncManager: SyncManager = {
return BrowserSyncManager(profile: self)
}()
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandStoringSyncDelegate()
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
let commands = items.map { item in
SyncCommand.fromShareItem(item, withAction: "displayURI")
}
self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() }
}
lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = {
return SQLiteLogins(db: self.loginsDB)
}()
private lazy var loginsKey: String? = {
let key = "sqlcipher.key.logins.db"
if KeychainWrapper.hasValueForKey(key) {
return KeychainWrapper.stringForKey(key)
}
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
KeychainWrapper.setString(secret, forKey: key)
return secret
}()
private var loginsDBCreated = false
private lazy var loginsDB: BrowserDB = {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
self.loginsDBCreated = true
}
return Singleton.instance
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.None
}
func getAccount() -> FirefoxAccount? {
return account
}
func removeAccountMetadata() {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
KeychainWrapper.removeObjectForKey(self.name + ".account")
}
func removeAccount() {
let old = self.account
removeAccountMetadata()
self.account = nil
// Tell any observers that our account has changed.
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount(old)
// Deregister for remote notifications.
app?.unregisterForRemoteNotifications()
}
func setAccount(account: FirefoxAccount) {
KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account")
self.account = account
// register for notifications for the account
registerForNotifications()
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
self.syncManager.onAddedAccount()
}
func registerForNotifications() {
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.View.rawValue
viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
viewAction.activationMode = UIUserNotificationActivationMode.Foreground
viewAction.destructive = false
viewAction.authenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.Bookmark.rawValue
bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground
bookmarkAction.destructive = false
bookmarkAction.authenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.ReadingList.rawValue
readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
readingListAction.activationMode = UIUserNotificationActivationMode.Foreground
readingListAction.destructive = false
readingListAction.authenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default)
sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal)
app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory]))
app?.registerForRemoteNotifications()
}
// Extends NSObject so we can use timers.
class BrowserSyncManager: NSObject, SyncManager {
// We shouldn't live beyond our containing BrowserProfile, either in the main app or in
// an extension.
// But it's possible that we'll finish a side-effect sync after we've ditched the profile
// as a whole, so we hold on to our Prefs, potentially for a little while longer. This is
// safe as a strong reference, because there's no cycle.
unowned private let profile: BrowserProfile
private let prefs: Prefs
let FifteenMinutes = NSTimeInterval(60 * 15)
let OneMinute = NSTimeInterval(60)
private var syncTimer: NSTimer? = nil
private var backgrounded: Bool = true
func applicationDidEnterBackground() {
self.backgrounded = true
self.endTimedSyncs()
}
func applicationDidBecomeActive() {
self.backgrounded = false
self.beginTimedSyncs()
}
/**
* Locking is managed by withSyncInputs. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
var syncLock = OSSpinLock() {
didSet {
let notification = syncLock == 0 ? ProfileDidFinishSyncingNotification : ProfileDidStartSyncingNotification
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil))
}
}
// According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value
// and a locked lock is a non-zero value
var isSyncing: Bool {
return syncLock != 0
}
private func beginSyncing() -> Bool {
return OSSpinLockTry(&syncLock)
}
private func endSyncing() {
OSSpinLockUnlock(&syncLock)
}
init(profile: BrowserProfile) {
self.profile = profile
self.prefs = profile.prefs
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil)
center.addObserver(self, selector: "onFinishSyncing:", name: ProfileDidFinishSyncingNotification, object: nil)
}
deinit {
// Remove 'em all.
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil)
center.removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil)
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(notification: NSNotification) {
log.debug("Login did change.")
if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = NSDate.now()
// Give it a few seconds.
let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered)
// Trigger on the main queue. The bulk of the sync work runs in the background.
dispatch_after(when, dispatch_get_main_queue()) {
self.syncLogins()
}
}
}
@objc func onFinishSyncing(notification: NSNotification) {
self.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastSyncFinishTime)
}
var prefsForSync: Prefs {
return self.prefs.branch("sync")
}
func onAddedAccount() -> Success {
return self.syncEverything()
}
func locallyResetCollection(collection: String) -> Success {
switch collection {
case "bookmarks":
return MirroringBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks")
case "clients":
fallthrough
case "tabs":
// Because clients and tabs share storage, and thus we wipe data for both if we reset either,
// we reset the prefs for both at the same time.
return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync)
case "history":
return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history")
case "passwords":
return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords")
case "forms":
log.debug("Requested reset for forms, but this client doesn't sync them yet.")
return succeed()
case "addons":
log.debug("Requested reset for addons, but this client doesn't sync them.")
return succeed()
case "prefs":
log.debug("Requested reset for prefs, but this client doesn't sync them.")
return succeed()
default:
log.warning("Asked to reset collection \(collection), which we don't know about.")
return succeed()
}
}
func onNewProfile() {
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
func onRemovedAccount(account: FirefoxAccount?) -> Success {
let profile = self.profile
// Run these in order, because they might write to the same DB!
let remove = [
profile.history.onRemovedAccount,
profile.remoteClientsAndTabs.onRemovedAccount,
profile.logins.onRemovedAccount,
profile.bookmarks.onRemovedAccount,
]
let clearPrefs: () -> Success = {
withExtendedLifetime(self) {
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
return succeed()
}
return accumulate(remove) >>> clearPrefs
}
private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = Selector("syncOnTimer")
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info)
}
private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
}
private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing history to storage.")
let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs)
return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing logins to storage.")
let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs)
return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info)
}
private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Mirroring server bookmarks to storage.")
let bookmarksMirrorer = ready.synchronizer(MirroringBookmarksSynchronizer.self, delegate: delegate, prefs: prefs)
return bookmarksMirrorer.mirrorBookmarksToStorage(self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
func takeActionsOnEngineStateChanges<T: EngineStateChanges>(changes: T) -> Deferred<Maybe<T>> {
var needReset = Set<String>(changes.collectionsThatNeedLocalReset())
needReset.unionInPlace(changes.enginesDisabled())
needReset.unionInPlace(changes.enginesEnabled())
if needReset.isEmpty {
log.debug("No collections need reset. Moving on.")
return deferMaybe(changes)
}
// needReset needs at most one of clients and tabs, because we reset them
// both if either needs reset. This is strictly an optimization to avoid
// doing duplicate work.
if needReset.contains("clients") {
if needReset.remove("tabs") != nil {
log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.")
}
}
return walk(Array(needReset), f: self.locallyResetCollection)
>>> effect(changes.clearLocalCommands)
>>> always(changes)
}
/**
* Returns nil if there's no account.
*/
private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? {
if let account = profile.account {
if !beginSyncing() {
log.info("Not syncing \(label); already syncing something.")
return deferMaybe(AlreadySyncingError())
}
if let label = label {
log.info("Syncing \(label).")
}
let authState = account.syncAuthState
let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState)
let delegate = profile.getSyncDelegate()
let go = readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in
function(delegate, self.prefsForSync, ready)
}
// Always unlock when we're done.
go.upon({ res in self.endSyncing() })
return go
}
log.warning("No account; can't sync.")
return nil
}
/**
* Runs the single provided synchronization function and returns its status.
*/
private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult {
return self.withSyncInputs(label, function: function) ??
deferMaybe(.NotStarted(.NoAccount))
}
/**
* Runs each of the provided synchronization functions with the same inputs.
* Returns an array of IDs and SyncStatuses the same length as the input.
*/
private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
typealias Pair = (EngineIdentifier, SyncStatus)
let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in
let thunks = synchronizers.map { (i, f) in
return { () -> Deferred<Maybe<Pair>> in
log.debug("Syncing \(i)…")
return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) }
}
}
return accumulate(thunks)
}
return self.withSyncInputs(nil, function: combined) ??
deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) })
}
func syncEverything() -> Success {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate),
("logins", self.syncLoginsWithDelegate),
("bookmarks", self.mirrorBookmarksWithDelegate),
("history", self.syncHistoryWithDelegate)
) >>> succeed
}
@objc func syncOnTimer() {
log.debug("Running timed logins sync.")
// Note that we use .upon here rather than chaining with >>> precisely
// to allow us to sync subsequent engines regardless of earlier failures.
// We don't fork them in parallel because we want to limit perf impact
// due to background syncs, and because we're cautious about correctness.
self.syncLogins().upon { result in
if let success = result.successValue {
log.debug("Timed logins sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed logins sync failed. Reason: \(reason).")
}
log.debug("Running timed history sync.")
self.syncHistory().upon { result in
if let success = result.successValue {
log.debug("Timed history sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed history sync failed. Reason: \(reason).")
}
}
}
}
func syncClients() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("clients", function: syncClientsWithDelegate)
}
func syncClientsThenTabs() -> SyncResult {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate)
) >>== { statuses in
let tabsStatus = statuses[1].1
return deferMaybe(tabsStatus)
}
}
func syncLogins() -> SyncResult {
return self.sync("logins", function: syncLoginsWithDelegate)
}
func syncHistory() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("history", function: syncHistoryWithDelegate)
}
func mirrorBookmarks() -> SyncResult {
return self.sync("bookmarks", function: mirrorBookmarksWithDelegate)
}
/**
* Return a thunk that continues to return true so long as an ongoing sync
* should continue.
*/
func greenLight() -> () -> Bool {
let start = NSDate.now()
// Give it one minute to run before we stop.
let stopBy = start + OneMinuteInMilliseconds
log.debug("Checking green light. Backgrounded: \(self.backgrounded).")
return {
!self.backgrounded &&
NSDate.now() < stopBy &&
self.profile.hasSyncableAccount()
}
}
}
}
class AlreadySyncingError: MaybeErrorType {
var description: String {
return "Already syncing."
}
}
| 53f9b4e08dac0b9b7920eba64d18dbeb | 39.551181 | 238 | 0.642302 | false | false | false | false |
mkrisztian95/iOS | refs/heads/master | Tardis/SpeakersTableViewController.swift | apache-2.0 | 1 | //
// SpeakersTableViewController.swift
// Tardis
//
// Created by Molnar Kristian on 7/25/16.
// Copyright © 2016 Molnar Kristian. All rights reserved.
//
import UIKit
import Firebase
class SpeakersTableViewController: UITableViewController {
let ref = FIRDatabase.database().reference()
var speakersItemsArray:[[String:AnyObject]] = []
var contentHeight:CGFloat = 117.0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = APPConfig().appColor
let blogRef = ref.child("\(APPConfig().dataBaseRoot)/speakers")
blogRef.keepSynced(true)
let refHandle = blogRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
var postDict = snapshot.value as! [AnyObject]
print(postDict[0])
postDict.removeFirst()
for item in postDict {
if item is NSNull {
continue
}
let fetchedItem = item as! [String:AnyObject]
self.speakersItemsArray.append(fetchedItem)
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.speakersItemsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "row")
if indexPath.row % 2 != 0 {
let contentView = SpeakerTableViewItem(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.contentHeight))
contentView.setUp(self.speakersItemsArray[indexPath.row])
cell.addSubview(contentView)
cell.backgroundColor = UIColor.clearColor()
} else {
let contentView = SpeakerTableViewItemRight(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.contentHeight))
contentView.setUp(self.speakersItemsArray[indexPath.row])
cell.addSubview(contentView)
cell.backgroundColor = UIColor.clearColor()
}
APPConfig().setUpCellForUsage(cell)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.contentHeight
}
}
| 701514e41d9ba92401da018569585509 | 28.268817 | 139 | 0.687362 | false | false | false | false |
KimBin/DTCollectionViewManager | refs/heads/master | Example/Example/SectionsViewController.swift | mit | 1 | //
// SectionsViewController.swift
// DTCollectionViewManagerExample
//
// Created by Denys Telezhkin on 24.08.15.
// Copyright © 2015 Denys Telezhkin. All rights reserved.
//
import UIKit
import DTCollectionViewManager
func randomColor() -> UIColor {
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
class SectionsViewController: UIViewController, DTCollectionViewManageable, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView?
var sectionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
self.manager.startManagingWithDelegate(self)
self.manager.registerCellClass(SolidColorCollectionCell)
self.manager.registerHeaderClass(SimpleTextCollectionReusableView)
self.manager.registerFooterClass(SimpleTextCollectionReusableView)
(self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.headerReferenceSize = CGSize(width: 320, height: 50)
(self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.footerReferenceSize = CGSize(width: 320, height: 50)
self.addSection()
self.addSection()
}
@IBAction func addSection()
{
sectionNumber++
let section = self.manager.memoryStorage.sectionAtIndex(manager.memoryStorage.sections.count)
section.collectionHeaderModel = "Section \(sectionNumber) header"
section.collectionFooterModel = "Section \(sectionNumber) footer"
self.manager.memoryStorage.addItems([randomColor(), randomColor(), randomColor()], toSection: manager.memoryStorage.sections.count - 1)
}
@IBAction func removeSection(sender: AnyObject) {
if self.manager.memoryStorage.sections.count > 0 {
self.manager.memoryStorage.deleteSections(NSIndexSet(index: manager.memoryStorage.sections.count - 1))
}
}
@IBAction func moveSection(sender: AnyObject) {
if self.manager.memoryStorage.sections.count > 0 {
self.manager.memoryStorage.moveCollectionViewSection(self.manager.memoryStorage.sections.count - 1, toSection: 0)
}
}
}
| 21948be567beee193f49040ba993b51a | 38.566667 | 143 | 0.713564 | false | false | false | false |
volodg/iAsync.social | refs/heads/master | Pods/iAsync.utils/iAsync.utils/NSObject/NSObject+Ownerships.swift | mit | 1 | //
// NSObject+OnDeallocBlock.swift
// JUtils
//
// Created by Vladimir Gorbenko on 10.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
private var sharedObserversKey: Void?
public extension NSObject {
//do not autorelease returned value !
private func lazyOwnerships() -> NSMutableArray {
if let result = objc_getAssociatedObject(self, &sharedObserversKey) as? NSMutableArray {
return result
}
let result = NSMutableArray()
objc_setAssociatedObject(self,
&sharedObserversKey,
result,
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return result
}
private func ownerships() -> NSMutableArray? {
let result = objc_getAssociatedObject(self, &sharedObserversKey) as? NSMutableArray
return result
}
public func addOwnedObject(object: AnyObject) {
autoreleasepool {
self.lazyOwnerships().addObject(object)
}
}
func removeOwnedObject(object: AnyObject) {
autoreleasepool {
if let ownerships = self.ownerships() {
ownerships.removeObject(object)
}
}
}
func firstOwnedObjectMatch(predicate: (AnyObject) -> Bool) -> AnyObject? {
if let ownerships = self.ownerships()?.copy() as? [AnyObject] {
return firstMatch(ownerships, predicate)
}
return nil
}
}
| 1514a459b0ef3c3fbdf6de784814ddec | 24.983051 | 96 | 0.59426 | false | false | false | false |
mcdappdev/Vapor-Template | refs/heads/master | Sources/App/Controllers/Views/RegisterViewController.swift | mit | 1 | import Vapor
import BCrypt
import Flash
import MySQL
import Validation
final class RegisterViewController: RouteCollection {
private let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
func build(_ builder: RouteBuilder) throws {
builder.frontend(.noAuthed).group(RedirectMiddleware()) { build in
build.get("/register", handler: register)
build.post("/register", handler: handleRegisterPost)
}
}
//MARK: - GET /register
func register(_ req: Request) throws -> ResponseRepresentable {
return try view.make("register", for: req)
}
//MARK: - POST /register
func handleRegisterPost(_ req: Request) throws -> ResponseRepresentable {
guard let data = req.formURLEncoded else { throw Abort.badRequest }
//TODO: - Generic subscript upon Swift 4
guard let password = data[User.Field.password.rawValue]?.string else { throw Abort.badRequest }
guard let confirmPassword = data["confirmPassword"]?.string else { throw Abort.badRequest }
if password != confirmPassword {
return Response(redirect: "/register").flash(.error, "Passwords don't match")
}
var json = JSON(node: data)
try json.set(User.Field.password, try BCryptHasher().make(password.bytes).makeString())
do {
let user = try User(json: json)
try user.save()
try user.authenticate(req: req)
return Response(redirect: "/home")
} catch is MySQLError {
return Response(redirect: "/register").flash(.error, "Email already exists")
} catch is ValidationError {
return Response(redirect: "/register").flash(.error, "Email format is invalid")
} catch {
return Response(redirect: "/register").flash(.error, "Something went wrong")
}
}
}
| 902021c8925f6aa16496a6bccd144168 | 34.527273 | 103 | 0.61566 | false | false | false | false |
ajsutton/caltool | refs/heads/master | caltool/main.swift | apache-2.0 | 1 | /*
Copyright 2014 Adrian Sutton
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Cocoa
import Foundation
import EventKit
func printError(message : String) {
let stderr = NSFileHandle.fileHandleWithStandardError()
stderr.writeData("\(message)\n".dataUsingEncoding(NSUTF8StringEncoding))
}
var fetching = true
let dateHelper = DateHelper()
var startDate = dateHelper.startOfCurrentDay
var endDate = dateHelper.endOfCurrentDay
var formatter: OutputFormat = TextOutput(dateHelper: dateHelper)
var errorMessages = Array<String>()
let parser = JVArgumentParser()
var error : NSError?
let dateDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)
if let error = error {
printError("Failed to create date parser \(error.localizedDescription)")
}
error = nil
func parseDate(value: String, errorMessage: String) -> NSDate {
let range = NSMakeRange(0, (value as NSString).length)
let matches = dateDetector.matchesInString(value as NSString, options: nil, range: range)
if matches.count == 1 {
return matches[0].date
} else {
errorMessages += (errorMessage + ": " + value)
return NSDate()
}
}
parser.addOptionWithArgumentWithLongName("from") { value in startDate = parseDate(value, "Invalid from date") }
parser.addOptionWithArgumentWithLongName("to") { value in endDate = parseDate(value, "Invalid to date") }
parser.addOptionWithArgumentWithLongName("format") { value in
switch value as String {
case "json":
formatter = JsonOutput()
case "text":
formatter = TextOutput(dateHelper: dateHelper)
default:
errorMessages += "Unsupported format \(value)"
}
}
parser.parse(NSProcessInfo.processInfo().arguments, error: &error)
if let error = error {
errorMessages += error.localizedDescription!
}
if (errorMessages.isEmpty) {
let retriever = EventRetriever()
retriever.findEvents(startDate: startDate, endDate: endDate) { (events, error) in
if let events = events {
formatter.printEvents(events, to: NSFileHandle.fileHandleWithStandardOutput())
} else if let message = error?.localizedDescription? {
printError("ERROR: Access to calendar was refused: \(message)");
} else {
printError("ERROR: Access to calendar was refused.")
}
fetching = false
}
while (fetching) {
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.1))
}
} else {
for message in errorMessages {
printError(message)
}
printError("Usage caltool [--from <date>] [--to <date>] [--format (text|json)]")
} | 631e1f498c40a1039f9fb8e763e1bd1f | 34.202247 | 111 | 0.714879 | false | false | false | false |
kiwitechnologies/ServiceClientiOS | refs/heads/master | ServiceClient/ServiceClient/TSGServiceClient/Helper/TSGHelper+Download.swift | mit | 1 | //
// TSGHelper+Download.swift
// TSGServiceClient
//
// Created by Yogesh Bhatt on 20/06/16.
// Copyright © 2016 kiwitech. All rights reserved.
//
import Foundation
extension TSGHelper{
//MARK: A common method to download file
public class func downloadFile(path:String, param:NSDictionary?=nil,requestType:RequestType ,downloadType:DownloadType = DownloadType.PARALLEL, withApiTag apiTag:String?=nil,priority:Bool, downloadingPath:String?=nil,fileName:String?=nil, progressValue:(percentage:Float)->Void, success:(response:AnyObject) -> Void, failure:NSError->Void)
{
let obj = TSGHelper.sharedInstance
var objTag:String!
if apiTag != nil {
objTag = apiTag
} else {
objTag = "0"
}
let currentTime = NSDate.timeIntervalSinceReferenceDate()
if downloadType == .SEQUENTIAL
{
if priority == true {
obj.sequentialDownloadRequest.insertObject((RequestModel(url: path, bodyParam: param, type: requestType, state: true, apiTag: objTag, priority: priority, actionType: .DOWNLOAD, apiTime: "\(currentTime)", progressBlock: progressValue, successBlock: success, failureBlock: failure)), atIndex: 0)
} else {
obj.sequentialDownloadRequest.addObject(RequestModel(url: path, bodyParam: param, type: requestType, state: true, apiTag: objTag, priority: priority, actionType: .DOWNLOAD, apiTime: "\(currentTime)", progressBlock: progressValue, successBlock: success, failureBlock: failure))
}
if obj.sequentialDownloadRequest.count == 1 {
obj.download(path, param: param, requestType: requestType,downloadType:.SEQUENTIAL, withApiTag: objTag, progressValue: { (percentage) in
progressValue(percentage: percentage)
},fileName:fileName, downloadingPath: downloadingPath, success: { (response) in
success(response: response)
}, failure: { (error) in
failure(error)
})
} else {
let firstArrayObject:RequestModel = obj.sequentialDownloadRequest[0] as! RequestModel
if firstArrayObject.isRunning == false{
obj.download(path, param: param, requestType: requestType, downloadType: .SEQUENTIAL, withApiTag: objTag, progressValue: { (percentage) -> Void? in
progressValue(percentage: percentage)
},fileName:fileName, downloadingPath: downloadingPath, success: { (response) -> Void? in
success(response: response)
}, failure: { (error) -> Void? in
failure(error)
})
}
}
}
else
{
obj.download(path, param: param, requestType: requestType,downloadType:.PARALLEL, withApiTag: objTag, progressValue: { (percentage) in
progressValue(percentage: percentage)
},fileName:fileName, downloadingPath: downloadingPath, success: { (response) in
success(response: response)
}, failure: { (error) in
failure(error)
})
}
}
func download(path:String, param:NSDictionary?=nil,requestType:RequestType,downloadType:DownloadType, withApiTag apiTag:String, progressValue:(percentage:Float)->Void?,downloadingPath:String?=nil,fileName:String?=nil, success:(response:AnyObject) -> Void?, failure:NSError->Void?){
self.success = success
self.progress = progressValue
self.failure = failure
var localPath: NSURL?
let obj = TSGHelper.sharedInstance
var completeURL:String!
if TSGHelper.sharedInstance.baseUrl != nil {
completeURL = TSGHelper.sharedInstance.baseUrl + path
}
else {
completeURL = path
}
// let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
var requestMethod:Method = .GET
switch requestType {
case .GET:
requestMethod = .GET
case .POST:
requestMethod = .POST
case .DELETE:
requestMethod = .DELETE
case .PUT:
requestMethod = .PUT
}
var firstArrayObject:RequestModel!
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0])
var downloadPath:NSURL?// = documentsPath.URLByAppendingPathComponent("downloads123/DownloadsArticles")
if downloadingPath != nil {
downloadPath = documentsPath.URLByAppendingPathComponent(downloadingPath!)
var isDirectory: ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(downloadPath!.path!, isDirectory: &isDirectory) {
if(!isDirectory){
do {
try NSFileManager.defaultManager().createDirectoryAtPath(downloadPath!.path!, withIntermediateDirectories: true, attributes: nil)
}catch {
NSLog("Unable to create directory ")
}
}
}else{
do {
try NSFileManager.defaultManager().createDirectoryAtPath(downloadPath!.path!, withIntermediateDirectories: true, attributes: nil)
}catch {
NSLog("Unable to create directory ")
}
}
}
if downloadType == .SEQUENTIAL {
firstArrayObject = obj.sequentialDownloadRequest[0] as! RequestModel
}
obj.req = obj.manager.download(requestMethod, completeURL,parameters:param as? [String : AnyObject],
destination: { (temporaryURL, response) in
var pathComponent:String!
print("************************************")
print(downloadPath)
print("************************************")
if fileName == nil {
pathComponent = response.suggestedFilename
}
else {
pathComponent = fileName
}
if downloadPath == nil {
let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0]
localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
return localPath!
} else {
downloadPath = downloadPath!.URLByAppendingPathComponent(pathComponent!)
}
localPath = downloadPath
return localPath!
})
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let percentage = (Float(totalBytesRead) / Float(totalBytesExpectedToRead))
if downloadType == .SEQUENTIAL {
firstArrayObject.progressValue(percentage: percentage)
self.progress = firstArrayObject.progressValue
} else {
progressValue(percentage: percentage)
}
}
let currentTime = NSDate.timeIntervalSinceReferenceDate()
obj.req?.requestTAG = apiTag
obj.req?.requestTime = "\(currentTime)"
if downloadType == .PARALLEL {
obj.parallelDownloadRequest.addObject(obj.req!)
} else {
firstArrayObject.isRunning = true
firstArrayObject.requestObj = obj.req
firstArrayObject.apiTime = "\(currentTime)"
firstArrayObject.apiTag = apiTag
}
obj.req?.response(completionHandler: { _,response, _, error in
let requestTag = self.req?.requestTAG
if downloadType == .SEQUENTIAL {
let matchingObjects = TSGHelper.sharedInstance.sequentialDownloadRequest.filter({return ($0 as! RequestModel).apiTag == requestTag})
for object in matchingObjects {
for serialObj in self.sequentialDownloadRequest {
if (object as! RequestModel).apiTime == (serialObj as! RequestModel).apiTime{
self.sequentialDownloadRequest.removeObject(object)
}
}
}
self.hitAnotherDownloadRequest({ (percentage) in
progressValue(percentage: percentage)
}, success: { (response) in
success(response: localPath!)
}, failure: { (error) in
failure(error)
})
}
else {
let matchingObjects = TSGHelper.sharedInstance.parallelDownloadRequest.filter({return ($0 as! Request).requestTAG == requestTag})
self.parallelDownloadRequest.removeObject(matchingObjects)
for object in matchingObjects {
for parallelObj in self.parallelDownloadRequest {
if (object as! Request).requestTAG == (parallelObj as! Request).requestTAG{
self.parallelDownloadRequest.removeObject(object)
}
}
}
}
if response != nil {
if downloadType == .SEQUENTIAL {
if localPath == nil {
failure(error!)
}else {
firstArrayObject.successBlock(response: localPath!)
self.success = firstArrayObject.successBlock
}
}
else {
if localPath == nil {
failure(error!)
}else {
success(response: localPath!)
}
}
}
if error != nil {
if downloadType == .SEQUENTIAL {
firstArrayObject.failureBlock(error: error!)
self.failure = firstArrayObject.failureBlock
}
else {
failure(error!)
}
}
})
}
/**
Resume any pending downloads
- paramter url: Resume download url
- parameter success: Block to handle response
*/
public class func resumeDownloads(path:String, withApiTag apiTag:String?=nil,success:(Int64,totalBytes:Int64)-> Void)
{
let obj = TSGHelper.sharedInstance
obj.serviceCount = obj.serviceCount + 1
var actionID:String!
if apiTag != nil {
actionID = apiTag
} else {
actionID = "ResumeDownload"
}
let completeURL = TSGHelper.sharedInstance.baseUrl + path
let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
obj.req = obj.manager.download(.GET, completeURL, destination: destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
success(totalBytesRead,totalBytes:totalBytesExpectedToRead)
}
obj.req?.requestTAG = apiTag!
let currentTime = NSDate.timeIntervalSinceReferenceDate()
let failureBlock:(error:NSError)->()? = {error in return}
let progressValue:(percentage:Float)->()? = { percent in return}
let successBlock:(response:AnyObject)->()? = {success in return}
progressValue(percentage: 1.0)
obj.sequentialDownloadRequest.addObject(RequestModel(url: path, type: RequestType.GET, state: true, apiTag: actionID, priority: true, actionType: .DOWNLOAD, apiTime: "\(currentTime)", progressBlock: progressValue, successBlock: successBlock, failureBlock: failureBlock))
obj.req!.response { _, _, _, _ in
if let
resumeData = obj.req!.resumeData,
_ = NSString(data: resumeData, encoding: NSUTF8StringEncoding)
{
obj.serviceCount = obj.serviceCount - 1
} else {
obj.serviceCount = obj.serviceCount - 1
}
}
}
internal func hitAnotherDownloadRequest(progressValue:(percentage:Float)->(),success:(response:AnyObject)->(),failure:(NSError)->()){
if TSGHelper.sharedInstance.sequentialDownloadRequest.count > 0 {
let requestObj:RequestModel = sequentialDownloadRequest[0] as! RequestModel
self.download(requestObj.url,requestType:requestObj.type,downloadType:.SEQUENTIAL, withApiTag: requestObj.apiTag, progressValue: { (percentage) in
progressValue(percentage: percentage)
}, success: { (response) in
success(response: response)
}, failure: { (error) in
failure(error)
})
}
}
} | 8449102bda27bc38c09207bb2b17f8e4 | 39.919643 | 343 | 0.543934 | false | false | false | false |
CesarValiente/CursoSwiftUniMonterrey | refs/heads/master | week5/happiness/happiness/ViewController.swift | mit | 1 | //
// ViewController.swift
// happiness
//
// Created by Cesar Valiente on 27/12/15.
// Copyright © 2015 Cesar Valiente. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var possitiveMessage: UILabel!
let colors = Colors()
let phrases = Data()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func giveMeAMessage() {
possitiveMessage.text = phrases.getHappyPhrase()
let randomColor = colors.getRandomColor()
view.backgroundColor = randomColor
view.tintColor = randomColor
}
}
| f1a6cd3d96af4b0b48fc656bcfa16111 | 23.257143 | 80 | 0.666667 | false | false | false | false |
yuhaifei123/WeiBo_Swift | refs/heads/master | WeiBo_Swift/WeiBo_Swift/class/tool(工具)/PopviewController/Pop_PresentationController.swift | apache-2.0 | 1 | //
// Pop_ViewController.swift
// WeiBo_Swift
//
// Created by 虞海飞 on 2016/11/20.
// Copyright © 2016年 虞海飞. All rights reserved.
//
import UIKit
class Pop_ViewController: UIPresentationController {
///
///
/// - Parameters:
/// - presentedViewController: 被展示的控制器
/// - presentingViewController: 发起的控制器
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController);
print(presentedViewController);
}
/// 转场过程中,初始化方法
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews();
//containerView 容器视图
//presentedView 展示视图
presentedView?.frame = CGRect(x: 100, y: 60, width: 200, height: 200);
containerView?.insertSubview(backgroundView, at: 0);
}
//懒加载 背景试图
private lazy var backgroundView : UIView = {
let view = UIView();
view.backgroundColor = UIColor(white: 0.0, alpha: 0.2);
view.frame = UIScreen.main.bounds;//屏幕大小
//因为这个是 oc 的方法所以 #selector(self.closea)
let tap = UITapGestureRecognizer(target: self, action:#selector(self.closea));
view.addGestureRecognizer(tap)
return view;
}();
@objc private func closea(){
presentedViewController.dismiss(animated: true, completion: nil);
}
}
| d18a891d843441ff3957aa87a9ccbdec | 25.862069 | 118 | 0.627086 | false | false | false | false |
jaanus/NSProgressExample | refs/heads/master | NSProgressExample/ViewController.swift | mit | 1 | //
// ViewController.swift
// NSProgressExample
//
// Created by Jaanus Kase on 14/08/15.
// Copyright © 2015 Jaanus Kase. All rights reserved.
//
import Cocoa
private var progressObservationContext = 0
class ViewController: NSViewController, ProgressSheetInterface, ProgressSheetDelegate {
@IBOutlet weak var firstTaskDurationField: NSTextField!
@IBOutlet weak var secondTaskDurationField: NSTextField!
@IBOutlet weak var taskWeightSlider: NSSlider!
// Use progress reporting because the sheet asks for our progress
var progress = NSProgress()
var worker1, worker2: NSWindowController?
override func viewDidLoad() {
super.viewDidLoad()
// The child window controllers are long-lived.
worker1 = self.storyboard?.instantiateControllerWithIdentifier("Worker") as? NSWindowController
worker2 = self.storyboard?.instantiateControllerWithIdentifier("Worker") as? NSWindowController
}
@IBAction func start(sender: AnyObject) {
fixWindowPositions()
worker1?.showWindow(self)
worker2?.showWindow(self)
if let worker1 = worker1 as? ChildTaskInterface, worker2 = worker2 as? ChildTaskInterface {
// The actual durations for each task.
let firstTaskDuration = firstTaskDurationField.floatValue
let secondTaskDuration = secondTaskDurationField.floatValue
// The weights to give to each task in accounting for their progress.
let totalWeight = Int64(taskWeightSlider.maxValue)
let secondTaskWeight = Int64(taskWeightSlider.integerValue)
let firstTaskWeight = totalWeight - secondTaskWeight
progress = NSProgress(totalUnitCount: totalWeight)
progress.addObserver(self, forKeyPath: "completedUnitCount", options: [], context: &progressObservationContext)
progress.addObserver(self, forKeyPath: "cancelled", options: [], context: &progressObservationContext)
worker1.startTaskWithDuration(firstTaskDuration)
worker2.startTaskWithDuration(secondTaskDuration)
progress.addChild(worker1.progress, withPendingUnitCount: firstTaskWeight)
progress.addChild(worker2.progress, withPendingUnitCount: secondTaskWeight)
}
// Present the progress sheet with action buttons.
performSegueWithIdentifier("presentProgressSheet", sender: self)
}
// MARK: - ProgressSheetInterface
var sheetIsUserInteractive: Bool {
get {
return true
}
}
var sheetLabel: String? {
get {
return nil
}
}
// MARK: - ProgressSheetDelegate
func cancel() {
progress.cancel()
}
func pause() {
progress.pause()
}
func resume() {
progress.resume()
}
// MARK: - KVO
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &progressObservationContext else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
if let progress = object as? NSProgress {
if keyPath == "completedUnitCount" {
if progress.completedUnitCount >= progress.totalUnitCount {
// Work is done.
self.tasksFinished()
}
} else if keyPath == "cancelled" {
if progress.cancelled {
self.tasksFinished()
}
}
}
}
// MARK: - Utilities
func fixWindowPositions() {
let myWindowFrame = self.view.window?.frame as NSRect!
let x = CGRectGetMaxX(myWindowFrame!) + 32
let y = CGRectGetMaxY(myWindowFrame!)
worker1?.window?.setFrameTopLeftPoint(NSPoint(x: x, y: y))
let y2 = CGRectGetMinY((worker1!.window?.frame)!) - 32
worker2?.window?.setFrameTopLeftPoint(NSPoint(x: x, y: y2))
}
func tasksFinished() {
progress.removeObserver(self, forKeyPath: "cancelled")
progress.removeObserver(self, forKeyPath: "completedUnitCount")
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
self?.dismissViewController((self?.presentedViewControllers?.first)!)
}
}
}
| cbc99a674dd7340917160d81a5aceaaf | 29.710526 | 157 | 0.613967 | false | false | false | false |
kemalenver/SwiftHackerRank | refs/heads/master | Algorithms/Sorting.playground/Pages/Sorting - Quicksort In-Place.xcplaygroundpage/Contents.swift | mit | 1 | import Foundation
var inputs = ["7", "1 3 9 8 2 7 5"]
// Expected
//1 3 2 5 9 7 8
//1 2 3 5 9 7 8
//1 2 3 5 7 8 9
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
func swapArrayValues<T: Comparable>(_ array: inout [T], indexA: Int, indexB: Int) {
let temp = array[indexA]
array[indexA] = array[indexB]
array[indexB] = temp
}
func partition<T: Comparable>(_ array: inout [T], p: Int, r: Int) -> Int {
var q = p
for j in q ..< r {
if array[j] <= array[r] {
if array[j] <= array[r] {
swapArrayValues(&array, indexA: j, indexB: q)
q += 1
}
}
}
swapArrayValues(&array, indexA: r, indexB: q)
printArray(array)
return q
}
func quickSort<T: Comparable>(_ array: inout [T], p: Int, r: Int) {
if p < r {
let q = partition(&array, p: p, r: r)
quickSort(&array, p: p, r: q - 1)
quickSort(&array, p: q + 1, r: r)
}
}
func printArray<T>(_ array: [T]) {
for element in array {
print(element, separator: "", terminator: " ")
}
print()
}
let numberOfElements = readLine()
var inputArr = readLine()!.split(separator: " ").map { Int(String($0))! }
quickSort(&inputArr, p: 0, r: inputArr.count - 1)
| 0a84e4fdcb54848c954b3b27859ee793 | 18.216216 | 83 | 0.496484 | false | false | false | false |
rameshrathiakg/Loader3Pin | refs/heads/master | Source/Loader3Pin.swift | mit | 1 |
//
// RKActivityIndicator.swift
// AroundMe
//
// Created by Ramesh Rathi on 6/21/16.
// Copyright © 2016 ramesh. All rights reserved.
//
import UIKit
var KeyLoaderPin = "keyLoaderObject"
let LoaderColor = UIColor.gray
//Circular Layer
class CicularLayer: CALayer {
override func layoutSublayers() {
super.layoutSublayers()
self.backgroundColor = LoaderColor.cgColor
self.masksToBounds = true
self.borderWidth = 2.0
self.borderColor = LoaderColor.cgColor
self.cornerRadius = self.bounds.size.height/2.0
}
func addBlinkAnimation(_ level:CFTimeInterval) {
let fadeIn = CABasicAnimation.init(keyPath: "transform.scale")
fadeIn.beginTime = level
fadeIn.fromValue = 1.0
fadeIn.toValue = 0.1
fadeIn.duration = 1.0
let fadeOut = CABasicAnimation.init(keyPath: "transform.scale")
fadeOut.beginTime = level+1
fadeOut.fromValue = 0.1
fadeOut.toValue = 1.0
fadeOut.duration = 1.0
let group = CAAnimationGroup()
group.duration = 4.0
group.repeatCount = Float.infinity
group.animations = [fadeIn,fadeOut]
group.repeatDuration = 0
group.speed = 4.0
self.add(group, forKey: "scaleAnimation")
}
}
@IBDesignable
class Loader3Pin: UIView {
var isAnimating = true
override init(frame: CGRect) {
super.init(frame: frame)
self.baseInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.baseInit()
}
func baseInit() {
self.backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.createCircle()
}
override func layoutSubviews() {
super.layoutSubviews()
if isAnimating {
self.startAnimatingAndShow()
}
}
func startAnimatingAndShow() {
var index = 0;
if self.layer.sublayers != nil {
for circle in (self.layer.sublayers)! {
if circle is CicularLayer && circle.animation(forKey: "scaleAnimation") == nil {
(circle as! CicularLayer).addBlinkAnimation(Double(index))
}
index += 1
}
self.isHidden = false
}
isAnimating = true
}
func stopAnimatingAndHide() {
if self.layer.sublayers != nil {
for layer in (self.layer.sublayers)! {
layer.removeAnimation(forKey: "scaleAnimation")
}
}
self.isHidden = true
isAnimating = false
}
func createCircle() {
for count in -1...1 {
let circle = CicularLayer()
circle.frame = CGRect(x: self.bounds.size.width/2.0+CGFloat(count*12),
y: self.bounds.size.height/2.0-4, width: 8.0, height: 8.0)
circle.addBlinkAnimation(Double(count+1))
self.layer.addSublayer(circle)
}
}
}
/*
* To bind loader with any view
* - To show call show3PinLoader() method
*/
extension UIView {
func show3PinLoader() {
var loader = objc_getAssociatedObject(self, &KeyLoaderPin) as? Loader3Pin
if loader == nil {
loader = Loader3Pin.init(frame: CGRect(x: self.bounds.size.width/2.0-20,
y: self.bounds.size.height/2.0-20, width: 40, height: 40))
objc_setAssociatedObject(self, &KeyLoaderPin, loader, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.addSubview(loader!)
}
loader!.alpha = 0
loader!.center = self.center
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
loader!.alpha = 1
}) { (finished) in
loader!.startAnimatingAndShow()
loader!.frame = CGRect(x: self.bounds.size.width/2.0-20,
y: self.bounds.size.height/2.0-20, width: 40, height: 40)
}
}
func hide3PinLoader() {
let activity = objc_getAssociatedObject(self, &KeyLoaderPin)
if activity != nil {
let loader = activity as! Loader3Pin
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
loader.alpha = 0
}) { (finished) in
loader.stopAnimatingAndHide()
}
}
}
}
| 02535dface6c14be4dcb94d8a1bf50fb | 28.690789 | 123 | 0.571682 | false | false | false | false |
rev2k/Landmark-Locator | refs/heads/master | LandmarkLocator/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// LandmarkLocator
//
// Created by John Humphrys on 12/5/17.
// Copyright © 2017 John Humphrys. All rights reserved.
//
import UIKit
import CoreData
import Fabric
import TwitterKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Key used to access Twitter information
Twitter.sharedInstance().start(withConsumerKey: "Nu161AaVyiH6SJcbuc88rANTL", consumerSecret: "QWZ0Aqs0hv5VvZPVyOjSs3k1BuSEvBrTbFG9TMyvSe3upJYewq")
Fabric.with([Twitter.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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "LandmarkLocator")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| a1c0225963f979d110513bd3460224c8 | 47.534653 | 285 | 0.688902 | false | false | false | false |
gunterhager/AnnotationClustering | refs/heads/master | AnnotationClustering/Code/QuadTree/QuadTreeNode.swift | mit | 1 | //
// QuadTreeNode.swift
// AnnotationClustering
//
// Created by Gunter Hager on 07.06.16.
// Copyright © 2016 Gunter Hager. All rights reserved.
//
import Foundation
import MapKit
private let nodeCapacity = 8
class QuadTreeNode {
var boundingBox: BoundingBox
var northEast: QuadTreeNode? = nil
var northWest: QuadTreeNode? = nil
var southEast: QuadTreeNode? = nil
var southWest: QuadTreeNode? = nil
var annotations:[MKAnnotation] = []
// MARK: - Initializers
init(x: Double, y: Double, width: Double, height: Double) {
boundingBox = BoundingBox(x: x, y: y, width: width, height: height)
}
init(boundingBox box: BoundingBox) {
boundingBox = box
}
// Annotations
var allAnnotations: [MKAnnotation] {
var result = annotations
result += northEast?.allAnnotations ?? []
result += northWest?.allAnnotations ?? []
result += southEast?.allAnnotations ?? []
result += southWest?.allAnnotations ?? []
return result
}
func addAnnotation(_ annotation: MKAnnotation) -> Bool {
guard boundingBox.contains(annotation.coordinate) else {
return false
}
if (annotations.count < nodeCapacity) || boundingBox.isSmall {
annotations.append(annotation)
return true
}
subdivide()
if let node = northEast, node.addAnnotation(annotation) == true {
return true
}
if let node = northWest, node.addAnnotation(annotation) == true {
return true
}
if let node = southEast, node.addAnnotation(annotation) == true {
return true
}
if let node = southWest, node.addAnnotation(annotation) == true {
return true
}
return false
}
func forEachAnnotationInBox(_ box: BoundingBox, block: (MKAnnotation) -> Void) {
guard boundingBox.intersects(box) else { return }
for annotation in annotations {
if box.contains(annotation.coordinate) {
block(annotation)
}
}
if isLeaf() {
return
}
if let node = northEast {
node.forEachAnnotationInBox(box, block: block)
}
if let node = northWest {
node.forEachAnnotationInBox(box, block: block)
}
if let node = southEast {
node.forEachAnnotationInBox(box, block: block)
}
if let node = southWest {
node.forEachAnnotationInBox(box, block: block)
}
}
// MARK: - Private
fileprivate func isLeaf() -> Bool {
return (northEast == nil) ? true : false
}
fileprivate func subdivide() {
guard isLeaf() == true else { return }
let w2 = boundingBox.width / 2.0
let xMid = boundingBox.x + w2
let h2 = boundingBox.height / 2.0
let yMid = boundingBox.y + h2
northEast = QuadTreeNode(x: xMid, y: boundingBox.y, width: w2, height: h2)
northWest = QuadTreeNode(x: boundingBox.x, y: boundingBox.y, width: w2, height: h2)
southEast = QuadTreeNode(x: xMid, y: yMid, width: w2, height: h2)
southWest = QuadTreeNode(x: boundingBox.x, y: yMid, width: w2, height: h2)
}
}
| 8690a0bd0d6e31b7c876ee28aca15a7b | 27.349593 | 91 | 0.557786 | false | false | false | false |
AnarchyTools/atfoundation | refs/heads/master | src/string/split.swift | apache-2.0 | 1 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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.
/// String splitting and joining
public extension String {
/// Join array of strings by using a delimiter string
///
/// - parameter parts: parts to join
/// - parameter delimiter: delimiter to insert
/// - returns: combined string
public static func join(parts: [String], delimiter: String) -> String {
// calculate final length to reserve space
var len = 0
for part in parts {
len += part.characters.count + delimiter.characters.count
}
// reserve space
var result = ""
result.reserveCapacity(len)
// join string parts
for (idx, part) in parts.enumerated() {
result.append(part)
if idx < parts.count - 1 {
result.append(delimiter)
}
}
return result
}
/// Join array of strings by using a delimiter character
///
/// - parameter parts: parts to join
/// - parameter delimiter: delimiter to insert
/// - returns: combined string
public static func join(parts: [String], delimiter: Character) -> String {
// calculate final length to reserve space
var len = 0
for part in parts {
len += part.characters.count + 1
}
// reserve space
var result = ""
result.reserveCapacity(len)
// join string parts
for (idx, part) in parts.enumerated() {
result.append(part)
if idx < parts.count - 1 {
result.append(delimiter)
}
}
return result
}
/// Join array of strings
///
/// - parameter parts: parts to join
/// - returns: combined string
public static func join(parts: [String]) -> String {
// calculate final length to reserve space
var len = 0
for part in parts {
len += part.characters.count
}
// reserve space
var result = ""
result.reserveCapacity(len)
// join string parts
for part in parts {
result.append(part)
}
return result
}
/// Split string into array by using delimiter character
///
/// - parameter character: delimiter to use
/// - parameter maxSplits: (optional) maximum number of splits, set to 0 to allow unlimited splits
/// - returns: array with string components
public func split(character: Character, maxSplits: Int = 0) -> [String] {
var result = [String]()
var current = ""
// reserve space, heuristic
current.reserveCapacity(self.characters.count / 2)
// create generator and add current char to `current`
var i = 0
var gen = self.characters.makeIterator()
while let c = gen.next() {
if c == character && ((maxSplits == 0) || (result.count < maxSplits)) {
// if we don't have reached maxSplits or maxSplits is zero and the current character is a delimiter
// append the current string to the result array and start over
result.append(current)
current = ""
// reserve space again, heuristic
current.reserveCapacity(self.characters.count - i)
} else {
current.append(c)
}
i += 1
}
result.append(current)
return result
}
/// Split string into array by using delimiter string
///
/// - parameter string: delimiter to use
/// - parameter maxSplits: (optional) maximum number of splits, set to 0 to allow unlimited splits
/// - returns: array with string components
public func split(string: String, maxSplits: Int = 0) -> [String] {
var result = [String]()
let positions = self.positions(string: string)
var start = self.startIndex
for idx in positions {
result.append(self.subString(range: start..<idx))
start = self.index(idx, offsetBy: string.characters.count)
if result.count == maxSplits {
break
}
}
result.append(self.subString(range: start..<self.endIndex))
return result
}
} | d2b0d4dd9e0e4853f79b1f6912ca4bb1 | 31.059603 | 115 | 0.58595 | false | false | false | false |
javalnanda/JNDropDownMenu | refs/heads/master | Example/JNDropDownSample/ViewController.swift | mit | 1 | //
// ViewController.swift
// JNDropDownSample
//
// Created by Javal Nanda on 4/27/17.
// Copyright © 2017 Javal Nanda. All rights reserved.
//
import UIKit
import JNDropDownMenu
class ViewController: UIViewController {
var columnOneArray = ["All","C1-1","C1-2","C1-3","C1-4","C1-5"]
var columnTwoArray = ["All","C2-1","C2-2"]
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "JNDropDownMenu"
// pass custom width or set as nil to use screen width
let menu = JNDropDownMenu(origin: CGPoint(x: 0, y: 64), height: 40, width: self.view.frame.size.width)
/*
// Customize if required
menu.textColor = UIColor.red
menu.cellBgColor = UIColor.green
menu.arrowColor = UIColor.black
menu.cellSelectionColor = UIColor.white
menu.textFont = UIFont.boldSystemFont(ofSize: 16.0)
menu.updateColumnTitleOnSelection = false
menu.arrowPostion = .Left
*/
menu.datasource = self
menu.delegate = self
self.view.addSubview(menu)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: JNDropDownMenuDelegate, JNDropDownMenuDataSource {
func numberOfColumns(in menu: JNDropDownMenu) -> NSInteger {
return 2
}
/* Override this method if you want to provide custom column title other than the first object of column array
func titleFor(column: Int, menu: JNDropDownMenu) -> String {
return "Column \(column)"
}*/
func numberOfRows(in column: NSInteger, for forMenu: JNDropDownMenu) -> Int {
switch column {
case 0:
return columnOneArray.count
case 1:
return columnTwoArray.count
default:
return 0
}
}
func titleForRow(at indexPath: JNIndexPath, for forMenu: JNDropDownMenu) -> String {
switch indexPath.column {
case 0:
return columnOneArray[indexPath.row]
case 1:
return columnTwoArray[indexPath.row]
default:
return ""
}
}
func didSelectRow(at indexPath: JNIndexPath, for forMenu: JNDropDownMenu) {
var str = ""
switch indexPath.column {
case 0:
str = columnOneArray[indexPath.row]
break
case 1:
str = columnTwoArray[indexPath.row]
break
default:
str = ""
}
label.text = str + " selected"
}
}
| 3991b6f0921833f96aca61fd72a690f6 | 27.21875 | 114 | 0.594684 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.