repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
tuzaiz/ConciseCore
|
refs/heads/dev
|
src/CCDB.swift
|
mit
|
1
|
//
// TZDB.swift
// CloudCore
//
// Created by Henry on 2014/11/22.
// Copyright (c) 2014年 Cloudbay. All rights reserved.
//
import Foundation
import CoreData
class CCDB : NSObject {
lazy var context : NSManagedObjectContext = {
var ctx = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
ctx.parentContext = ConciseCore.managedObjectContext
return ctx
}()
internal func save() {
var error : NSError?
self.context.performBlockAndWait { () -> Void in
self.saveToContext(&error)
}
}
internal func save(completion:((NSError?) -> Void)?) {
self.context.performBlock { () -> Void in
var error : NSError?
self.context.performBlock({ () -> Void in
self.saveToContext(&error)
if let complete = completion {
complete(error)
}
})
}
}
private func saveToContext(error:NSErrorPointer?) {
var error : NSError?
self.context.save(&error)
var ctx : NSManagedObjectContext? = self.context
while var context = ctx?.parentContext {
context.save(&error)
ctx = context
}
}
}
|
e2c1ad14ba7be001785275f56bf2565f
| 26.851064 | 124 | 0.580275 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
stdlib/private/OSLog/OSLogPrivacy.swift
|
apache-2.0
|
14
|
//===----------------- OSLogPrivacy.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file defines the APIs for specifying privacy in the log messages and also
// the logic for encoding them in the byte buffer passed to the libtrace library.
/// Privacy options for specifying privacy level of the interpolated expressions
/// in the string interpolations passed to the log APIs.
@frozen
public struct OSLogPrivacy {
@usableFromInline
internal enum PrivacyOption {
case `private`
case `public`
case auto
}
public enum Mask {
/// Applies a salted hashing transformation to an interpolated value to redact it in the logs.
///
/// Its purpose is to permit the correlation of identical values across multiple log lines
/// without revealing the value itself.
case hash
case none
}
@usableFromInline
internal var privacy: PrivacyOption
@usableFromInline
internal var mask: Mask
@_transparent
@usableFromInline
internal init(privacy: PrivacyOption, mask: Mask) {
self.privacy = privacy
self.mask = mask
}
/// Sets the privacy level of an interpolated value to public.
///
/// When the privacy level is public, the value will be displayed
/// normally without any redaction in the logs.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var `public`: OSLogPrivacy {
OSLogPrivacy(privacy: .public, mask: .none)
}
/// Sets the privacy level of an interpolated value to private.
///
/// When the privacy level is private, the value will be redacted in the logs,
/// subject to the privacy configuration of the logging system.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var `private`: OSLogPrivacy {
OSLogPrivacy(privacy: .private, mask: .none)
}
/// Sets the privacy level of an interpolated value to private and
/// applies a `mask` to the interpolated value to redacted it.
///
/// When the privacy level is private, the value will be redacted in the logs,
/// subject to the privacy configuration of the logging system.
///
/// If the value need not be redacted in the logs, its full value is captured as normal.
/// Otherwise (i.e. if the value would be redacted) the `mask` is applied to
/// the argument value and the result of the transformation is recorded instead.
///
/// - Parameters:
/// - mask: Mask to use with the privacy option.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static func `private`(mask: Mask) -> OSLogPrivacy {
OSLogPrivacy(privacy: .private, mask: mask)
}
/// Auto-infers a privacy level for an interpolated value.
///
/// The system will automatically decide whether the value should
/// be captured fully in the logs or should be redacted.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var auto: OSLogPrivacy {
OSLogPrivacy(privacy: .auto, mask: .none)
}
/// Auto-infers a privacy level for an interpolated value and applies a `mask`
/// to the interpolated value to redacted it when necessary.
///
/// The system will automatically decide whether the value should
/// be captured fully in the logs or should be redacted.
/// If the value need not be redacted in the logs, its full value is captured as normal.
/// Otherwise (i.e. if the value would be redacted) the `mask` is applied to
/// the argument value and the result of the transformation is recorded instead.
///
/// - Parameters:
/// - mask: Mask to use with the privacy option.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static func auto(mask: Mask) -> OSLogPrivacy {
OSLogPrivacy(privacy: .auto, mask: mask)
}
/// Return an argument flag for the privacy option., as defined by the
/// os_log ABI, which occupies four least significant bits of the first byte of the
/// argument header. The first two bits are used to indicate privacy and
/// the other two are reserved.
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var argumentFlag: UInt8 {
switch privacy {
case .private:
return 0x1
case .public:
return 0x2
default:
return 0
}
}
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var isAtleastPrivate: Bool {
switch privacy {
case .public:
return false
case .auto:
return false
default:
return true
}
}
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var needsPrivacySpecifier: Bool {
if case .hash = mask {
return true
}
switch privacy {
case .auto:
return false
default:
return true
}
}
@inlinable
@_transparent
internal var hasMask: Bool {
if case .hash = mask {
return true
}
return false
}
/// A 64-bit value obtained by interpreting the mask name as a little-endian unsigned
/// integer.
@inlinable
@_transparent
internal var maskValue: UInt64 {
// Return the value of
// 'h' | 'a' << 8 | 's' << 16 | 'h' << 24 which equals
// 104 | (97 << 8) | (115 << 16) | (104 << 24)
1752392040
}
/// Return an os log format specifier for this `privacy` level. The
/// format specifier goes within curly braces e.g. %{private} in the format
/// string passed to the os log ABI.
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var privacySpecifier: String? {
let hasMask = self.hasMask
var isAuto = false
if case .auto = privacy {
isAuto = true
}
if isAuto, !hasMask {
return nil
}
var specifier: String
switch privacy {
case .public:
specifier = "public"
case .private:
specifier = "private"
default:
specifier = ""
}
if hasMask {
if !isAuto {
specifier += ","
}
specifier += "mask.hash"
}
return specifier
}
}
|
ec9f6403fdcb9a17e07a2c0c4064bf45
| 28.281818 | 98 | 0.65756 | false | false | false | false |
apple/swift-syntax
|
refs/heads/main
|
Sources/SwiftParser/Types.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_spi(RawSyntax) import SwiftSyntax
extension Parser {
/// Parse a type.
///
/// Grammar
/// =======
///
/// type → function-type
/// type → array-type
/// type → dictionary-type
/// type → type-identifier
/// type → tuple-type
/// type → optional-type
/// type → implicitly-unwrapped-optional-type
/// type → protocol-composition-type
/// type → opaque-type
/// type → metatype-type
/// type → any-type
/// type → self-type
/// type → '(' type ')'
@_spi(RawSyntax)
public mutating func parseType(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax {
let type = self.parseTypeScalar(misplacedSpecifiers: misplacedSpecifiers)
// Parse pack expansion 'T...'.
if self.currentToken.isEllipsis {
let ellipsis = self.consumeAnyToken(remapping: .ellipsis)
return RawTypeSyntax(
RawPackExpansionTypeSyntax(
patternType: type,
ellipsis: ellipsis,
arena: self.arena))
}
return type
}
mutating func parseTypeScalar(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax {
let (specifier, unexpectedBeforeAttrList, attrList) = self.parseTypeAttributeList(misplacedSpecifiers: misplacedSpecifiers)
var base = RawTypeSyntax(self.parseSimpleOrCompositionType())
if self.lookahead().isAtFunctionTypeArrow() {
let firstEffect = self.parseEffectsSpecifier()
let secondEffect = self.parseEffectsSpecifier()
let (unexpectedBeforeArrow, arrow) = self.expect(.arrow)
let returnTy = self.parseType()
let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
let leftParen: RawTokenSyntax
let unexpectedBetweenLeftParenAndElements: RawUnexpectedNodesSyntax?
let arguments: RawTupleTypeElementListSyntax
let unexpectedBetweenElementsAndRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax
if let input = base.as(RawTupleTypeSyntax.self) {
unexpectedBeforeLeftParen = input.unexpectedBeforeLeftParen
leftParen = input.leftParen
unexpectedBetweenLeftParenAndElements = input.unexpectedBetweenLeftParenAndElements
arguments = input.elements
unexpectedBetweenElementsAndRightParen = input.unexpectedBetweenElementsAndRightParen
rightParen = input.rightParen
} else {
unexpectedBeforeLeftParen = nil
leftParen = RawTokenSyntax(missing: .leftParen, arena: self.arena)
unexpectedBetweenLeftParenAndElements = nil
arguments = RawTupleTypeElementListSyntax(elements: [
RawTupleTypeElementSyntax(
inOut: nil, name: nil, secondName: nil, colon: nil, type: base,
ellipsis: nil, initializer: nil, trailingComma: nil, arena: self.arena)
], arena: self.arena)
unexpectedBetweenElementsAndRightParen = nil
rightParen = RawTokenSyntax(missing: .rightParen, arena: self.arena)
}
base = RawTypeSyntax(RawFunctionTypeSyntax(
unexpectedBeforeLeftParen,
leftParen: leftParen,
unexpectedBetweenLeftParenAndElements,
arguments: arguments,
unexpectedBetweenElementsAndRightParen,
rightParen: rightParen,
asyncKeyword: firstEffect,
throwsOrRethrowsKeyword: secondEffect,
unexpectedBeforeArrow,
arrow: arrow,
returnType: returnTy,
arena: self.arena))
}
if unexpectedBeforeAttrList != nil || specifier != nil || attrList != nil {
return RawTypeSyntax(RawAttributedTypeSyntax(
specifier: specifier,
unexpectedBeforeAttrList,
attributes: attrList,
baseType: base, arena: self.arena))
} else {
return RawTypeSyntax(base)
}
}
/// Parse a protocol composition involving at least one element.
///
/// Grammar
/// =======
///
/// type-identifier → type-name generic-argument-clause? | type-name generic-argument-clause? '.' type-identifier
/// type-name → identifier
///
/// protocol-composition-type → type-identifier '&' protocol-composition-continuation
/// protocol-composition-continuation → type-identifier | protocol-composition-type
@_spi(RawSyntax)
public mutating func parseSimpleOrCompositionType() -> RawTypeSyntax {
let someOrAny = self.consume(ifAny: [], contextualKeywords: ["some", "any"])
var base = self.parseSimpleType()
guard self.atContextualPunctuator("&") else {
if let someOrAny = someOrAny {
return RawTypeSyntax(RawConstrainedSugarTypeSyntax(
someOrAnySpecifier: someOrAny, baseType: base, arena: self.arena))
} else {
return base
}
}
var elements = [RawCompositionTypeElementSyntax]()
if let firstAmpersand = self.consumeIfContextualPunctuator("&") {
elements.append(RawCompositionTypeElementSyntax(
type: base, ampersand: firstAmpersand, arena: self.arena))
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let elementType = self.parseSimpleType()
keepGoing = self.consumeIfContextualPunctuator("&")
elements.append(RawCompositionTypeElementSyntax(
type: elementType,
ampersand: keepGoing,
arena: self.arena
))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
base = RawTypeSyntax(RawCompositionTypeSyntax(
elements: RawCompositionTypeElementListSyntax(elements: elements, arena: self.arena),
arena: self.arena))
}
if let someOrAny = someOrAny {
return RawTypeSyntax(RawConstrainedSugarTypeSyntax(
someOrAnySpecifier: someOrAny, baseType: base, arena: self.arena))
} else {
return base
}
}
/// Parse a "simple" type
///
/// Grammar
/// =======
///
/// type → type-identifier
/// type → tuple-type
/// type → array-type
/// type → dictionary-type
/// type → metatype-type
///
/// metatype-type → type '.' 'Type' | type '.' 'Protocol'
@_spi(RawSyntax)
public mutating func parseSimpleType(
stopAtFirstPeriod: Bool = false
) -> RawTypeSyntax {
var base: RawTypeSyntax
switch self.currentToken.tokenKind {
case .capitalSelfKeyword,
.anyKeyword,
.identifier:
base = self.parseTypeIdentifier(stopAtFirstPeriod: stopAtFirstPeriod)
case .leftParen:
base = RawTypeSyntax(self.parseTupleTypeBody())
case .leftSquareBracket:
base = RawTypeSyntax(self.parseCollectionType())
case .wildcardKeyword:
base = RawTypeSyntax(self.parsePlaceholderType())
default:
return RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena))
}
// '.Type', '.Protocol', '?', '!', and '[]' still leave us with type-simple.
var loopCondition = LoopProgressCondition()
while loopCondition.evaluate(currentToken) {
if !stopAtFirstPeriod, let (period, type) = self.consume(
if: { [.period, .prefixPeriod].contains($0.tokenKind) },
followedBy: { $0.isContextualKeyword(["Type", "Protocol"])}
) {
base = RawTypeSyntax(RawMetatypeTypeSyntax(
baseType: base, period: period, typeOrProtocol: type, arena: self.arena))
continue
}
if !self.currentToken.isAtStartOfLine {
if self.currentToken.isOptionalToken {
base = RawTypeSyntax(self.parseOptionalType(base))
continue
}
if self.currentToken.isImplicitlyUnwrappedOptionalToken {
base = RawTypeSyntax(self.parseImplicitlyUnwrappedOptionalType(base))
continue
}
}
break
}
return base
}
/// Parse an optional type.
///
/// Grammar
/// =======
///
/// optional-type → type '?'
@_spi(RawSyntax)
public mutating func parseOptionalType(_ base: RawTypeSyntax) -> RawOptionalTypeSyntax {
let (unexpectedBeforeMark, mark) = self.expect(.postfixQuestionMark)
return RawOptionalTypeSyntax(
wrappedType: base,
unexpectedBeforeMark,
questionMark: mark,
arena: self.arena
)
}
/// Parse an optional type.
///
/// Grammar
/// =======
///
/// implicitly-unwrapped-optional-type → type '!'
@_spi(RawSyntax)
public mutating func parseImplicitlyUnwrappedOptionalType(_ base: RawTypeSyntax) -> RawImplicitlyUnwrappedOptionalTypeSyntax {
let (unexpectedBeforeMark, mark) = self.expect(.exclamationMark)
return RawImplicitlyUnwrappedOptionalTypeSyntax(
wrappedType: base,
unexpectedBeforeMark,
exclamationMark: mark,
arena: self.arena
)
}
@_spi(RawSyntax)
public mutating func parseTypeIdentifier(
stopAtFirstPeriod: Bool = false
) -> RawTypeSyntax {
if self.at(.anyKeyword) && !stopAtFirstPeriod {
return RawTypeSyntax(self.parseAnyType())
}
var result: RawTypeSyntax?
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let (name, _) = self.parseDeclNameRef()
let generics: RawGenericArgumentClauseSyntax?
if self.atContextualPunctuator("<") {
generics = self.parseGenericArguments()
} else {
generics = nil
}
if let keepGoing = keepGoing {
result = RawTypeSyntax(RawMemberTypeIdentifierSyntax(
baseType: result!,
period: keepGoing,
name: name,
genericArgumentClause: generics,
arena: self.arena))
} else {
result = RawTypeSyntax(RawSimpleTypeIdentifierSyntax(
name: name, genericArgumentClause: generics, arena: self.arena))
}
if stopAtFirstPeriod {
keepGoing = nil
} else {
keepGoing = self.consume(if: .period) ?? self.consume(if: .prefixPeriod)
}
} while keepGoing != nil && loopProgress.evaluate(currentToken)
return result!
}
/// Parse the existential `Any` type.
///
/// Grammar
/// =======
///
/// any-type → Any
@_spi(RawSyntax)
public mutating func parseAnyType() -> RawSimpleTypeIdentifierSyntax {
let (unexpectedBeforeName, name) = self.expect(.anyKeyword)
return RawSimpleTypeIdentifierSyntax(
unexpectedBeforeName,
name: name,
genericArgumentClause: nil,
arena: self.arena
)
}
/// Parse a type placeholder.
///
/// Grammar
/// =======
///
/// placeholder-type → wildcard
@_spi(RawSyntax)
public mutating func parsePlaceholderType() -> RawSimpleTypeIdentifierSyntax {
let (unexpectedBeforeName, name) = self.expect(.wildcardKeyword)
// FIXME: Need a better syntax node than this
return RawSimpleTypeIdentifierSyntax(
unexpectedBeforeName,
name: name,
genericArgumentClause: nil,
arena: self.arena
)
}
}
extension Parser {
/// Parse the generic arguments applied to a type.
///
/// Grammar
/// =======
///
/// generic-argument-clause → '<' generic-argument-list '>'
/// generic-argument-list → generic-argument | generic-argument ',' generic-argument-list
/// generic-argument → type
@_spi(RawSyntax)
public mutating func parseGenericArguments() -> RawGenericArgumentClauseSyntax {
assert(self.currentToken.starts(with: "<"))
let langle = self.consumePrefix("<", as: .leftAngle)
var arguments = [RawGenericArgumentSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let type = self.parseType()
if arguments.isEmpty && type.is(RawMissingTypeSyntax.self) {
break
}
keepGoing = self.consume(if: .comma)
arguments.append(RawGenericArgumentSyntax(
argumentType: type, trailingComma: keepGoing, arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
let rangle: RawTokenSyntax
if self.currentToken.starts(with: ">") {
rangle = self.consumePrefix(">", as: .rightAngle)
} else {
rangle = RawTokenSyntax(missing: .rightAngle, arena: self.arena)
}
let args: RawGenericArgumentListSyntax
if arguments.isEmpty && rangle.isMissing {
args = RawGenericArgumentListSyntax(elements: [], arena: self.arena)
} else {
args = RawGenericArgumentListSyntax(elements: arguments, arena: self.arena)
}
return RawGenericArgumentClauseSyntax(
leftAngleBracket: langle,
arguments: args,
rightAngleBracket: rangle,
arena: self.arena)
}
}
extension Parser {
/// Parse a tuple type.
///
/// Grammar
/// =======
///
/// tuple-type → '(' ')' | '(' tuple-type-element ',' tuple-type-element-list ')'
/// tuple-type-element-list → tuple-type-element | tuple-type-element ',' tuple-type-element-list
/// tuple-type-element → element-name type-annotation | type
/// element-name → identifier
@_spi(RawSyntax)
public mutating func parseTupleTypeBody() -> RawTupleTypeSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawTupleTypeSyntax(
remainingTokens,
leftParen: missingToken(.leftParen),
elements: RawTupleTypeElementListSyntax(elements: [], arena: self.arena),
rightParen: missingToken(.rightParen),
arena: self.arena
)
}
let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen)
var elements = [RawTupleTypeElementSyntax]()
do {
var keepGoing = true
var loopProgress = LoopProgressCondition()
while !self.at(any: [.eof, .rightParen]) && keepGoing && loopProgress.evaluate(currentToken) {
let unexpectedBeforeFirst: RawUnexpectedNodesSyntax?
let first: RawTokenSyntax?
let unexpectedBeforeSecond: RawUnexpectedNodesSyntax?
let second: RawTokenSyntax?
let unexpectedBeforeColon: RawUnexpectedNodesSyntax?
let colon: RawTokenSyntax?
var misplacedSpecifiers: [RawTokenSyntax] = []
if self.withLookahead({ $0.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: true) }) {
while let specifier = self.consume(ifAnyIn: TypeSpecifier.self) {
misplacedSpecifiers.append(specifier)
}
(unexpectedBeforeFirst, first) = self.parseArgumentLabel()
if let parsedColon = self.consume(if: .colon) {
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = parsedColon
} else if self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon {
(unexpectedBeforeSecond, second) = self.parseArgumentLabel()
(unexpectedBeforeColon, colon) = self.expect(.colon)
} else {
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = RawTokenSyntax(missing: .colon, arena: self.arena)
}
} else {
unexpectedBeforeFirst = nil
first = nil
unexpectedBeforeSecond = nil
second = nil
unexpectedBeforeColon = nil
colon = nil
}
// In the case that the input is "(foo bar)" we have to decide whether we parse it as "(foo: bar)" or "(foo, bar)".
// As most people write identifiers lowercase and types capitalized, we decide on the first character of the first token
if let first = first,
second == nil,
colon?.isMissing == true,
first.tokenText.description.first?.isUppercase == true {
elements.append(RawTupleTypeElementSyntax(
inOut: nil,
name: nil,
secondName: nil,
unexpectedBeforeColon,
colon: nil,
type: RawTypeSyntax(RawSimpleTypeIdentifierSyntax(name: first, genericArgumentClause: nil, arena: self.arena)),
ellipsis: nil,
initializer: nil,
trailingComma: self.missingToken(.comma),
arena: self.arena
))
keepGoing = true
continue
}
// Parse the type annotation.
let type = self.parseType(misplacedSpecifiers: misplacedSpecifiers)
let ellipsis = self.currentToken.isEllipsis ? self.consumeAnyToken() : nil
var trailingComma = self.consume(if: .comma)
if trailingComma == nil && self.withLookahead({ $0.canParseType() }) {
// If the next token does not close the tuple, it is very likely the user forgot the comma.
trailingComma = self.missingToken(.comma)
}
keepGoing = trailingComma != nil
elements.append(RawTupleTypeElementSyntax(
inOut: nil,
RawUnexpectedNodesSyntax(combining: misplacedSpecifiers, unexpectedBeforeFirst, arena: self.arena),
name: first,
unexpectedBeforeSecond,
secondName: second,
unexpectedBeforeColon,
colon: colon,
type: type,
ellipsis: ellipsis,
initializer: nil,
trailingComma: trailingComma,
arena: self.arena
))
}
}
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
return RawTupleTypeSyntax(
unexpectedBeforeLParen,
leftParen: lparen,
elements: RawTupleTypeElementListSyntax(elements: elements, arena: self.arena),
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena)
}
}
extension Parser {
/// Parse an array or dictionary type..
///
/// Grammar
/// =======
///
/// array-type → '[' type ']'
///
/// dictionary-type → '[' type ':' type ']'
@_spi(RawSyntax)
public mutating func parseCollectionType() -> RawTypeSyntax {
if let remaingingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawTypeSyntax(RawArrayTypeSyntax(
remaingingTokens,
leftSquareBracket: missingToken(.leftSquareBracket),
elementType: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
rightSquareBracket: missingToken(.rightSquareBracket),
arena: self.arena
))
}
let (unexpectedBeforeLSquare, lsquare) = self.expect(.leftSquareBracket)
let firstType = self.parseType()
if let colon = self.consume(if: .colon) {
let secondType = self.parseType()
let (unexpectedBeforeRSquareBracket, rSquareBracket) = self.expect(.rightSquareBracket)
return RawTypeSyntax(RawDictionaryTypeSyntax(
unexpectedBeforeLSquare,
leftSquareBracket: lsquare,
keyType: firstType,
colon: colon,
valueType: secondType,
unexpectedBeforeRSquareBracket,
rightSquareBracket: rSquareBracket,
arena: self.arena
))
} else {
let (unexpectedBeforeRSquareBracket, rSquareBracket) = self.expect(.rightSquareBracket)
return RawTypeSyntax(RawArrayTypeSyntax(
unexpectedBeforeLSquare,
leftSquareBracket: lsquare,
elementType: firstType,
unexpectedBeforeRSquareBracket,
rightSquareBracket: rSquareBracket,
arena: self.arena
))
}
}
}
extension Parser.Lookahead {
mutating func canParseType() -> Bool {
// Accept 'inout' at for better recovery.
_ = self.consume(if: .inoutKeyword)
if self.consumeIfContextualKeyword("some") != nil {
} else {
self.consumeIfContextualKeyword("any")
}
switch self.currentToken.tokenKind {
case .capitalSelfKeyword, .anyKeyword:
guard self.canParseTypeIdentifier() else {
return false
}
case .protocolKeyword, // Deprecated composition syntax
.identifier:
guard self.canParseIdentifierTypeOrCompositionType() else {
return false
}
case .leftParen:
self.consumeAnyToken()
guard self.canParseTupleBodyType() else {
return false
}
case .atSign:
self.consumeAnyToken()
self.skipTypeAttribute()
return self.canParseType()
case .leftSquareBracket:
self.consumeAnyToken()
guard self.canParseType() else {
return false
}
if self.consume(if: .colon) != nil {
guard self.canParseType() else {
return false
}
}
guard self.consume(if: .rightSquareBracket) != nil else {
return false
}
case .wildcardKeyword:
self.consumeAnyToken()
default:
return false
}
// '.Type', '.Protocol', '?', and '!' still leave us with type-simple.
var loopCondition = LoopProgressCondition()
while loopCondition.evaluate(currentToken) {
if let (_, _) = self.consume(
if: { [.period, .prefixPeriod].contains($0.tokenKind) },
followedBy: { $0.isContextualKeyword(["Type", "Protocol"])}) {
continue
}
if self.currentToken.isOptionalToken {
self.consumePrefix("?", as: .postfixQuestionMark)
continue
}
if self.currentToken.isImplicitlyUnwrappedOptionalToken {
self.consumePrefix("!", as: .exclamationMark)
continue
}
break
}
guard self.isAtFunctionTypeArrow() else {
return true
}
// Handle type-function if we have an '->' with optional
// 'async' and/or 'throws'.
var loopProgress = LoopProgressCondition()
while let (_, handle) = self.at(anyIn: EffectsSpecifier.self), loopProgress.evaluate(currentToken) {
self.eat(handle)
}
guard self.consume(if: .arrow) != nil else {
return false
}
return self.canParseType()
}
mutating func canParseTupleBodyType() -> Bool {
guard
!self.at(any: [.rightParen, .rightBrace]) &&
!self.atContextualPunctuator("...") &&
!self.atStartOfDeclaration()
else {
return self.consume(if: .rightParen) != nil
}
var loopProgress = LoopProgressCondition()
repeat {
// The contextual inout marker is part of argument lists.
_ = self.consume(if: .inoutKeyword)
// If the tuple element starts with "ident :", then it is followed
// by a type annotation.
if self.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: false) {
self.consumeAnyToken()
if self.currentToken.canBeArgumentLabel() {
self.consumeAnyToken()
guard self.at(.colon) else {
return false
}
}
self.eat(.colon)
// Parse a type.
guard self.canParseType() else {
return false
}
// Parse default values. This aren't actually allowed, but we recover
// better if we skip over them.
if self.consume(if: .equal) != nil {
var skipProgress = LoopProgressCondition()
while !self.at(any: [.eof, .rightParen, .rightBrace, .comma])
&& !self.atContextualPunctuator("...")
&& !self.atStartOfDeclaration()
&& skipProgress.evaluate(currentToken) {
self.skipSingle()
}
}
continue
}
// Otherwise, this has to be a type.
guard self.canParseType() else {
return false
}
self.consumeIfContextualPunctuator("...")
} while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken)
return self.consume(if: .rightParen) != nil
}
mutating func canParseTypeIdentifier() -> Bool {
var loopCondition = LoopProgressCondition()
while loopCondition.evaluate(currentToken) {
guard self.canParseSimpleTypeIdentifier() else {
return false
}
// Treat 'Foo.<anything>' as an attempt to write a dotted type
// unless <anything> is 'Type' or 'Protocol'.
if self.at(any: [.period, .prefixPeriod]) &&
!self.peek().isContextualKeyword(["Type", "Protocol"]) {
self.consumeAnyToken()
} else {
return true
}
}
preconditionFailure("Should return from inside the loop")
}
func isAtFunctionTypeArrow() -> Bool {
if self.at(.arrow) {
return true
}
if self.at(anyIn: EffectsSpecifier.self) != nil {
if self.peek().tokenKind == .arrow {
return true
}
if EffectsSpecifier(lexeme: self.peek()) != nil {
var backtrack = self.lookahead()
backtrack.consumeAnyToken()
backtrack.consumeAnyToken()
return backtrack.isAtFunctionTypeArrow()
}
return false
}
return false
}
mutating func canParseIdentifierTypeOrCompositionType() -> Bool {
if self.at(.protocolKeyword) {
return self.canParseOldStyleProtocolComposition()
}
var loopCondition = LoopProgressCondition()
while loopCondition.evaluate(currentToken) {
guard self.canParseTypeIdentifier() else {
return false
}
if self.atContextualPunctuator("&") {
self.consumeAnyToken()
continue
} else {
return true
}
}
preconditionFailure("Should return from inside the loop")
}
mutating func canParseOldStyleProtocolComposition() -> Bool {
self.eat(.protocolKeyword)
// Check for the starting '<'.
guard self.currentToken.starts(with: "<") else {
return false
}
self.consumePrefix("<", as: .leftAngle)
// Check for empty protocol composition.
if self.currentToken.starts(with: ">") {
self.consumePrefix(">", as: .rightAngle)
return true
}
// Parse the type-composition-list.
var loopProgress = LoopProgressCondition()
repeat {
guard self.canParseTypeIdentifier() else {
return false;
}
} while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken)
// Check for the terminating '>'.
guard self.currentToken.starts(with: ">") else {
return false
}
self.consumePrefix(">", as: .rightAngle)
return true
}
mutating func canParseSimpleTypeIdentifier() -> Bool {
// Parse an identifier.
guard self.at(.identifier) || self.at(any: [.capitalSelfKeyword, .anyKeyword]) else {
return false
}
self.consumeAnyToken()
// Parse an optional generic argument list.
if self.currentToken.starts(with: "<") && !self.consumeGenericArguments() {
return false
}
return true
}
func canParseAsGenericArgumentList() -> Bool {
guard self.atContextualPunctuator("<") else {
return false
}
var lookahead = self.lookahead()
guard lookahead.consumeGenericArguments() else {
return false
}
return lookahead.currentToken.isGenericTypeDisambiguatingToken
}
mutating func consumeGenericArguments() -> Bool {
// Parse the opening '<'.
guard self.currentToken.starts(with: "<") else {
return false
}
self.consumePrefix("<", as: .leftAngle)
var loopProgress = LoopProgressCondition()
repeat {
guard self.canParseType() else {
return false
}
// Parse the comma, if the list continues.
} while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken)
guard self.currentToken.starts(with: ">") else {
return false
}
self.consumePrefix(">", as: .rightAngle)
return true
}
}
extension Parser {
@_spi(RawSyntax)
public mutating func parseTypeAttributeList(misplacedSpecifiers: [RawTokenSyntax] = []) -> (
specifier: RawTokenSyntax?, unexpectedBeforeAttributes: RawUnexpectedNodesSyntax?, attributes: RawAttributeListSyntax?
) {
var specifier: RawTokenSyntax? = self.consume(ifAnyIn: TypeSpecifier.self)
// We can only stick one specifier on this type. Let's pick the first one
if specifier == nil, let misplacedSpecifier = misplacedSpecifiers.first {
specifier = missingToken(misplacedSpecifier.tokenKind, text: misplacedSpecifier.tokenText)
}
var extraneousSpecifiers: [RawTokenSyntax] = []
while let extraSpecifier = self.consume(ifAny: [.inoutKeyword], contextualKeywords: ["__shared", "__owned", "isolated", "_const"]) {
if specifier == nil {
specifier = extraSpecifier
} else {
extraneousSpecifiers.append(extraSpecifier)
}
}
let unexpectedBeforeAttributeList = RawUnexpectedNodesSyntax(extraneousSpecifiers, arena: self.arena)
if self.at(any: [.atSign, .inoutKeyword]) {
return (specifier, unexpectedBeforeAttributeList, self.parseTypeAttributeListPresent())
}
return (specifier, unexpectedBeforeAttributeList, nil)
}
@_spi(RawSyntax)
public mutating func parseTypeAttributeListPresent() -> RawAttributeListSyntax {
var elements = [RawAttributeListSyntax.Element]()
var attributeProgress = LoopProgressCondition()
while self.at(.atSign) && attributeProgress.evaluate(currentToken) {
elements.append(self.parseTypeAttribute())
}
return RawAttributeListSyntax(elements: elements, arena: self.arena)
}
@_spi(RawSyntax)
public mutating func parseTypeAttribute() -> RawAttributeListSyntax.Element {
guard let typeAttr = Parser.TypeAttribute(rawValue: self.peek().tokenText) else {
return .customAttribute(self.parseCustomAttribute())
}
switch typeAttr {
case .differentiable:
return .attribute(self.parseDifferentiableAttribute())
case .convention:
let (unexpectedBeforeAt, at) = self.expect(.atSign)
let (unexpectedBeforeIdent, ident) = self.expectIdentifier()
let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
let arguments = self.parseConventionArguments()
let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
return .attribute(
RawAttributeSyntax(
unexpectedBeforeAt,
atSignToken: at,
unexpectedBeforeIdent,
attributeName: ident,
unexpectedBeforeLeftParen,
leftParen: leftParen,
argument: arguments,
unexpectedBeforeRightParen,
rightParen: rightParen,
tokenList: nil,
arena: self.arena
)
)
case ._opaqueReturnTypeOf:
let (unexpectedBeforeAt, at) = self.expect(.atSign)
let ident = self.expectIdentifierWithoutRecovery()
let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
let argument = self.parseOpaqueReturnTypeOfAttributeArguments()
let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
return .attribute(
RawAttributeSyntax(
unexpectedBeforeAt,
atSignToken: at,
attributeName: ident,
unexpectedBeforeLeftParen,
leftParen: leftParen,
argument: .opaqueReturnTypeOfAttributeArguments(argument),
unexpectedBeforeRightParen,
rightParen: rightParen,
tokenList: nil,
arena: self.arena
)
)
default:
let (unexpectedBeforeAt, at) = self.expect(.atSign)
let ident = self.expectIdentifierWithoutRecovery()
return .attribute(
RawAttributeSyntax(
unexpectedBeforeAt,
atSignToken: at,
attributeName: ident,
leftParen: nil,
argument: nil,
rightParen: nil,
tokenList: nil,
arena: self.arena
)
)
}
}
}
extension Parser {
mutating func parseResultType() -> RawTypeSyntax {
if self.currentToken.starts(with: "<") {
let generics = self.parseGenericParameters()
let baseType = self.parseType()
return RawTypeSyntax(
RawNamedOpaqueReturnTypeSyntax(
genericParameters: generics,
baseType: baseType,
arena: self.arena))
} else {
return self.parseType()
}
}
}
extension Lexer.Lexeme {
var isBinaryOperator: Bool {
return self.tokenKind == .spacedBinaryOperator
|| self.tokenKind == .unspacedBinaryOperator
}
var isAnyOperator: Bool {
return self.isBinaryOperator
|| self.tokenKind == .postfixOperator
|| self.tokenKind == .prefixOperator
}
var isEllipsis: Bool {
return self.isAnyOperator && self.tokenText == "..."
}
var isOptionalToken: Bool {
// A postfix '?' by itself is obviously optional.
if self.tokenKind == .postfixQuestionMark {
return true
}
// A postfix or bound infix operator token that begins with '?' can be
// optional too.
if self.tokenKind == .postfixOperator || self.tokenKind == .unspacedBinaryOperator {
return self.tokenText.first == UInt8(ascii: "?")
}
return false
}
var isImplicitlyUnwrappedOptionalToken: Bool {
// A postfix !?' by itself is obviously optional.
if self.tokenKind == .exclamationMark {
return true
}
// A postfix or bound infix operator token that begins with '?' can be
// optional too.
if self.tokenKind == .postfixOperator || self.tokenKind == .unspacedBinaryOperator {
return self.tokenText.first == UInt8(ascii: "!")
}
return false
}
var isGenericTypeDisambiguatingToken: Bool {
switch self.tokenKind {
case .rightParen,
.rightSquareBracket,
.leftBrace,
.rightBrace,
.period,
.prefixPeriod,
.comma,
.semicolon,
.eof,
.exclamationMark,
.postfixQuestionMark,
.colon:
return true
case .spacedBinaryOperator:
return self.tokenText == "&"
case .unspacedBinaryOperator,
.postfixOperator:
return self.isOptionalToken || self.isImplicitlyUnwrappedOptionalToken
case .leftParen, .leftSquareBracket:
// These only apply to the generic type if they don't start a new line.
return !self.isAtStartOfLine
default:
return false
}
}
}
|
a53abdb360fae1e0fe8ec0926a88c0d5
| 31.99422 | 136 | 0.642724 | false | false | false | false |
JunDang/SwiftFoundation
|
refs/heads/develop
|
Sources/SwiftFoundation/DateComponents.swift
|
mit
|
1
|
//
// DateComponents.swift
// SwiftFoundation
//
// Created by David Ask on 07/12/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux)
import Glibc
#endif
public struct DateComponents {
public enum Component {
case Second
case Minute
case Hour
case DayOfMonth
case Month
case Year
case Weekday
case DayOfYear
}
public var second: Int32 = 0
public var minute: Int32 = 0
public var hour: Int32 = 0
public var dayOfMonth: Int32 = 1
public var month: Int32 = 1
public var year: Int32 = 0
public var weekday: Int32
public var dayOfYear: Int32 = 1
public init(timeInterval: TimeInterval) {
self.init(
brokenDown: tm(
UTCSecondsSince1970: timeval(timeInterval: timeInterval).tv_sec
)
)
}
public init() {
weekday = 0
}
public init(fromDate date: Date) {
self.init(timeInterval: date.timeIntervalSince1970)
}
public var date: Date {
return Date(timeIntervalSince1970: timeInterval)
}
public mutating func setValue(value: Int32, forComponent component: Component) {
switch component {
case .Second:
second = value
break
case .Minute:
minute = value
break
case .Hour:
hour = value
break
case .DayOfMonth:
dayOfMonth = value
break
case .Month:
month = value
break
case .Year:
year = value
break
case .Weekday:
weekday = value
break
case .DayOfYear:
dayOfYear = value
break
}
}
public func valueForComponent(component: Component) -> Int32 {
switch component {
case .Second:
return second
case .Minute:
return minute
case .Hour:
return hour
case .DayOfMonth:
return dayOfMonth
case .Month:
return month
case .Year:
return year
case .Weekday:
return weekday
case .DayOfYear:
return dayOfYear
}
}
private init(brokenDown: tm) {
second = brokenDown.tm_sec
minute = brokenDown.tm_min
hour = brokenDown.tm_hour
dayOfMonth = brokenDown.tm_mday
month = brokenDown.tm_mon + 1
year = 1900 + brokenDown.tm_year
weekday = brokenDown.tm_wday
dayOfYear = brokenDown.tm_yday
}
private var brokenDown: tm {
return tm.init(
tm_sec: second,
tm_min: minute,
tm_hour: hour,
tm_mday: dayOfMonth,
tm_mon: month - 1,
tm_year: year - 1900,
tm_wday: weekday,
tm_yday: dayOfYear,
tm_isdst: -1,
tm_gmtoff: 0,
tm_zone: nil
)
}
private var timeInterval: TimeInterval {
var time = brokenDown
return TimeInterval(timegm(&time))
}
}
|
a2df64cc22c2634049e7234e844b9277
| 22.89781 | 84 | 0.521991 | false | false | false | false |
Pyroh/Fluor
|
refs/heads/main
|
Fluor/Controllers/BehaviorController.swift
|
mit
|
1
|
//
// BehaviorController.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
import os.log
import UserNotifications
class BehaviorController: NSObject, BehaviorDidChangeObserver, DefaultModeViewControllerDelegate, SwitchMethodDidChangeObserver, ActiveApplicationDidChangeObserver {
@IBOutlet weak var statusMenuController: StatusMenuController!
@IBOutlet var defaultModeViewController: DefaultModeViewController!
@objc dynamic private var isKeySwitchCapable: Bool = false
private var globalEventManager: Any?
private var fnDownTimestamp: TimeInterval? = nil
private var shouldHandleFNKey: Bool = false
private var currentMode: FKeyMode = .media
private var onLaunchKeyboardMode: FKeyMode = .media
private var currentAppID: String = ""
private var currentAppURL: URL?
private var currentAppName: String?
private var currentBehavior: AppBehavior = .inferred
private var switchMethod: SwitchMethod = .window
func setupController() {
self.onLaunchKeyboardMode = AppManager.default.getCurrentFKeyMode()
self.currentMode = self.onLaunchKeyboardMode
self.switchMethod = AppManager.default.switchMethod
self.applyAsObserver()
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustSleep(notification:)), name: NSWorkspace.sessionDidResignActiveNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustSleep(notification:)), name: NSWorkspace.willSleepNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustWake(notification:)), name: NSWorkspace.sessionDidBecomeActiveNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustWake(notification:)), name: NSWorkspace.didWakeNotification, object: nil)
guard !AppManager.default.isDisabled else { return }
if let currentApp = NSWorkspace.shared.frontmostApplication, let id = currentApp.bundleIdentifier ?? currentApp.executableURL?.lastPathComponent {
self.adaptModeForApp(withId: id)
// self.updateAppBehaviorViewFor(app: currentApp, id: id)
}
}
func setApplicationIsEnabled(_ enabled: Bool) {
if enabled {
self.adaptModeForApp(withId: self.currentAppID)
} else {
do { try FKeyManager.setCurrentFKeyMode(self.onLaunchKeyboardMode) }
catch { AppErrorManager.terminateApp(withReason: error.localizedDescription) }
}
}
func performTerminationCleaning() {
if AppManager.default.shouldRestoreStateOnQuit {
let state: FKeyMode
if AppManager.default.shouldRestorePreviousState {
state = self.onLaunchKeyboardMode
} else {
state = AppManager.default.onQuitState
}
do { try FKeyManager.setCurrentFKeyMode(state) }
catch { fatalError() }
}
}
func adaptToAccessibilityTrust() {
if AXIsProcessTrusted() {
self.isKeySwitchCapable = true
self.ensureMonitoringFlagKey()
} else {
self.isKeySwitchCapable = false
self.stopMonitoringFlagKey()
}
}
// MARK: - ActiveApplicationDidChangeObserver
func activeApplicationDidChangw(notification: Notification) {
self.adaptToAccessibilityTrust()
guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
let id = app.bundleIdentifier ?? app.executableURL?.lastPathComponent else { return }
self.currentAppName = app.localizedName
self.currentAppID = id
self.currentAppURL = app.bundleURL
if !AppManager.default.isDisabled {
self.adaptModeForApp(withId: id)
}
}
// MARK: - BehaviorDidChangeObserver
/// React to the change of the function keys behavior for one app.
///
/// - parameter notification: The notification.
func behaviorDidChangeForApp(notification: Notification) {
guard let id = notification.userInfo?["id"] as? String else { return }
if id == self.currentAppID {
self.adaptModeForApp(withId: id)
}
}
// MARK: - SwitchMethodDidChangeObserver
func switchMethodDidChange(notification: Notification) {
guard let userInfo = notification.userInfo, let method = userInfo["method"] as? SwitchMethod else { return }
self.switchMethod = method
switch method {
case .window, .hybrid:
self.startObservingBehaviorDidChange()
self.adaptModeForApp(withId: self.currentAppID)
case .key:
self.stopObservingBehaviorDidChange()
self.currentMode = AppManager.default.defaultFKeyMode
self.changeKeyboard(mode: currentMode)
}
}
// MARK: - DefaultModeViewControllerDelegate
func defaultModeController(_ controller: DefaultModeViewController, didChangeModeTo mode: FKeyMode) {
switch self.switchMethod {
case .window, .hybrid:
self.adaptModeForApp(withId: self.currentAppID)
case .key:
self.changeKeyboard(mode: mode)
self.currentMode = mode
}
}
// MARK: - Private functions
/// Disable this session's Fluor instance in order to prevent it from messing when potential other sessions' ones.
///
/// - Parameter notification: The notification.
@objc private func appMustSleep(notification: Notification) {
do { try FKeyManager.setCurrentFKeyMode(self.onLaunchKeyboardMode) }
catch { os_log("Unable to reset FKey mode to pre-launch mode", type: .error) }
self.resignAsObserver()
}
/// Reenable this session's Fluor instance.
///
/// - Parameter notification: The notification.
@objc private func appMustWake(notification: Notification) {
self.changeKeyboard(mode: currentMode)
self.applyAsObserver()
}
/// Register self as an observer for some notifications.
private func applyAsObserver() {
if self.switchMethod != .key { self.startObservingBehaviorDidChange() }
self.startObservingSwitchMethodDidChange()
self.startObservingActiveApplicationDidChange()
self.adaptToAccessibilityTrust()
}
/// Unregister self as an observer for some notifications.
private func resignAsObserver() {
if self.switchMethod != .key { self.stopObservingBehaviorDidChange() }
self.stopObservingSwitchMethodDidChange()
self.stopObservingActiveApplicationDidChange()
self.stopMonitoringFlagKey()
}
/// Set the function keys' behavior for the given app.
///
/// - parameter id: The app's bundle id.
private func adaptModeForApp(withId id: String) {
guard self.switchMethod != .key else { return }
let behavior = AppManager.default.behaviorForApp(id: id)
let mode = AppManager.default.keyboardStateFor(behavior: behavior)
guard mode != self.currentMode else { return }
self.currentMode = mode
self.changeKeyboard(mode: mode)
}
private func changeKeyboard(mode: FKeyMode) {
do { try FKeyManager.setCurrentFKeyMode(mode) }
catch { AppErrorManager.terminateApp(withReason: error.localizedDescription) }
switch mode {
case .media:
os_log("Switch to Apple Mode for %@", self.currentAppID)
self.statusMenuController.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "AppleMode") : #imageLiteral(resourceName: "IconAppleMode")
case .function:
NSLog("Switch to Other Mode for %@", self.currentAppID)
self.statusMenuController.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "OtherMode") : #imageLiteral(resourceName: "IconOtherMode")
}
UserNotificationHelper.sendModeChangedTo(mode)
}
private func manageKeyPress(event: NSEvent) {
guard self.switchMethod != .window else { return }
if event.type == .flagsChanged {
if event.modifierFlags.contains(.function) {
if event.keyCode == 63 {
self.fnDownTimestamp = event.timestamp
self.shouldHandleFNKey = true
} else {
self.fnDownTimestamp = nil
self.shouldHandleFNKey = false
}
} else {
if self.shouldHandleFNKey, let timestamp = self.fnDownTimestamp {
let delta = (event.timestamp - timestamp) * 1000
self.shouldHandleFNKey = false
if event.keyCode == 63, delta <= AppManager.default.fnKeyMaximumDelay {
switch self.switchMethod {
case .key:
self.fnKeyPressedImpactsGlobal()
case .hybrid:
self.fnKeyPressedImpactsApp()
default:
return
}
}
}
}
} else if self.shouldHandleFNKey {
self.shouldHandleFNKey = false
self.fnDownTimestamp = nil
}
}
private func fnKeyPressedImpactsGlobal() {
let mode = self.currentMode.counterPart
AppManager.default.defaultFKeyMode = mode
UserNotificationHelper.holdNextModeChangedNotification = true
self.changeKeyboard(mode: mode)
self.currentMode = mode
UserNotificationHelper.sendGlobalModeChangedTo(mode)
}
private func fnKeyPressedImpactsApp() {
guard let url = self.currentAppURL else { AppErrorManager.terminateApp(withReason: "An unexpected error occured") }
let appBehavior = AppManager.default.behaviorForApp(id: self.currentAppID)
let defaultBehavior = AppManager.default.defaultFKeyMode.behavior
let newAppBehavior: AppBehavior
switch appBehavior {
case .inferred:
newAppBehavior = defaultBehavior.counterPart
case defaultBehavior.counterPart:
newAppBehavior = defaultBehavior
case defaultBehavior:
newAppBehavior = .inferred
default:
newAppBehavior = .inferred
}
UserNotificationHelper.holdNextModeChangedNotification = self.currentAppName != nil
AppManager.default.propagate(behavior: newAppBehavior, forApp: self.currentAppID , at: url, from: .fnKey)
if let name = self.currentAppName {
UserNotificationHelper.sendFKeyChangedAppBehaviorTo(newAppBehavior, appName: name)
}
}
private func ensureMonitoringFlagKey() {
guard self.isKeySwitchCapable && self.globalEventManager == nil else { return }
self.globalEventManager = NSEvent.addGlobalMonitorForEvents(matching: [.flagsChanged, .keyDown], handler: manageKeyPress)
}
private func stopMonitoringFlagKey() {
guard let gem = self.globalEventManager else { return }
NSEvent.removeMonitor(gem)
if self.globalEventManager != nil {
self.globalEventManager = nil
}
}
}
|
10e16f10f6d31764fde24527f309bfdb
| 40.64918 | 180 | 0.659214 | false | false | false | false |
Stanbai/MultiThreadBasicDemo
|
refs/heads/master
|
Operation/Swift/NSOperation/NSOperation/BasicDemosVC.swift
|
mit
|
1
|
//
// BasicDemosVC.swift
// NSOperation
//
// Created by Stan on 2017-07-07.
// Copyright © 2017 stan. All rights reserved.
//
import UIKit
enum DemoType : Int{
case basic
case priority
case dependency
case collection
}
class BasicDemosVC: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet weak var imageView3: UIImageView!
@IBOutlet weak var imageView4: UIImageView!
let operationQueue = OperationQueue.init()
var imageViews : [UIImageView]?
var demoType : DemoType?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let type = demoType else { return }
switch type {
case .basic:
self.title = "Basic Demo"
break
case .priority :
self.title = "Priority Demo"
break
case .dependency :
self.title = "Dependency Demo"
break
default :
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
imageViews = [imageView1,imageView2,imageView3,imageView4]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playItemClick(_ sender: Any) {
guard let type = demoType else { return }
switch type {
case .basic:
startBasicDemo()
break
case .priority :
startPriorityDemo()
break
case .dependency :
startDepencyDemo()
break
default :
break
}
}
}
extension BasicDemosVC {
fileprivate func startBasicDemo() {
operationQueue.maxConcurrentOperationCount = 3
activityIndicator.startAnimating()
// 使用数组给图片赋值
// use Array set image
for imageView in imageViews! {
operationQueue.addOperation {
if let url = URL(string: "https://placebeard.it/355/140") {
do {
let image = UIImage(data:try Data(contentsOf: url))
DispatchQueue.main.async {
imageView.image = image
}
} catch {
print(error)
}
}
}
}
// global queue
DispatchQueue.global().async {
[weak self] in
// 等待所有操作都完成了,回到主线程停止刷新器。
// wait Until All Operations are finished, then stop animation of activity indicator
self?.operationQueue.waitUntilAllOperationsAreFinished()
DispatchQueue.main.async {
self?.activityIndicator.stopAnimating()
}
}
}
fileprivate func startPriorityDemo() {
operationQueue.maxConcurrentOperationCount = 2
activityIndicator.startAnimating()
var operations = [Operation]()
for (index, imageView) in (imageViews?.enumerated())! {
if let url = URL(string: "https://placebeard.it/355/140") {
// 使用构造方法创建operation
let operation = convenienceOperation(setImageView: imageView, withURL: url)
//根据索引设置优先级
switch index {
case 0:
operation.queuePriority = .veryHigh
case 1:
operation.queuePriority = .high
case 2:
operation.queuePriority = .normal
case 3:
operation.queuePriority = .low
default:
operation.queuePriority = .veryLow
}
operations.append(operation)
}
}
// 把任务数组加入到线程中
DispatchQueue.global().async {
[weak self] in
self?.operationQueue.addOperations(operations, waitUntilFinished: true)
DispatchQueue.main.async {
self?.activityIndicator.stopAnimating()
}
}
}
fileprivate func startDepencyDemo() {
operationQueue.maxConcurrentOperationCount = 4
self.activityIndicator.startAnimating()
guard let url = URL(string: "https://placebeard.it/355/140") else {return }
let op1 = convenienceOperation(setImageView: imageView1, withURL: url)
let op2 = convenienceOperation(setImageView: imageView2, withURL: url)
op2.addDependency(op1)
let op3 = convenienceOperation(setImageView: imageView3, withURL: url)
op3.addDependency(op2)
let op4 = convenienceOperation(setImageView: imageView4, withURL: url)
op4.addDependency(op3)
DispatchQueue.global().async {
[weak self] in
self?.operationQueue.addOperations([op1,op2,op3,op4], waitUntilFinished: true)
DispatchQueue.main.async {
self?.activityIndicator.stopAnimating()
}
}
}
}
class convenienceOperation: Operation {
let url: URL
let imageView: UIImageView
init(setImageView: UIImageView, withURL: URL) {
imageView = setImageView
url = withURL
super.init()
}
override func main() {
do {
// 当任务被取消的时候,立刻返回
if isCancelled {
return
}
let imageData = try Data(contentsOf: url)
let image = UIImage(data: imageData)
DispatchQueue.main.async {
[weak self] in
self?.imageView.image = image
}
} catch {
print(error)
}
}
}
|
7770ada5b71183593df9d1f66884eb18
| 27.307339 | 107 | 0.524226 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/find-and-replace-pattern.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/find-and-replace-pattern/
*
*
*/
// Date: Fri May 21 11:51:49 PDT 2021
class Solution {
func findAndReplacePattern(_ words: [String], _ pattern: String) -> [String] {
var result = [String]()
for w in words {
if self.transformable(from: w, to: pattern) {
result.append(w)
}
}
return result
}
private func transformable(from a: String, to b: String) -> Bool {
var map1 = [Character : Character]()
var map2 = [Character : Character]()
let a = Array(a)
let b = Array(b)
for index in 0 ..< a.count {
if map1[a[index]] == nil {
map1[a[index]] = b[index]
}
if map2[b[index]] == nil {
map2[b[index]] = a[index]
}
if map1[a[index]]! != b[index] || map2[b[index]]! != a[index] { return false }
}
return true
}
}
|
bc2a6176871c4108786cd4694a540827
| 28 | 90 | 0.481218 | false | false | false | false |
qiuncheng/CuteAttribute
|
refs/heads/master
|
CuteAttribute/CuteAttribute+NSRange.swift
|
mit
|
1
|
//
// CuteAttribute+NSRange.swift
// Cute
//
// Created by vsccw on 2017/8/11.
// Copyright © 2017年 https://vsccw.com. All rights reserved.
//
import Foundation
public extension CuteAttribute where Base: NSMutableAttributedString {
/// Set the range.
///
/// - Parameter range: NSRange value.
/// - Returns: self
func range(_ range: NSRange) -> CuteAttribute<Base> {
assert(base.string.nsrange >> range, "range should be in range of string.")
self.ranges = [range]
return self
}
internal(set) var ranges: [NSRange] {
get {
let defaultRange = NSRange(location: 0, length: base.length)
let value = (objc_getAssociatedObject(base, CuteAttributeKey.rangesKey) as? Box<[NSRange]>)?.value
return value ?? [defaultRange]
}
set {
let value = Box(newValue)
objc_setAssociatedObject(base, CuteAttributeKey.rangesKey, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Set the ranges.
///
/// - Parameter ranges: [NSRange] value.
/// - Returns: self
func ranges(_ ranges: [NSRange]) -> CuteAttribute<Base> {
let isValid = ranges
.compactMap { return base.string.nsrange >> $0 }
.reduce(true) { return $1 && $0 }
assert(isValid, "ranges must in string.")
self.ranges = ranges
return self
}
}
|
04870746fc880653cce8c5667426d04e
| 28.541667 | 113 | 0.593794 | false | false | false | false |
Tonkpils/SpaceRun
|
refs/heads/master
|
SpaceRun/GameOverNode.swift
|
mit
|
1
|
//
// GameOverNode.swift
// SpaceRun
//
// Created by Leonardo Correa on 12/1/15.
// Copyright © 2015 Leonardo Correa. All rights reserved.
//
import SpriteKit
class GameOverNode: SKNode {
override init() {
super.init()
let labelNode = SKLabelNode(fontNamed: "AvenirNext-Heavy")
labelNode.fontSize = 32
labelNode.fontColor = SKColor.whiteColor()
labelNode.text = "Game Over"
self.addChild(labelNode)
labelNode.alpha = 0
labelNode.xScale = 0.2
labelNode.yScale = 0.2
let fadeIn = SKAction.fadeAlphaTo(1, duration: 2)
let scaleIn = SKAction.scaleTo(1, duration: 2)
let fadeAndScale = SKAction.sequence([fadeIn, scaleIn])
labelNode.runAction(fadeAndScale)
let instructionsNode = SKLabelNode(fontNamed: "AvenirNext-Medium")
instructionsNode.fontSize = 14
instructionsNode.fontColor = SKColor.whiteColor()
instructionsNode.text = "Tap to try again!"
instructionsNode.position = CGPoint(x: 0, y: -45)
self.addChild(instructionsNode)
instructionsNode.alpha = 0
let wait = SKAction.waitForDuration(4)
let appear = SKAction.fadeAlphaTo(1, duration: 0.2)
let popUp = SKAction.scaleTo(1.1, duration: 0.1)
let dropDown = SKAction.scaleTo(1, duration: 0.1)
let pauseAndAppear = SKAction.sequence([wait, appear, popUp, dropDown])
instructionsNode.runAction(pauseAndAppear)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
e4a77cf85ead048027d2c6dd8756f5fe
| 28.777778 | 79 | 0.651741 | false | false | false | false |
furuya02/ProvisioningProfileExplorer
|
refs/heads/master
|
ProvisioningProfileExplorer/Certificate.swift
|
mit
|
1
|
//
// ertificate.swift
// ProvisioningProfileExplorer
//
// Created by hirauchi.shinichi on 2016/04/16.
// Copyright © 2016年 SAPPOROWORKS. All rights reserved.
//
import Cocoa
class Certificate: NSObject {
var summary: String = ""
var expires: NSDate? = nil
var lastDays = 0
init(summary:String,expires:NSDate?,lastDays:Int){
self.summary = summary
self.expires = expires
self.lastDays = lastDays
}
}
|
35400dd8a6c7545b813ce4bd7043e063
| 20.52381 | 56 | 0.661504 | false | false | false | false |
levyjm/SecureCoffee
|
refs/heads/master
|
SecureCoffee/CheckVitals.swift
|
mit
|
1
|
//
// CheckVitals.swift
// SecureCoffee
//
// Created by John on 1/9/17.
// Copyright © 2017 john. All rights reserved.
//
import Foundation
import Cocoa
class CheckVitals: NSObject {
let instanceOfSendText: SendText = SendText()
let instanceOfCheckSMS: CheckSMS = CheckSMS()
let instanceOfCheckPowerSource: CheckPowerSource = CheckPowerSource()
var x = 0
var y = 0
func getStatus() -> Void {
if (loggedBackIn == 0) {
if (instanceOfCheckPowerSource.checkBattery() == -2 && y == 0) {
watchBattery()
y = 1
}
}
}
func watchBattery() -> Void {
while (loggedBackIn == 0) {
usleep(100000)
if (instanceOfCheckPowerSource.checkBattery() != -2) {
instanceOfSendText.sendBatteryTextAlert()
sleep(10)
}
}
}
func watchMovement() -> Void {
let watchZValue: Double = instanceOfCheckSMS.run()
var currentZValue: Double = watchZValue
while (loggedBackIn == 0) {
usleep(100000)
if (currentZValue > (watchZValue + 0.10) || currentZValue < (watchZValue - 0.10)){
instanceOfSendText.sendMovementTextAlert()
sleep(10)
}
currentZValue = instanceOfCheckSMS.run()
}
}
}
|
ef0332b3ab47397fceb75b0700adaa08
| 23.810345 | 94 | 0.530229 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothHCI/HCIEncryptionKeyRefreshComplete.swift
|
mit
|
1
|
//
// HCIEncryptionKeyRefreshComplete.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Encryption Key Refresh Complete Event
///
/// The Encryption Key Refresh Complete event is used to indicate to the Host that the encryption key was
/// refreshed on the given Connection_Handle any time encryption is paused and then resumed.
/// The BR/EDR Controller shall send this event when the encryption key has been refreshed
/// due to encryption being started or resumed.
///
/// If the Encryption Key Refresh Complete event was generated due to an encryption pause
/// and resume operation embedded within a change connection link key procedure, t
/// he Encryption Key Refresh Complete event shall be sent prior to the Change Connection Link Key Complete event.
///
/// If the Encryption Key Refresh Complete event was generated due to an encryption pause and
/// resume operation embedded within a role switch procedure,
/// the Encryption Key Refresh Complete event shall be sent prior to the Role Change event.
@frozen
public struct HCIEncryptionKeyRefreshComplete: HCIEventParameter {
public static let event = HCIGeneralEvent.encryptionKeyRefreshComplete // 0x30
public static let length: Int = 3
public let status: HCIStatus
public let handle: UInt16 // Connection_Handle
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let statusByte = data[0]
let handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2])))
guard let status = HCIStatus(rawValue: statusByte)
else { return nil }
self.status = status
self.handle = handle
}
}
|
de952958061d0516ce92339b86c5c831
| 35.156863 | 114 | 0.700108 | false | false | false | false |
vermont42/Conjugar
|
refs/heads/master
|
ConjugarTests/Controllers/InfoVCTests.swift
|
agpl-3.0
|
1
|
//
// InfoVCTests.swift
// ConjugarTests
//
// Created by Joshua Adams on 5/23/19.
// Copyright © 2019 Josh Adams. All rights reserved.
//
import XCTest
import UIKit
@testable import Conjugar
class InfoVCTests: XCTestCase, InfoDelegate {
var newHeading = ""
func infoSelectionDidChange(newHeading: String) {
self.newHeading = newHeading
}
func testInfoVC() {
var analytic = ""
Current = World.unitTest
Current.analytics = TestAnalyticsService(fire: { fired in analytic = fired })
let urlString = "https://racecondition.software"
guard let url = URL(string: urlString) else {
XCTFail("Could not create URL.")
return
}
let nonURLInfoString = "info"
guard let nonURLInfoURL = URL(string: nonURLInfoString) else {
XCTFail("Could not create nonURLInfoURL.")
return
}
let ivc = InfoVC(infoString: NSAttributedString(string: "\(nonURLInfoString)\(url)"), infoDelegate: self)
XCTAssertNotNil(ivc)
XCTAssertNotNil(ivc.infoView)
ivc.viewWillAppear(true)
XCTAssertEqual(analytic, "visited viewController: \(InfoVC.self) ")
XCTAssertEqual(newHeading, "")
var shouldInteract = ivc.textView(UITextView(), shouldInteractWith: nonURLInfoURL, in: NSRange(location: 0, length: nonURLInfoString.count))
XCTAssertFalse(shouldInteract)
XCTAssertEqual(newHeading, nonURLInfoString)
shouldInteract = ivc.textView(UITextView(), shouldInteractWith: url, in: NSRange(location: nonURLInfoString.count, length: "\(url)".count))
XCTAssert(shouldInteract)
}
}
|
0f622e66f100b9a70b457a2140facf0c
| 29.038462 | 144 | 0.711908 | false | true | false | false |
VitoNYang/VTAutoSlideView
|
refs/heads/master
|
VTAutoSlideViewDemo/UseInCodeViewController.swift
|
mit
|
1
|
//
// UseInCodeViewController.swift
// VTAutoSlideView
//
// Created by hao Mac Mini on 2017/2/8.
// Copyright © 2017年 Vito. All rights reserved.
//
import UIKit
import VTAutoSlideView
class UseInCodeViewController: UIViewController {
lazy var slideView: VTAutoSlideView = {
let slideView = VTAutoSlideView(direction: .vertical, dataSource: self)
return slideView
}()
lazy var imageList = {
// compactMap 不同于 map 的是, compactMap 会筛选非空元素
(1...4).compactMap { UIImage(named: "0\($0)") }
}()
override func viewDidLoad() {
super.viewDidLoad()
slideView.register(nib: UINib(nibName: "DisplayImageCell", bundle: nibBundle))
slideView.dataList = imageList
slideView.activated = false // 关闭自动轮播功能
view.addSubview(slideView)
slideView.translatesAutoresizingMaskIntoConstraints = false
// add constraints
NSLayoutConstraint.activate([
slideView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor),
slideView.topAnchor.constraint(equalTo: safeTopAnchor, constant: 20),
slideView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor),
slideView.heightAnchor.constraint(equalToConstant: view.bounds.height * 0.5)
])
}
}
extension UseInCodeViewController: VTAutoSlideViewDataSource {
func configuration(cell: UICollectionViewCell, for index: Int)
{
guard let cell = cell as? DisplayImageCell else {
return
}
cell.imageView.image = imageList[index]
}
}
extension UIViewController {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return view.safeAreaLayoutGuide.topAnchor
} else {
return topLayoutGuide.bottomAnchor
}
}
}
extension UIView {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.topAnchor
} else {
return self.topAnchor
}
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.bottomAnchor
} else {
return self.bottomAnchor
}
}
var safeLeadingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.leadingAnchor
} else {
return self.leadingAnchor
}
}
var safeTrailingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.trailingAnchor
} else {
return self.trailingAnchor
}
}
}
|
4cb0fa654567474d2edae0a37e525cd4
| 27.65625 | 88 | 0.625954 | false | false | false | false |
leancloud/objc-sdk
|
refs/heads/master
|
AVOS/LeanCloudObjcTests/LCIMConversationTestCase.swift
|
apache-2.0
|
1
|
//
// LCIMConversationTestCase.swift
// LeanCloudObjcTests
//
// Created by 黄驿峰 on 2021/12/17.
// Copyright © 2021 LeanCloud Inc. All rights reserved.
//
import XCTest
import XCTest
@testable import LeanCloudObjc
import CoreMedia
extension LCIMConversationTestCase {
}
class LCIMConversationTestCase: RTMBaseTestCase {
func testCreateConversationThenErrorThrows() {
let client: LCIMClient! = try? LCIMClient.init(clientId: uuid)
XCTAssertNotNil(client)
expecting(description: "not open") { exp in
client.createConversation(withClientIds: []) { conversation, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(error)
XCTAssertNil(conversation)
exp.fulfill()
}
}
expecting { exp in
let invalidID: String = Array<String>.init(repeating: "a", count: 65).joined()
client.createConversation(withClientIds: [invalidID]) { conversation, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(error)
XCTAssertNil(conversation)
exp.fulfill()
}
}
}
func testCreateNormalConversation() {
let delegatorA = LCIMClientDelegator.init()
let delegatorB = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let clientB = newOpenedClient(delegator: delegatorB)
let delegators = [delegatorA, delegatorB];
let name: String? = "normalConv"
let attribution: [String: Any] = [
"String": "",
"Int": 1,
"Double": 1.0,
"Bool": true,
"Array": Array<String>(),
"Dictionary": Dictionary<String, Any>()
]
let convAssertion: (LCIMConversation, LCIMClient) -> Void = { conv, client in
XCTAssertTrue(type(of: conv) == LCIMConversation.self)
guard let convAttr = conv.attributes as? [String: Any] else {
XCTFail()
return
}
// XCTAssertEqual(conv["objectId"] as? String, conv.conversationId)
XCTAssertEqual(conv.convType.rawValue, 1)
// conv. == .normal
XCTAssertEqual(conv.convType, .normal)
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.clientId), true)
XCTAssertEqual(conv.members?.contains(clientB.clientId), true)
XCTAssertNotNil(conv.imClient)
XCTAssertTrue(conv.imClient === client)
XCTAssertEqual(conv.clientId, client.clientId)
XCTAssertFalse(conv.unique)
XCTAssertNil(conv.uniqueId)
XCTAssertEqual(conv.creator, clientA.clientId)
XCTAssertNotNil(conv.updatedAt ?? conv.createdAt)
XCTAssertFalse(conv.muted)
XCTAssertNil(conv.lastMessage)
XCTAssertEqual(conv.unreadMessagesCount, 0)
XCTAssertFalse(conv.unreadMessagesMentioned)
if let name: String = name {
XCTAssertEqual(name, conv.name)
} else {
XCTAssertNil(conv.name)
}
XCTAssertEqual(attribution.count, convAttr.count)
for (key, value) in attribution {
switch key {
case "String":
XCTAssertEqual(value as? String, convAttr[key] as? String)
case "Int":
XCTAssertEqual(value as? Int, convAttr[key] as? Int)
case "Double":
XCTAssertEqual(value as? Double, convAttr[key] as? Double)
case "Bool":
XCTAssertEqual(value as? Bool, convAttr[key] as? Bool)
case "Array":
XCTAssertEqual((value as? Array<String>)?.isEmpty, true)
XCTAssertEqual((convAttr[key] as? Array<String>)?.isEmpty, true)
case "Dictionary":
XCTAssertEqual((value as? Dictionary<String, Any>)?.isEmpty, true)
XCTAssertEqual((convAttr[key] as? Dictionary<String, Any>)?.isEmpty, true)
default:
XCTFail()
}
}
}
expecting(description: "create conversation", count: 5) { exp in
delegators.forEach {
$0.conversationEvent = { client, conv, event in
XCTAssertTrue(Thread.isMainThread)
convAssertion(conv, client)
switch event {
case .joined(byClientID: let cID):
XCTAssertEqual(cID, clientA.ID)
exp.fulfill()
case .membersJoined(members: let members, byClientID: let byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(Set(members), Set([clientA.ID, clientB.ID]))
exp.fulfill()
default:
break
}
}
}
let options = LCIMConversationCreationOption.init()
options.name = name
options.attributes = attribution
options.isUnique = false
clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in
XCTAssertTrue(Thread.isMainThread)
if let conv = conv, let client = conv.imClient {
convAssertion(conv, client)
} else {
XCTFail()
}
exp.fulfill()
}
}
// delay(seconds: 5)
XCTAssertEqual(clientA.convCollection.count, 1)
XCTAssertEqual(clientB.convCollection.count, 1)
XCTAssertEqual(
clientA.convCollection.first?.value.ID,
clientB.convCollection.first?.value.ID
)
XCTAssertTrue(clientA.convQueryCallbackCollection.isEmpty)
XCTAssertTrue(clientB.convQueryCallbackCollection.isEmpty)
}
func testCreateNormalAndUniqueConversation() {
let delegatorA = LCIMClientDelegator.init()
let delegatorB = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let clientB = newOpenedClient(delegator: delegatorB)
let existingKey = "existingKey"
let existingValue = "existingValue"
let delegators = [delegatorA, delegatorB];
expecting(description: "create unique conversation", count: 5) { exp in
delegators.forEach {
$0.conversationEvent = { _, _, event in
switch event {
case .joined:
exp.fulfill()
case .membersJoined:
exp.fulfill()
default:
break
}
}
}
let options = LCIMConversationCreationOption.init()
options.attributes = [existingKey : existingValue]
clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in
XCTAssertTrue(Thread.isMainThread)
if let conv = conv {
XCTAssertEqual(conv.convType, .normal)
XCTAssertTrue(conv.unique)
XCTAssertNotNil(conv.uniqueId)
XCTAssertEqual(conv.attributes?[existingKey] as? String, existingValue)
} else {
XCTFail()
}
exp.fulfill()
}
}
delegatorA.conversationEvent = nil
delegatorB.conversationEvent = nil
delay(seconds: 5)
clientB.convCollection.removeAll()
expecting(description: "recreate unique conversation") { exp in
clientB.createConversation(withClientIds: [clientA.ID, clientB.ID]) { conv, error in
if let conv = conv {
XCTAssertEqual(conv.convType, .normal)
XCTAssertTrue(conv.unique)
XCTAssertNotNil(conv.uniqueId)
XCTAssertNil(conv.attributes?[existingKey])
conv.fetch { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
XCTAssertEqual(conv.attributes?[existingKey] as? String, existingValue)
exp.fulfill()
}
} else {
XCTFail()
exp.fulfill()
}
}
}
XCTAssertEqual(
clientA.convCollection.first?.value.ID,
clientB.convCollection.first?.value.ID
)
XCTAssertEqual(
clientA.convCollection.first?.value.uniqueID,
clientB.convCollection.first?.value.uniqueID
)
}
func testCreateChatRoom() {
let client = newOpenedClient()
expecting(description: "create chat room") { exp in
client.createChatRoom { chatRoom, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(chatRoom?.convType, .transient)
XCTAssertEqual(chatRoom?.convType.rawValue, 2)
XCTAssertEqual(chatRoom?.members?.count, 1)
exp.fulfill()
}
}
}
func testCreateTemporaryConversation() {
let delegatorA = LCIMClientDelegator.init()
let delegatorB = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let clientB = newOpenedClient(delegator: delegatorB)
let delegators = [delegatorA, delegatorB];
let ttl: Int32 = 3600
expecting(description: "create conversation", count: 5) { exp in
delegators.forEach {
$0.conversationEvent = { client, conv, event in
XCTAssertEqual(conv.convType, .temporary)
XCTAssertEqual((conv as? LCIMTemporaryConversation)?.timeToLive, Int(ttl))
switch event {
case .joined(byClientID: let cID):
XCTAssertEqual(cID, clientA.ID)
exp.fulfill()
case .membersJoined(members: let members, byClientID: let byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(Set(members), Set([clientA.ID, clientB.ID]))
exp.fulfill()
default:
break
}
}
}
let options = LCIMConversationCreationOption.init()
options.timeToLive = UInt(ttl)
clientA.createTemporaryConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in
if let conv = conv {
XCTAssertEqual(conv.convType, .temporary)
XCTAssertEqual(conv.rawJSONDataCopy()["objectId"] as? String, conv.ID)
XCTAssertEqual(conv.convType.rawValue, 4)
XCTAssertEqual(conv.timeToLive, Int(ttl))
} else {
XCTFail()
}
exp.fulfill()
}
}
XCTAssertEqual(
clientA.convCollection.first?.value.ID,
clientB.convCollection.first?.value.ID
)
XCTAssertEqual(
clientA.convCollection.first?.value.ID.hasPrefix(kTemporaryConversationIdPrefix),
true
)
}
func testServiceConversationSubscription() {
let client = newOpenedClient()
let serviceConversationID = newServiceConversation()
var serviceConversation: LCIMServiceConversation!
expecting { (exp) in
client.conversationQuery().getConversationById(serviceConversationID) { conv, error in
XCTAssertNotNil(conv)
XCTAssertNil(error)
XCTAssertEqual(conv?.rawJSONDataCopy()["objectId"] as? String, conv?.ID)
XCTAssertEqual(conv?.convType.rawValue, 3)
serviceConversation = conv as? LCIMServiceConversation
exp.fulfill()
}
}
XCTAssertNotNil(serviceConversation)
expecting(
description: "service conversation subscription",
count: 1)
{ (exp) in
serviceConversation.subscribe { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
let query = client.conversationQuery()
expecting { exp in
query.getConversationById(serviceConversationID) { conv, error in
XCTAssertNil(error)
if let conv = conv {
XCTAssertEqual(conv.muted, false)
XCTAssertNotNil(conv.rawJSONDataCopy()["joinedAt"])
} else {
XCTFail()
}
exp.fulfill()
}
}
}
func testNormalConversationUnreadEvent() {
let clientA = newOpenedClient()
let clientBID = uuid
var conversation1: LCIMConversation!
var conversation2: LCIMConversation!
let message1 = LCIMMessage.init(content: uuid)
let message2 = LCIMMessage.init(content: uuid)
expecting(
description: "create conversation, then send message",
count: 4)
{ (exp) in
let option = LCIMConversationCreationOption.init()
option.isUnique = false
clientA.createConversation(withClientIds: [clientBID], option: option) { conv1, error in
XCTAssertNil(error)
XCTAssertNotNil(conv1)
conversation1 = conv1
exp.fulfill()
conv1?.send(message1, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
clientA.createConversation(withClientIds: [clientBID], option: option) { conv2, error in
XCTAssertNil(error)
XCTAssertNotNil(conv2)
conversation2 = conv2
exp.fulfill()
conv2?.send(message2, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
})
}
})
}
}
delay()
XCTAssertNotNil(conversation1)
XCTAssertNotNil(conversation2)
LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects()
LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects()
let delegatorB = LCIMClientDelegator.init()
let clientB: LCIMClient! = try? LCIMClient.init(clientId: clientBID)
XCTAssertNotNil(clientB)
clientB.delegate = delegatorB
expecting(
description: "open, then receive unread event",
count: 5)
{ (exp) in
delegatorB.conversationEvent = { client, conversation, event in
if conversation.ID == conversation1.ID {
switch event {
case .lastMessageUpdated:
let lastMessage = conversation.lastMessage
XCTAssertEqual(lastMessage?.conversationID, message1.conversationID)
XCTAssertEqual(lastMessage?.sentTimestamp, message1.sentTimestamp)
XCTAssertEqual(lastMessage?.ID, message1.ID)
exp.fulfill()
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 1)
// XCTAssertTrue(conversation.isUnreadMessageContainMention)
exp.fulfill()
default:
break
}
} else if conversation.ID == conversation2.ID {
switch event {
case .lastMessageUpdated:
let lastMessage = conversation.lastMessage
XCTAssertEqual(lastMessage?.conversationID, message2.conversationID)
XCTAssertEqual(lastMessage?.sentTimestamp, message2.sentTimestamp)
XCTAssertEqual(lastMessage?.ID, message2.ID)
exp.fulfill()
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 1)
XCTAssertFalse(conversation.isUnreadMessageContainMention)
exp.fulfill()
default:
break
}
}
}
clientB.open { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
expecting { (exp) in
delegatorB.clientEvent = { client, event in
switch event {
case .sessionDidPause:
exp.fulfill()
default:
break
}
}
clientB.connection.disconnect()
}
delay()
XCTAssertTrue(clientB.lastUnreadNotifTime != 0)
let message3 = LCIMMessage.init(content: uuid)
expecting { (exp) in
conversation1.send(message3, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
})
}
expecting(
description: "reconnect, then receive unread event",
count: 3)
{ (exp) in
delegatorB.clientEvent = { client, event in
switch event {
case .sessionDidOpen:
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conversation, event in
if conversation.ID == conversation1.ID {
switch event {
case .lastMessageUpdated:
let lastMessage = conversation.lastMessage
XCTAssertEqual(lastMessage?.conversationID, message3.conversationID)
XCTAssertEqual(lastMessage?.sentTimestamp, message3.sentTimestamp)
XCTAssertEqual(lastMessage?.ID, message3.ID)
exp.fulfill()
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 2)
// XCTAssertTrue(conversation.isUnreadMessageContainMention)
exp.fulfill()
default:
break
}
}
}
clientB.connection.testConnect()
}
expecting(
description: "read",
count: 2)
{ (exp) in
delegatorB.conversationEvent = { client, conversation, event in
if conversation.ID == conversation1.ID {
switch event {
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 0)
exp.fulfill()
default:
break
}
} else if conversation.ID == conversation2.ID {
switch event {
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 0)
exp.fulfill()
default:
break
}
}
}
for (_, conv) in clientB.convCollection {
conv.read()
}
}
}
func testTemporaryConversationUnreadEvent() {
let clientA = newOpenedClient()
let otherClientID: String = uuid
let message = LCIMMessage.init(content: "test")
message.isAllMembersMentioned = true
expecting(description: "create temporary conversation and send message", count: 2) { exp in
let options = LCIMConversationCreationOption.init()
options.timeToLive = 3600
clientA.createTemporaryConversation(withClientIds: [otherClientID], option: options) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
conv?.send(message, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
})
exp.fulfill()
}
}
let delegator = LCIMClientDelegator.init()
let clientB: LCIMClient! = try? LCIMClient.init(clientId: otherClientID)
XCTAssertNotNil(clientB)
clientB.delegate = delegator
expecting(description: "opened and get unread event", count: 3) { exp in
delegator.conversationEvent = { client, conversation, event in
if client === clientB, conversation.ID == message.conversationID {
switch event {
case .lastMessageUpdated:
XCTAssertEqual(conversation.lastMessage?.conversationID, message.conversationID)
XCTAssertEqual(conversation.lastMessage?.sentTimestamp, message.sentTimestamp)
XCTAssertEqual(conversation.lastMessage?.ID, message.ID)
exp.fulfill()
case .unreadMessageCountUpdated:
XCTAssertEqual(conversation.unreadMessageCount, 1)
XCTAssertTrue(conversation.isUnreadMessageContainMention)
exp.fulfill()
default:
break
}
}
}
clientB.open { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
expecting(description: "read") { exp in
delegator.conversationEvent = { client, conversation, event in
if client === clientB, conversation.ID == message.conversationID {
if case .unreadMessageCountUpdated = event {
XCTAssertEqual(conversation.unreadMessageCount, 0)
exp.fulfill()
}
}
}
for (_, conv) in clientB.convCollection {
conv.read()
}
}
}
func testServiceConversationUnreadEvent() {
let clientID = uuid
let serviceConvID = newServiceConversation()
XCTAssertTrue(subscribing(serviceConversation: serviceConvID, by: clientID))
broadcastingMessage(to: serviceConvID)
delay(seconds: 15)
let delegator = LCIMClientDelegator.init()
let clientA: LCIMClient! = try? LCIMClient.init(clientId: clientID)
XCTAssertNotNil(clientA)
clientA.delegate = delegator
expecting(description: "opened and get unread event", count: 3) { exp in
delegator.conversationEvent = { client, conversation, event in
if client === clientA, conversation.ID == serviceConvID {
switch event {
case .lastMessageUpdated:
exp.fulfill()
case .unreadMessageCountUpdated:
exp.fulfill()
default:
break
}
}
}
clientA.open { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
expecting(description: "read") { exp in
delegator.conversationEvent = { client, conversation, event in
if client === clientA, conversation.ID == serviceConvID {
if case .unreadMessageCountUpdated = event {
XCTAssertEqual(conversation.unreadMessageCount, 0)
exp.fulfill()
}
}
}
for (_, conv) in clientA.convCollection {
conv.read()
}
}
}
func testLargeUnreadEvent() {
let clientA = newOpenedClient()
let otherClientID: String = uuid
let count: Int = 20
for i in 0..<count {
let exp = expectation(description: "create conversation and send message")
exp.expectedFulfillmentCount = 2
let message = LCIMMessage.init(content: "test")
if i % 2 == 0 {
let options = LCIMConversationCreationOption.init()
options.timeToLive = 3600
clientA.createTemporaryConversation(withClientIds: [otherClientID], option: options) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
conv?.send(message, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
})
exp.fulfill()
}
wait(for: [exp], timeout: timeout)
} else {
let option = LCIMConversationCreationOption.init()
option.isUnique = false
clientA.createConversation(withClientIds: [otherClientID], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
conv?.send(message, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
})
exp.fulfill()
}
wait(for: [exp], timeout: timeout)
}
}
let convIDSet = Set<String>(clientA.convCollection.keys)
let delegator = LCIMClientDelegator.init()
let clientB: LCIMClient! = try? LCIMClient.init(clientId: otherClientID)
XCTAssertNotNil(clientB)
clientB.delegate = delegator
let largeUnreadExp = expectation(description: "opened and get large unread event")
largeUnreadExp.expectedFulfillmentCount = (count + 2) + 1
// var lcount = 0
// var ucount = 0
delegator.conversationEvent = { client, conversaton, event in
switch event {
case .lastMessageUpdated:
// lcount += 1
// print("lastMessageUpdated count---\(lcount)")
largeUnreadExp.fulfill()
case .unreadMessageCountUpdated:
// ucount += 1
// print("unreadMessageCountUpdated count---\(ucount)")
largeUnreadExp.fulfill()
default:
break
}
}
clientB.open { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
largeUnreadExp.fulfill()
}
wait(for: [largeUnreadExp], timeout: timeout)
delay()
XCTAssertNotNil(clientB.lastUnreadNotifTime)
let allReadExp = expectation(description: "all read")
allReadExp.expectedFulfillmentCount = count
delegator.conversationEvent = { client, conversation, event in
if client === clientB, convIDSet.contains(conversation.ID) {
if case .unreadMessageCountUpdated = event {
allReadExp.fulfill()
}
}
}
for (_, conv) in clientB.convCollection {
conv.read()
}
wait(for: [allReadExp], timeout: timeout)
delegator.reset()
}
func testMembersChange() {
let delegatorA = LCIMClientDelegator.init()
let delegatorB = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let clientB = newOpenedClient(delegator: delegatorB)
var convA: LCIMConversation!
expecting(
description: "create conversation",
count: 5)
{ (exp) in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .joined(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientA.ID))
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .joined(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientA.ID))
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
clientA.createConversation(withClientIds: [clientB.ID]) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
convA = conv
exp.fulfill()
}
}
let convB = clientB.convCollection[convA?.ID ?? ""]
XCTAssertNotNil(convB)
expecting(
description: "leave",
count: 3)
{ (exp) in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersLeft(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientB.ID)
XCTAssertEqual(members.count, 1)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertEqual(conv.members?.count, 1)
XCTAssertEqual(conv.members?.first, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .left(byClientID: byClientID):
XCTAssertEqual(byClientID, clientB.ID)
XCTAssertEqual(conv.members?.count, 1)
XCTAssertEqual(conv.members?.first, clientA.ID)
exp.fulfill()
default:
break
}
}
convB?.quit(callback: { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
})
}
expecting(
description: "join",
count: 4)
{ (exp) in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientB.ID)
XCTAssertEqual(members.count, 1)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .joined(byClientID: byClientID):
XCTAssertEqual(byClientID, clientB.ID)
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientB.ID)
XCTAssertEqual(members.count, 1)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
default:
break
}
}
convB?.join { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
expecting(
description: "remove",
count: 3)
{ (exp) in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersLeft(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(members.count, 1)
XCTAssertEqual(members.first, clientB.ID)
XCTAssertEqual(conv.members?.count, 1)
XCTAssertEqual(conv.members?.first, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .left(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(conv.members?.count, 1)
XCTAssertEqual(conv.members?.first, clientA.ID)
exp.fulfill()
default:
break
}
}
convA?.removeMembers(withClientIds: [clientB.ID]) { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
}
expecting(
description: "add",
count: 4)
{ (exp) in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(members.count, 1)
XCTAssertEqual(members.first, clientB.ID)
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .joined(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
case let .membersJoined(members: members, byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertEqual(members.count, 1)
XCTAssertEqual(members.first, clientB.ID)
XCTAssertEqual(conv.members?.count, 2)
XCTAssertEqual(conv.members?.contains(clientA.ID), true)
XCTAssertEqual(conv.members?.contains(clientB.ID), true)
exp.fulfill()
default:
break
}
}
convA?.addMembers(withClientIds: [clientB.ID], callback: { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
})
}
expecting { (exp) in
convA?.countMembers(callback: { num, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertEqual(num, 2);
exp.fulfill()
})
}
}
func testGetChatRoomOnlineMembers() {
let clientA = newOpenedClient()
let clientB = newOpenedClient()
var chatRoomA: LCIMChatRoom?
expecting { (exp) in
clientA.createChatRoom { room, error in
XCTAssertNil(error)
XCTAssertNotNil(room)
chatRoomA = room
exp.fulfill()
}
}
var chatRoomB: LCIMChatRoom?
expecting { (exp) in
if let ID = chatRoomA?.ID {
clientB.conversationQuery().getConversationById(ID) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
chatRoomB = conv as? LCIMChatRoom
exp.fulfill()
}
} else {
XCTFail()
exp.fulfill()
}
}
expecting(
description: "get online count",
count: 7)
{ (exp) in
chatRoomA?.countMembers(callback: { num, error in
XCTAssertNil(error)
XCTAssertEqual(num, 1);
exp.fulfill()
chatRoomB?.join(callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
exp.fulfill()
self.delay()
chatRoomA?.countMembers(callback: { num, error in
XCTAssertNil(error)
XCTAssertEqual(num, 2);
exp.fulfill()
chatRoomA?.getAllMemberInfo(callback: { memberInfos, error in
XCTAssertNil(error)
//???
XCTAssertEqual(memberInfos?.count, 1)
exp.fulfill()
chatRoomB?.quit(callback: { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
self.delay()
chatRoomA?.countMembers(callback: { num, error in
XCTAssertNil(error)
XCTAssertEqual(num, 1);
exp.fulfill()
chatRoomA?.getAllMemberInfo(callback: { memberInfos, error in
XCTAssertNil(error)
XCTAssertEqual(memberInfos?.count, 1)
exp.fulfill()
})
})
})
})
})
})
})
}
}
func testMuteAndUnmute() {
let client = newOpenedClient()
var conversation: LCIMConversation? = nil
// var previousUpdatedAt: Date?
let createExp = expectation(description: "create conversation")
let option = LCIMConversationCreationOption.init()
option.isUnique = false
client.createConversation(withClientIds: [uuid, uuid], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
conversation = conv
// previousUpdatedAt = conversation?.updatedAt ?? conversation?.createdAt
createExp.fulfill()
}
wait(for: [createExp], timeout: timeout)
delay()
let muteExp = expectation(description: "mute")
conversation?.mute(callback: {[weak conversation] ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
XCTAssertEqual(conversation?.isMuted, true)
let mutedMembers = conversation?.rawJSONDataCopy()[LCIMConversationKey.mutedMembers] as? [String]
XCTAssertEqual(mutedMembers?.count, 1)
XCTAssertEqual(mutedMembers?.contains(client.ID), true)
// if let updatedAt = conversation?.updatedAt, let preUpdatedAt = previousUpdatedAt {
// XCTAssertGreaterThan(updatedAt, preUpdatedAt)
// previousUpdatedAt = updatedAt
// } else {
// XCTFail()
// }
muteExp.fulfill()
})
wait(for: [muteExp], timeout: timeout)
delay()
let unmuteExp = expectation(description: "unmute")
conversation?.unmute(callback: { [weak conversation] ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
XCTAssertEqual(conversation?.isMuted, false)
let mutedMembers = conversation?.rawJSONDataCopy()[LCIMConversationKey.mutedMembers] as? [String]
XCTAssertEqual(mutedMembers?.count, 0)
// if let updatedAt = conversation?.updatedAt, let preUpdatedAt = previousUpdatedAt {
// XCTAssertGreaterThan(updatedAt, preUpdatedAt)
// previousUpdatedAt = updatedAt
// } else {
// XCTFail()
// }
unmuteExp.fulfill()
})
wait(for: [unmuteExp], timeout: timeout)
}
func testConversationQuery() {
let clientA = newOpenedClient()
var ID1: String? = nil
var ID2: String? = nil
var ID3: String? = nil
var ID4: String? = nil
for i in 0...3 {
switch i {
case 0:
let createExp = expectation(description: "create normal conversation")
createExp.expectedFulfillmentCount = 2
let option = LCIMConversationCreationOption.init()
option.isUnique = false
clientA.createConversation(withClientIds: [uuid], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
ID1 = conv?.ID
let message = LCIMMessage.init(content: "test")
conv?.send(message, callback: { ret, error in
XCTAssertNil(error)
XCTAssertTrue(ret)
createExp.fulfill()
})
createExp.fulfill()
}
wait(for: [createExp], timeout: timeout)
case 1:
let createExp = expectation(description: "create chat room")
clientA.createChatRoom { room, error in
XCTAssertNil(error)
XCTAssertNotNil(room)
ID2 = room?.ID
createExp.fulfill()
}
wait(for: [createExp], timeout: timeout)
case 2:
let ID = newServiceConversation()
XCTAssertNotNil(ID)
ID3 = ID
case 3:
let createExp = expectation(description: "create temporary conversation")
let options = LCIMConversationCreationOption.init()
options.timeToLive = 3600
clientA.createTemporaryConversation(withClientIds: [uuid], option: options) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
ID4 = conv?.ID
createExp.fulfill()
}
wait(for: [createExp], timeout: timeout)
default:
break
}
}
guard
let normalConvID = ID1,
let chatRoomID = ID2,
let serviceID = ID3,
let tempID = ID4
else
{
XCTFail()
return
}
delay()
clientA.convCollection.removeAll()
let queryExp1 = expectation(description: "query normal conversation with message and without member")
let query1 = clientA.conversationQuery()
query1.option = [.compact, .withMessage]
query1.getConversationById(normalConvID) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
XCTAssertEqual(conv?.convType, .normal)
XCTAssertEqual(conv?.members ?? [], [])
XCTAssertNotNil(conv?.lastMessage)
queryExp1.fulfill()
}
wait(for: [queryExp1], timeout: timeout)
let queryExp2 = expectation(description: "query chat room")
clientA.conversationQuery().getConversationById(chatRoomID) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
XCTAssertEqual(conv?.convType, .transient)
queryExp2.fulfill()
}
wait(for: [queryExp2], timeout: timeout)
let queryExp3 = expectation(description: "query service conversation")
clientA.conversationQuery().getConversationById(serviceID) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
XCTAssertEqual(conv?.convType, .system)
queryExp3.fulfill()
}
wait(for: [queryExp3], timeout: timeout)
clientA.convCollection.removeAll()
let queryTempExp = expectation(description: "query temporary conversation")
clientA.conversationQuery().findTemporaryConversations(with: [tempID]) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
XCTAssertEqual(conv?.count, 1)
if let tmpConv = conv?.first {
XCTAssertEqual(tmpConv.convType.rawValue, 4)
} else {
XCTFail()
}
queryTempExp.fulfill()
}
wait(for: [queryTempExp], timeout: timeout)
clientA.convCollection.removeAll()
let generalQueryExp1 = expectation(description: "general query with default conditon")
clientA.conversationQuery().findConversations { convs, error in
XCTAssertNil(error)
XCTAssertEqual(convs?.count, 1)
XCTAssertEqual(convs?.first?.convType, .normal)
XCTAssertEqual(convs?.first?.members?.contains(clientA.ID), true)
generalQueryExp1.fulfill()
}
wait(for: [generalQueryExp1], timeout: timeout)
let generalQueryExp2 = expectation(description: "general query with custom conditon")
let generalQuery1 = clientA.conversationQuery()
generalQuery1.whereKey(LCIMConversationKey.transient.rawValue, equalTo: true)
let generalQuery2 = clientA.conversationQuery()
generalQuery2.whereKey(LCIMConversationKey.system.rawValue, equalTo: true)
let generalQuery3 = LCIMConversationQuery.orQuery(withSubqueries: [generalQuery1, generalQuery2])
generalQuery3?.addAscendingOrder(LCIMConversationKey.createdAt.rawValue)
generalQuery3?.limit = 5
generalQuery3?.findConversations { convs, error in
XCTAssertNil(error)
XCTAssertLessThanOrEqual(convs?.count ?? .max, 5)
if let convs = convs {
let types: [LCIMConvType] = [.system, .transient]
var date = Date(timeIntervalSince1970: 0)
for conv in convs {
XCTAssertTrue(types.contains(conv.convType))
XCTAssertNotNil(conv.createdAt)
if let createdAt = conv.createdAt {
XCTAssertGreaterThanOrEqual(createdAt, date)
date = createdAt
}
}
}
generalQueryExp2.fulfill()
}
wait(for: [generalQueryExp2], timeout: timeout)
}
func testUpdateAttribution() {
let delegatorA = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects()
LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects()
let delegatorB = LCIMClientDelegator.init()
let clientB = newOpenedClient(delegator: delegatorB)
var convA: LCIMConversation? = nil
var convB: LCIMConversation? = nil
let nameKey = LCIMConversationKey.name.rawValue
let attrKey = LCIMConversationKey.attributes.rawValue
let createKey = "create"
let deleteKey = "delete"
let arrayKey = "array"
let createConvExp = expectation(description: "create conversation")
let option = LCIMConversationCreationOption.init()
option.isUnique = false
option.attributes = [
deleteKey: uuid,
arrayKey: [uuid]
]
option.name = uuid
clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
convA = conv
createConvExp.fulfill()
}
wait(for: [createConvExp], timeout: timeout)
delay()
let data: [String: Any] = [
nameKey: uuid,
"\(attrKey).\(createKey)": uuid,
"\(attrKey).\(deleteKey)": ["__op": "Delete"],
"\(attrKey).\(arrayKey)": ["__op": "Add", "objects": [uuid]]
]
let updateExp = expectation(description: "update")
updateExp.expectedFulfillmentCount = 2
delegatorB.conversationEvent = { client, conv, event in
if conv.ID == convA?.ID {
switch event {
case let .dataUpdated(updatingData: updatingData, updatedData: updatedData, byClientID: byClientID):
XCTAssertNotNil(updatedData)
XCTAssertNotNil(updatingData)
XCTAssertEqual(byClientID, clientA.ID)
convB = conv
updateExp.fulfill()
default:
break
}
}
}
data.forEach { key, value in
convA?[key] = value
}
convA?.update(callback: { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(ret)
XCTAssertNil(error)
updateExp.fulfill()
})
wait(for: [updateExp], timeout: timeout)
let check = { (conv: LCIMConversation?) in
XCTAssertEqual(conv?.name, data[nameKey] as? String)
XCTAssertEqual(conv?.attributes?[createKey] as? String, data["\(attrKey).\(createKey)"] as? String)
XCTAssertNil(conv?.attributes?[deleteKey])
XCTAssertNotNil(conv?.attributes?[arrayKey])
}
check(convA)
check(convB)
XCTAssertEqual(convA?.attributes?[arrayKey] as? [String], convB?.attributes?[arrayKey] as? [String])
}
func testOfflineEvents() {
let delegatorA = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects()
LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects()
let delegatorB = LCIMClientDelegator.init()
let clientB = newOpenedClient(delegator: delegatorB)
expecting(expectation: { () -> XCTestExpectation in
let exp = self.expectation(description: "create conv and send msg with rcp")
exp.expectedFulfillmentCount = 5
return exp
}) { (exp) in
delegatorA.messageEvent = { client, conv, event in
switch event {
case .received:
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case .joined:
exp.fulfill()
let message = LCIMTextMessage.init()
message.text = "text"
let msgOpt = LCIMMessageOption.init()
msgOpt.receipt = true
conv.send(message, option: msgOpt) { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
}
case .message(event: let msgEvent):
switch msgEvent {
case .delivered:
exp.fulfill()
default:
break
}
default:
break
}
}
clientA.createConversation(withClientIds: [clientB.ID]) { conv, error in
XCTAssertNotNil(conv)
XCTAssertNil(error)
exp.fulfill()
}
}
delegatorA.reset()
delegatorB.reset()
delay()
clientB.connection.disconnect()
delay()
expecting(expectation: { () -> XCTestExpectation in
let exp = self.expectation(description: "conv read")
exp.expectedFulfillmentCount = 1
return exp
}) { (exp) in
let conv = clientA.convCollection.first?.value
delegatorA.conversationEvent = { client, conv, event in
switch event {
case .unreadMessageCountUpdated:
exp.fulfill()
default:
break
}
}
conv?.read()
}
delegatorA.reset()
expecting(expectation: { () -> XCTestExpectation in
let exp = self.expectation(description: "create another normal conv")
exp.expectedFulfillmentCount = 3
return exp
}) { exp in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case .joined:
exp.fulfill()
case .membersJoined:
exp.fulfill()
default:
break
}
}
let option = LCIMConversationCreationOption.init()
option.isUnique = false
clientA.createConversation(withClientIds: [clientB.ID], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
exp.fulfill()
}
}
delegatorA.reset()
expecting(description: "update normal conv attr") { (exp) in
let conv = clientA.convCollection.first?.value
let name = self.uuid
delegatorA.conversationEvent = { client, conv, event in
switch event {
case .dataUpdated:
XCTAssertEqual(conv.name, name)
exp.fulfill()
default:
break
}
}
conv?["name"] = name
conv?.update(callback: { ret, error in
XCTAssertTrue(ret)
XCTAssertNil(error)
exp.fulfill()
})
}
delegatorA.reset()
expecting(expectation: { () -> XCTestExpectation in
let exp = self.expectation(description: "create temp conv")
exp.expectedFulfillmentCount = 3
return exp
}) { exp in
delegatorA.conversationEvent = { client, conv, event in
switch event {
case .joined:
exp.fulfill()
case .membersJoined:
exp.fulfill()
default:
break
}
}
let option = LCIMConversationCreationOption.init()
option.timeToLive = 3600
clientA.createTemporaryConversation(withClientIds: [clientB.ID], option: option) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
exp.fulfill()
}
}
// delegatorA.reset()
//
// delay()
//
// expecting(expectation: { () -> XCTestExpectation in
// let exp = self.expectation(description: "get offline events")
// exp.expectedFulfillmentCount = 6
// return exp
// }) { (exp) in
// delegatorB.conversationEvent = { client, conv, event in
// switch event {
// case .joined:
// if conv is LCIMTemporaryConversation {
// exp.fulfill()
// } else {
// exp.fulfill()
// }
// case .membersJoined:
// if conv is LCIMTemporaryConversation {
// exp.fulfill()
// } else {
// exp.fulfill()
// }
// case .dataUpdated:
// exp.fulfill()
// case .message(event: let msgEvent):
// switch msgEvent {
// case .read:
// exp.fulfill()
// default:
// break
// }
// default:
// break
// }
// }
// clientB.connection.testConnect()
// }
// delegatorB.reset()
}
func testMemberInfo() {
let delegatorA = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let delegatorB = LCIMClientDelegator.init()
let clientB = newOpenedClient(delegator: delegatorB)
let clientCID: String = self.uuid
var convA: LCIMConversation?
expecting { (exp) in
clientA.createConversation(withClientIds: [clientB.ID, clientCID]) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
convA = conv
exp.fulfill()
}
}
expecting { (exp) in
convA?.updateMemberRole(withMemberId: clientB.ID, role: .owner, callback: { ret, error in
XCTAssertNotNil(error)
XCTAssertFalse(ret)
exp.fulfill()
})
}
expecting { (exp) in
convA?.getAllMemberInfo(callback: {[weak convA] infos, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(convA?.memberInfoTable)
XCTAssertEqual(convA?.memberInfoTable?.count, 1)
exp.fulfill()
})
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "change member role to manager")
exp.expectedFulfillmentCount = 2
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .memberInfoChanged(memberId: memberId, role: role, byClientID: byClientID):
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(role, .manager)
XCTAssertEqual(memberId, clientB.ID)
XCTAssertEqual(byClientID, clientA.ID)
XCTAssertNotNil(convA?.memberInfoTable)
exp.fulfill()
default:
break
}
}
convA?.updateMemberRole(withMemberId: clientB.ID, role: .manager, callback: { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertTrue(ret)
let info = convA?.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo
XCTAssertEqual(info?.role(), .manager)
exp.fulfill()
})
}
delay()
expecting { (exp) in
let convB = clientB.convCollection.values.first
XCTAssertNil(convB?.memberInfoTable)
convB?.getMemberInfo(withMemberId: clientB.ID, callback: { info, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(info)
exp.fulfill()
})
}
expecting { (exp) in
convA?.getAllMemberInfo(callback: {[weak convA] infos, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(convA?.memberInfoTable)
XCTAssertEqual(convA?.memberInfoTable?.count, 2)
exp.fulfill()
})
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "change member role to member")
exp.expectedFulfillmentCount = 2
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .memberInfoChanged(memberId: memberId, role: role, byClientID: byClientID):
XCTAssertEqual(role, .member)
XCTAssertEqual(memberId, clientB.ID)
XCTAssertEqual(byClientID, clientA.ID)
let info = conv.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo
XCTAssertEqual(info?.role(), .member)
exp.fulfill()
default:
break
}
}
convA?.updateMemberRole(withMemberId: clientB.ID, role: .member, callback: { ret, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertTrue(ret)
let info = convA?.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo
XCTAssertEqual(info?.role(), .member)
exp.fulfill()
})
}
}
func testMemberBlock() {
let delegatorA = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let delegatorB = LCIMClientDelegator.init()
let clientB = newOpenedClient(delegator: delegatorB)
let delegatorC = LCIMClientDelegator.init()
let clientC = newOpenedClient(delegator: delegatorC)
var convA: LCIMConversation?
expecting { (exp) in
clientA.createConversation(withClientIds: [clientB.ID, clientC.ID]) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
convA = conv
exp.fulfill()
}
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "block member")
exp.expectedFulfillmentCount = 7
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersBlocked(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertTrue(members.contains(clientC.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
case let .membersLeft(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertTrue(members.contains(clientC.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .blocked(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
case let .left(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorC.conversationEvent = { client, conv, event in
switch event {
case let .blocked(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
case let .left(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
convA?.blockMembers([clientB.ID, clientC.ID], callback: { ids, oper, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(ids)
exp.fulfill()
})
}
delegatorA.reset()
delegatorB.reset()
delegatorC.reset()
var next: String?
expecting { (exp) in
convA?.queryBlockedMembers(withLimit: 1, next: nil, callback: { members, _next, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertEqual(members?.count, 1)
if let member = members?.first {
XCTAssertTrue([clientB.ID, clientC.ID].contains(member))
}
XCTAssertNotNil(_next)
next = _next
exp.fulfill()
})
}
expecting { (exp) in
convA?.queryBlockedMembers(withLimit: 50, next: next, callback: { members, _next, error in
XCTAssertNil(error)
XCTAssertEqual(members?.count, 1)
if let member = members?.first {
XCTAssertTrue([clientB.ID, clientC.ID].contains(member))
}
XCTAssertNil(_next)
exp.fulfill()
})
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "unblock member")
exp.expectedFulfillmentCount = 4
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersUnblocked(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertTrue(members.contains(clientC.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .unblocked(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorC.conversationEvent = { client, conv, event in
switch event {
case let .unblocked(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
convA?.unblockMembers([clientB.ID, clientC.ID], callback: { members, fails, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
exp.fulfill()
})
}
}
func testMemberMute() {
let delegatorA = LCIMClientDelegator.init()
let clientA = newOpenedClient(delegator: delegatorA)
let delegatorB = LCIMClientDelegator.init()
let clientB = newOpenedClient(delegator: delegatorB)
let delegatorC = LCIMClientDelegator.init()
let clientC = newOpenedClient(delegator: delegatorC)
var convA: LCIMConversation?
expecting { (exp) in
clientA.createConversation(withClientIds: [clientB.ID, clientC.ID]) { conv, error in
XCTAssertNil(error)
XCTAssertNotNil(conv)
convA = conv
exp.fulfill()
}
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "mute member")
exp.expectedFulfillmentCount = 4
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersMuted(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertTrue(members.contains(clientC.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .muted(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorC.conversationEvent = { client, conv, event in
switch event {
case let .muted(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
convA?.muteMembers([clientB.ID, clientC.ID], callback: { members, fails, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
exp.fulfill()
})
}
delegatorA.reset()
delegatorB.reset()
delegatorC.reset()
var next: String?
expecting { (exp) in
convA?.queryMutedMembers(withLimit: 1, next: nil, callback: { members, _next, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertEqual(members?.count, 1)
if let member = members?.first {
XCTAssertTrue([clientB.ID, clientC.ID].contains(member))
}
XCTAssertNotNil(_next)
next = _next
exp.fulfill()
})
}
expecting { (exp) in
convA?.queryMutedMembers(withLimit: 50, next: next, callback: { members, _next, error in
XCTAssertNil(error)
XCTAssertEqual(members?.count, 1)
if let member = members?.first {
XCTAssertTrue([clientB.ID, clientC.ID].contains(member))
}
XCTAssertNil(_next)
exp.fulfill()
})
}
multiExpecting(expectations: { () -> [XCTestExpectation] in
let exp = self.expectation(description: "unmute member")
exp.expectedFulfillmentCount = 4
return [exp]
}) { (exps) in
let exp = exps[0]
delegatorA.conversationEvent = { client, conv, event in
switch event {
case let .membersUnmuted(members: members, byClientID: byClientID):
XCTAssertEqual(members.count, 2)
XCTAssertTrue(members.contains(clientB.ID))
XCTAssertTrue(members.contains(clientC.ID))
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorB.conversationEvent = { client, conv, event in
switch event {
case let .unmuted(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
delegatorC.conversationEvent = { client, conv, event in
switch event {
case let .unmuted(byClientID: byClientID):
XCTAssertEqual(byClientID, clientA.ID)
exp.fulfill()
default:
break
}
}
convA?.unmuteMembers([clientB.ID, clientC.ID], callback: { members, fails, error in
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
exp.fulfill()
})
}
}
}
extension LCIMConversationTestCase {
func subscribing(serviceConversation conversationID: String, by clientID: String) -> Bool {
var success: Bool = false
let paasClient = LCPaasClient.sharedInstance()
let request = paasClient?.request(withPath: "https://s5vdi3ie.lc-cn-n1-shared.com/1.2/rtm/service-conversations/\(conversationID)/subscribers", method: "POST", headers: ["X-LC-Key": BaseTestCase.cnApp.masterKey], parameters: ["client_id": clientID])
expecting { exp in
paasClient?.perform(request as URLRequest?, success: { response, responseObject in
success = true
exp.fulfill()
}, failure: { _, _, _ in
exp.fulfill()
})
}
return success
}
}
|
dd5c7b119001128004fe44c5cfab6e8f
| 38.287733 | 257 | 0.502178 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift
|
refs/heads/master
|
10-Number/10-Number/Statistics.swift
|
mit
|
1
|
//
// Statistics.swift
// 10-Number
//
// Created by FlyElephant on 17/2/28.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class Statistics {
// 对于数abcde,c这位出现1的次数分以下情况:
// 1.若c == 0,结轮是 ab * 100;
// 2.若c == 1,结论是(ab)* 100 + de + 1;
// 3.若c > 1,结论是(ab + 1)* 100;
func sumls(num:Int) -> Int {
var count:Int = 0
for i in 1...num {
var temp:Int = i
while temp != 0 {
count += temp % 10 == 1 ? 1 : 0
temp /= 10
}
}
return count
}
func sumlsSimple(num:Int) -> Int {
if num <= 0 {
return 0
}
var factor = 1
var lowNum:Int = 0
var curNum:Int = 0
var highNum:Int = 0
var count:Int = 0
let n:Int = num
while n / factor != 0 {
lowNum = n - (n / factor) * factor
curNum = (n / factor) % 10
highNum = n / (factor * 10)
if curNum == 0 {
count += highNum * factor
} else if curNum == 1 {
count += highNum * factor + lowNum + 1
} else {
count += (highNum + 1) * factor
}
factor *= 10
}
return count
}
func sumlsCommon(num:Int,target:Int) -> Int {
if num <= 0 || (target < 1 || target > 9){
return 0
}
var factor = 1
var lowNum:Int = 0
var curNum:Int = 0
var highNum:Int = 0
var count:Int = 0
let n:Int = num
while n / factor != 0 {
lowNum = n - (n / factor) * factor
curNum = (n / factor) % 10
highNum = n / (factor * 10)
if curNum < target {
count += highNum * factor
} else if curNum == target {
count += highNum * factor + lowNum + 1
} else {
count += (highNum + 1) * factor
}
factor *= 10
}
return count
}
}
|
3a006582a3064dc4a0f28d8be5c2149a
| 21.916667 | 55 | 0.395455 | false | false | false | false |
apple/swift-experimental-string-processing
|
refs/heads/main
|
Sources/_StringProcessing/_CharacterClassModel.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@_implementationOnly import _RegexParser
// NOTE: This is a model type. We want to be able to get one from
// an AST, but this isn't a natural thing to produce in the context
// of parsing or to store in an AST
struct _CharacterClassModel: Hashable {
/// The actual character class to match.
let cc: Representation
/// The level (character or Unicode scalar) at which to match.
let matchLevel: MatchingOptions.SemanticLevel
/// If this character character class only matches ascii characters
let isStrictASCII: Bool
/// Whether this character class matches against an inverse,
/// e.g \D, \S, [^abc].
let isInverted: Bool
init(
cc: Representation,
options: MatchingOptions,
isInverted: Bool
) {
self.cc = cc
self.matchLevel = options.semanticLevel
self.isStrictASCII = cc.isStrictAscii(options: options)
self.isInverted = isInverted
}
enum Representation: UInt64, Hashable {
/// Any character
case any = 0
/// Any grapheme cluster
case anyGrapheme
/// Any Unicode scalar
case anyScalar
/// Character.isDigit
case digit
/// Horizontal whitespace: `[:blank:]`, i.e
/// `[\p{gc=Space_Separator}\N{CHARACTER TABULATION}]
case horizontalWhitespace
/// Character.isNewline
case newlineSequence
/// Vertical whitespace: `[\u{0A}-\u{0D}\u{85}\u{2028}\u{2029}]`
case verticalWhitespace
/// Character.isWhitespace
case whitespace
/// Character.isLetter or Character.isDigit or Character == "_"
case word
}
/// Returns the end of the match of this character class in the string.
///
/// - Parameter str: The string to match against.
/// - Parameter at: The index to start matching.
/// - Parameter options: Options for the match operation.
/// - Returns: The index of the end of the match, or `nil` if there is no match.
func matches(
in input: String,
at currentPosition: String.Index
) -> String.Index? {
// FIXME: This is only called in custom character classes that contain builtin
// character classes as members (ie: [a\w] or set operations), is there
// any way to avoid that? Can we remove this somehow?
guard currentPosition != input.endIndex else {
return nil
}
let char = input[currentPosition]
let scalar = input.unicodeScalars[currentPosition]
let isScalarSemantics = matchLevel == .unicodeScalar
let asciiCheck = (char.isASCII && !isScalarSemantics)
|| (scalar.isASCII && isScalarSemantics)
|| !isStrictASCII
var matched: Bool
var next: String.Index
switch (isScalarSemantics, cc) {
case (_, .anyGrapheme):
next = input.index(after: currentPosition)
case (_, .anyScalar):
// FIXME: This allows us to be not-scalar aligned when in grapheme mode
// Should this even be allowed?
next = input.unicodeScalars.index(after: currentPosition)
case (true, _):
next = input.unicodeScalars.index(after: currentPosition)
case (false, _):
next = input.index(after: currentPosition)
}
switch cc {
case .any, .anyGrapheme, .anyScalar:
matched = true
case .digit:
if isScalarSemantics {
matched = scalar.properties.numericType != nil && asciiCheck
} else {
matched = char.isNumber && asciiCheck
}
case .horizontalWhitespace:
if isScalarSemantics {
matched = scalar.isHorizontalWhitespace && asciiCheck
} else {
matched = char._isHorizontalWhitespace && asciiCheck
}
case .verticalWhitespace:
if isScalarSemantics {
matched = scalar.isNewline && asciiCheck
} else {
matched = char._isNewline && asciiCheck
}
case .newlineSequence:
if isScalarSemantics {
matched = scalar.isNewline && asciiCheck
if matched && scalar == "\r"
&& next != input.endIndex && input.unicodeScalars[next] == "\n" {
// Match a full CR-LF sequence even in scalar sematnics
input.unicodeScalars.formIndex(after: &next)
}
} else {
matched = char._isNewline && asciiCheck
}
case .whitespace:
if isScalarSemantics {
matched = scalar.properties.isWhitespace && asciiCheck
} else {
matched = char.isWhitespace && asciiCheck
}
case .word:
if isScalarSemantics {
matched = scalar.properties.isAlphabetic && asciiCheck
} else {
matched = char.isWordCharacter && asciiCheck
}
}
if isInverted {
matched.toggle()
}
if matched {
return next
} else {
return nil
}
}
}
extension _CharacterClassModel {
var consumesSingleGrapheme: Bool {
switch self.cc {
case .anyScalar: return false
default: return true
}
}
}
extension _CharacterClassModel.Representation {
/// Returns true if this CharacterClass should be matched by strict ascii under the given options
func isStrictAscii(options: MatchingOptions) -> Bool {
switch self {
case .digit: return options.usesASCIIDigits
case .horizontalWhitespace: return options.usesASCIISpaces
case .newlineSequence: return options.usesASCIISpaces
case .verticalWhitespace: return options.usesASCIISpaces
case .whitespace: return options.usesASCIISpaces
case .word: return options.usesASCIIWord
default: return false
}
}
}
extension _CharacterClassModel.Representation: CustomStringConvertible {
var description: String {
switch self {
case .any: return "<any>"
case .anyGrapheme: return "<any grapheme>"
case .anyScalar: return "<any scalar>"
case .digit: return "<digit>"
case .horizontalWhitespace: return "<horizontal whitespace>"
case .newlineSequence: return "<newline sequence>"
case .verticalWhitespace: return "vertical whitespace"
case .whitespace: return "<whitespace>"
case .word: return "<word>"
}
}
}
extension _CharacterClassModel: CustomStringConvertible {
var description: String {
return "\(isInverted ? "not " : "")\(cc)"
}
}
extension DSLTree.Atom.CharacterClass {
/// Converts this DSLTree CharacterClass into our runtime representation
func asRuntimeModel(_ options: MatchingOptions) -> _CharacterClassModel {
let cc: _CharacterClassModel.Representation
var inverted = false
switch self {
case .digit:
cc = .digit
case .notDigit:
cc = .digit
inverted = true
case .horizontalWhitespace:
cc = .horizontalWhitespace
case .notHorizontalWhitespace:
cc = .horizontalWhitespace
inverted = true
case .newlineSequence:
cc = .newlineSequence
// FIXME: This is more like '.' than inverted '\R', as it is affected
// by e.g (*CR). We should therefore really be emitting it through
// emitDot(). For now we treat it as semantically invalid.
case .notNewline:
cc = .newlineSequence
inverted = true
case .whitespace:
cc = .whitespace
case .notWhitespace:
cc = .whitespace
inverted = true
case .verticalWhitespace:
cc = .verticalWhitespace
case .notVerticalWhitespace:
cc = .verticalWhitespace
inverted = true
case .word:
cc = .word
case .notWord:
cc = .word
inverted = true
case .anyGrapheme:
cc = .anyGrapheme
case .anyUnicodeScalar:
cc = .anyScalar
}
return _CharacterClassModel(cc: cc, options: options, isInverted: inverted)
}
}
|
0a9b934980e844f06a95bf7d04410bef
| 29.74031 | 99 | 0.649098 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV
|
refs/heads/master
|
PopcornTime/UI/iOS/Extensions/String+Truncation.swift
|
gpl-3.0
|
1
|
import Foundation
extension String {
func truncateToSize(size: CGSize,
ellipsesString: String,
trailingText: String,
attributes: [NSAttributedString.Key : Any],
trailingTextAttributes: [NSAttributedString.Key : Any]) -> NSAttributedString {
if !willFit(to: size, attributes: attributes) {
let indexOfLastCharacterThatFits = indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: 0,
maxIndex: count)
let range = startIndex..<index(startIndex, offsetBy: indexOfLastCharacterThatFits)
let substring = self[range]
let attributedString = NSMutableAttributedString(string: substring + ellipsesString, attributes: attributes)
let attributedTrailingString = NSAttributedString(string: trailingText, attributes: trailingTextAttributes)
attributedString.append(attributedTrailingString)
return attributedString
}
else {
return NSAttributedString(string: self, attributes: attributes)
}
}
func willFit(to size: CGSize,
ellipsesString: String = "",
trailingText: String = "",
attributes: [NSAttributedString.Key : Any]) -> Bool {
let text = (self + ellipsesString + trailingText) as NSString
let boundedSize = CGSize(width: size.width, height: .greatestFiniteMagnitude)
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
let boundedRect = text.boundingRect(with: boundedSize, options: options, attributes: attributes, context: nil)
return boundedRect.height <= size.height
}
// MARK: - Private
private func indexThatFits(size: CGSize,
ellipsesString: String,
trailingText: String,
attributes: [NSAttributedString.Key : Any],
minIndex: Int,
maxIndex: Int) -> Int {
guard maxIndex - minIndex != 1 else { return minIndex }
let midIndex = (minIndex + maxIndex) / 2
let range = startIndex..<index(startIndex, offsetBy: midIndex)
let substring = String(self[range])
if !substring.willFit(to: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes) {
return indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: minIndex,
maxIndex: midIndex)
}
else {
return indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: midIndex,
maxIndex: maxIndex)
}
}
}
|
3cd6c51cbe73900667cee78743cb77cb
| 44.810127 | 125 | 0.505112 | false | false | false | false |
ShamylZakariya/Squizit
|
refs/heads/master
|
Squizit/Transitions/SaveToGalleryTransitionManager.swift
|
mit
|
1
|
//
// SaveToGalleryTransitionManager.swift
// Squizit
//
// Created by Shamyl Zakariya on 9/26/14.
// Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import UIKit
class SaveToGalleryTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let presenting = self.presenting
let scale:CGFloat = 1.075
let bigScale = CGAffineTransformMakeScale(scale, scale)
let container = transitionContext.containerView()!
let baseView = transitionContext.viewForKey(presenting ? UITransitionContextFromViewKey : UITransitionContextToViewKey)!
let dialogView = transitionContext.viewForKey(presenting ? UITransitionContextToViewKey : UITransitionContextFromViewKey)!
let dialogViewController = transitionContext.viewControllerForKey(presenting ? UITransitionContextToViewControllerKey : UITransitionContextFromViewControllerKey)! as! SaveToGalleryViewController
container.addSubview(baseView)
container.addSubview(dialogView)
if presenting {
dialogView.alpha = 0
dialogViewController.dialogView.transform = bigScale
}
let duration = self.transitionDuration(transitionContext)
UIView.animateWithDuration(duration,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: {
if presenting {
dialogView.alpha = 1
} else {
dialogViewController.dialogView.transform = bigScale
}
},
completion: nil )
UIView.animateWithDuration(duration,
delay: duration/6,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
if presenting {
dialogViewController.dialogView.transform = CGAffineTransformIdentity
} else {
dialogView.alpha = 0
}
},
completion: { finished in
transitionContext.completeTransition(true)
})
}
// return how many seconds the transiton animation will take
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
|
becb060b6d186f031721b054da54e079
| 30.241379 | 217 | 0.761221 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.