repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/AudioDetails.swift | 1 | 2229 | /**
* Copyright IBM Corporation 2018
*
* 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
/** AudioDetails. */
public struct AudioDetails: Decodable {
/// The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files.
public enum ModelType: String {
case audio = "audio"
case archive = "archive"
}
/// **For an archive-type resource,** the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource.
public enum Compression: String {
case zip = "zip"
case gzip = "gzip"
}
/// The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files.
public var type: String?
/// **For an audio-type resource,** the codec in which the audio is encoded. Omitted for an archive-type resource.
public var codec: String?
/// **For an audio-type resource,** the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource.
public var frequency: Int?
/// **For an archive-type resource,** the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource.
public var compression: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
case codec = "codec"
case frequency = "frequency"
case compression = "compression"
}
}
| mit | fcd915bd37814b13615c75a0ab4b01c9 | 40.277778 | 177 | 0.673396 | 4.127778 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Medium/Medium_093_Restore_IP_Addresses.swift | 1 | 1680 | /*
https://leetcode.com/problems/restore-ip-addresses/
#93 Restore IP Addresses
Level: medium
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
Inspired by @fiona_mao at https://leetcode.com/discuss/12790/my-code-in-java
*/
import Foundation
struct Medium_093_Restore_IP_Addresses {
// t = O(1), s = O(1)
static func restoreIpAddresses(_ s: String) -> [String] {
let chars = [Character](s)
let len = chars.count
guard len >= 4 else { return [] }
var result = [String]()
for i in 1...min(3, len-3) {
for j in i...min(i+3, len-2) {
for k in j...min(j+3, len-1) {
let s0 = String(chars[0..<i])
guard validate(s0) == true else { continue }
let s1 = String(chars[i..<j])
guard validate(s1) == true else { continue }
let s2 = String(chars[j..<k])
guard validate(s2) == true else { continue }
let s3 = String(chars[k..<len])
guard validate(s3) == true else { continue }
result.append("\(s0).\(s1).\(s2).\(s3)")
}
}
}
return result
}
static func validate(_ s: String) -> Bool {
let chars = [Character](s)
if chars.count > 1 && chars[0] == "0" { return false }
let v = Int(s) ?? Int.max
if v < 0 || v > 255 { return false }
else { return true }
}
}
| mit | 243d9a8a2afd782783057cd8997ed3cc | 30.111111 | 107 | 0.511905 | 3.716814 | false | false | false | false |
inoity/nariko | Nariko/Classes/BubbleLongPressGestureRecognizer.swift | 1 | 2457 | //
// BubbleLongPressGestureRecognizer.swift
// Nariko
//
// Created by Zsolt Papp on 13/06/16.
// Copyright © 2016 Nariko. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
open class BubbleLongPressGestureRecognizer: UILongPressGestureRecognizer, UIGestureRecognizerDelegate {
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
self.addTarget(self, action: #selector(tap(_:)))
self.minimumPressDuration = 1.5
self.numberOfTouchesRequired = 3
delegate = self
}
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view == okButton {
NarikoTool.sharedInstance.closeNarikoAlertView()
}
return true
}
}
extension BubbleLongPressGestureRecognizer {
func tap(_ g: UILongPressGestureRecognizer) {
if !isOnboarding{
switch g.state {
case .began:
if NarikoTool.sharedInstance.isAuth {
NarikoTool.sharedInstance.setupBubble()
} else {
let alertController = UIAlertController (title: "Information", message: "Please login in the settings", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.shared.openURL(url)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
NarikoTool.sharedInstance.APPDELEGATE.window!!.rootViewController!.present(alertController, animated: true, completion: nil);
}
default: break
}
}
}
}
| mit | 9c444560960e7ca79b753434351dc372 | 33.111111 | 147 | 0.557818 | 6.14 | false | false | false | false |
farshadtx/Fleet | Fleet/CoreExtensions/UINavigationController+Fleet.swift | 1 | 3352 | import UIKit
fileprivate var didSwizzle = false
extension UINavigationController {
open override class func initialize() {
super.initialize()
if !didSwizzle {
swizzlePushViewController()
swizzlePopViewController()
swizzlePopToViewController()
swizzlePopToRootViewControllerAnimated()
didSwizzle = true
}
}
fileprivate class func swizzlePushViewController() {
let originalSelector = #selector(UINavigationController.pushViewController(_:animated:))
let swizzledSelector = #selector(UINavigationController.fleet_pushViewController(_:animated:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func fleet_pushViewController(_ viewController: UIViewController, animated: Bool) {
var newViewControllers = self.viewControllers
newViewControllers.append(viewController)
self.setViewControllers(newViewControllers, animated: false)
let _ = viewController.view
}
fileprivate class func swizzlePopViewController() {
let originalSelector = #selector(UINavigationController.popViewController(animated:))
let swizzledSelector = #selector(UINavigationController.fleet_popViewControllerAnimated(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func fleet_popViewControllerAnimated(_ animated: Bool) -> UIViewController? {
var newViewControllers = self.viewControllers
let poppedViewController = newViewControllers.removeLast()
self.setViewControllers(newViewControllers, animated: false)
return poppedViewController
}
fileprivate class func swizzlePopToViewController() {
let originalSelector = #selector(UINavigationController.popToViewController(_:animated:))
let swizzledSelector = #selector(UINavigationController.fleet_popToViewController(_:animated:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func fleet_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
return fleet_popToViewController(viewController, animated: false)
}
fileprivate class func swizzlePopToRootViewControllerAnimated() {
let originalSelector = #selector(UINavigationController.popToRootViewController(animated:))
let swizzledSelector = #selector(UINavigationController.fleet_popToRootViewControllerAnimated(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func fleet_popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? {
return fleet_popToRootViewControllerAnimated(false)
}
}
| apache-2.0 | 5f3540ce5aa9937e64d155174cbb6fdd | 41.974359 | 111 | 0.74284 | 6.572549 | false | false | false | false |
nomadik223/twitter-client | TwitterClient/TwitterClient/API.swift | 1 | 5730 | //
// API.swift
// TwitterClient
//
// Created by Kent Rogers on 3/21/17.
// Copyright © 2017 Austin Rogers. All rights reserved.
//
import Foundation
import Accounts
import Social
typealias AccountCallback = (ACAccount?)->()
typealias UserCallback = (User?)->()
typealias TweetsCallback = ([Tweet]?)->()
class API {
static let shared = API()
var account : ACAccount?
private func login(callback: @escaping AccountCallback) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: accountType, options: nil) { (success, error) in
if let error = error {
print("Error: \(error.localizedDescription)")
callback(nil)
return
}
if success {
if let account = accountStore.accounts(with: accountType).first as? ACAccount {
callback(account)
}
} else {
print("The user did not allow access to their account.")
callback(nil)
}
}
}
func getOAuthUser(callback: @escaping UserCallback){
let url = URL(string: "https://api.twitter.com/1.1/account/verify_credentials.json")
if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: url, parameters: nil) {
request.account = self.account
request.perform(handler: { (data, response, error) in
if let error = error {
print("Error: \(error)")
callback(nil)
return
}
guard let response = response else { callback(nil); return }
guard let data = data else { callback(nil); return }
switch response.statusCode {
case 200...299:
JSONParser.getUser(data: data, callback: { (success, user) in
if success {
callback(user)
}
})
default:
print("Error: response came back with statusCode: \(response.statusCode)")
callback(nil)
}
})
}
}
private func updateTimeLine(url: String, callback: @escaping TweetsCallback) {
//let url = URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")
if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: URL(string: url), parameters: nil) {
request.account = self.account
request.perform(handler: { (data, response, error) in
if let error = error {
print("Error: Error requesting user's home timeline - \(error.localizedDescription)")
callback(nil)
return
}
guard let response = response else { callback(nil); return }
guard let data = data else { callback(nil); return }
switch response.statusCode {
case 200...299:
JSONParser.tweetsFrom(data: data, callback: { (success, tweets) in
if success {
callback(tweets)
}
})
case 400...499:
print("Client side error code: \(response.statusCode)")
callback(nil)
case 500...599:
print("Server side error code: \(response.statusCode)")
callback(nil)
default:
print("Something else went terribly wrong. We have a status code of: \(response.statusCode)")
callback(nil)
}
})
}
}
func getTweets(callback: @escaping TweetsCallback) {
if self.account == nil {
login(callback: { (account) in
if let account = account {
self.account = account
self.updateTimeLine(url: "https://api.twitter.com/1.1/statuses/home_timeline.json", callback: { (tweets) in
callback(tweets)
})
}
})
} else {
self.updateTimeLine(url: "https://api.twitter.com/1.1/statuses/home_timeline.json", callback: { (tweets) in
callback(tweets)
})
}
}
func getTweetsFor(_ userEx: String, callback: @escaping TweetsCallback) {
let urlString = "https://api.twitter.com/1.1/statuses/home_timeline.json?screen_name=\(userEx)"
self.updateTimeLine(url: urlString) { (tweets) in
callback(tweets)
}
}
}
| mit | 0eda518b8e29dc3d22a00acdabc8860f | 31.185393 | 135 | 0.448595 | 5.894033 | false | false | false | false |
the-grid/Portal | Portal/Models/User.swift | 1 | 1782 | import Argo
import Curry
import Foundation
import Ogra
/// A user.
public struct User {
public let avatarUrl: NSURL?
public let emailAddress: String
public let founderNumber: Int
public let id: NSUUID
public let name: String
public let sitesQuota: Int
public init(
avatarUrl: NSURL? = .None,
emailAddress: String,
founderNumber: Int,
id: NSUUID,
name: String,
sitesQuota: Int
) {
self.avatarUrl = avatarUrl
self.emailAddress = emailAddress
self.founderNumber = founderNumber
self.id = id
self.name = name
self.sitesQuota = sitesQuota
}
}
// MARK: - Decodable
extension User: Decodable {
public static func decode(json: JSON) -> Decoded<User> {
return curry(self.init)
<^> json <|? "avatar"
<*> json <| "email"
<*> json <| "founder"
<*> json <| "id"
<*> json <| "name"
<*> json <| "quotaSites"
}
}
// MARK: - Encodable
extension User: Encodable {
public func encode() -> JSON {
return .Object([
"avatar": avatarUrl.encode(),
"email": emailAddress.encode(),
"founder": founderNumber.encode(),
"id": id.encode(),
"name": name.encode(),
"quotaSites": sitesQuota.encode()
])
}
}
// MARK: - Equatable
extension User: Equatable {}
public func == (lhs: User, rhs: User) -> Bool {
return lhs.avatarUrl?.absoluteString == rhs.avatarUrl?.absoluteString
&& lhs.emailAddress == rhs.emailAddress
&& lhs.founderNumber == rhs.founderNumber
&& lhs.id == rhs.id
&& lhs.name == rhs.name
&& lhs.sitesQuota == rhs.sitesQuota
}
| mit | 938cf35f7ae2211b02b19fee75d6ddeb | 22.76 | 73 | 0.556117 | 4.232779 | false | false | false | false |
a2/passcards-swift | Sources/App/OpenSSLHelper.swift | 1 | 1163 | import CLibreSSL
import Foundation
func ECKeys(from privateKey: String) -> (privateKey: String, publicKey: String)? {
guard var privateKeyData = privateKey.data(using: .utf8) else {
return nil
}
let bp = privateKeyData.withUnsafeMutableBytes { ptr in
BIO_new_mem_buf(UnsafeMutableRawPointer(ptr), Int32(privateKeyData.count))
}
var pKey = EVP_PKEY_new()
defer { EVP_PKEY_free(pKey) }
PEM_read_bio_PrivateKey(bp, &pKey, nil, nil)
BIO_free(bp)
let ecKey = EVP_PKEY_get1_EC_KEY(pKey)
defer { EC_KEY_free(ecKey) }
EC_KEY_set_conv_form(ecKey, POINT_CONVERSION_UNCOMPRESSED)
var pub: UnsafeMutablePointer<UInt8>? = nil
let pubLen = i2o_ECPublicKey(ecKey, &pub)
let publicData = Data(buffer: UnsafeBufferPointer(start: pub, count: Int(pubLen)))
let privBN = EC_KEY_get0_private_key(ecKey)
let privLen = (BN_num_bits(privBN) + 7) / 8
var privateData = Data(count: Int(privLen) + 1)
privateData.withUnsafeMutableBytes { pointer in
_ = BN_bn2bin(privBN, pointer.advanced(by: 1))
}
return (privateData.base64EncodedString(), publicData.base64EncodedString())
}
| mit | 4381263974b425f6b92dc6c51caf0bb8 | 31.305556 | 86 | 0.681857 | 3.276056 | false | false | false | false |
cozkurt/coframework | COFramework/COFramework/Swift/Extentions/UISegmentedControl+Additions.swift | 1 | 2070 | //
// UISegmentedControl+Additions.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import UIKit
extension UISegmentedControl {
public func defaultConfiguration(font: UIFont, color: UIColor) {
let defaultAttributes: [NSAttributedString.Key: Any]? = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): font,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): color
]
setTitleTextAttributes(defaultAttributes, for: .normal)
}
public func selectedConfiguration(font: UIFont, color: UIColor) {
let selectedAttributes: [NSAttributedString.Key: Any]? = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): font,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): color
]
setTitleTextAttributes(selectedAttributes, for: .selected)
}
public func removeDividers() {
setDividerImage(UIImage(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
public func removeBorders() {
setBackgroundImage(imageWithColor(color: backgroundColor!), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
// create a 1x1 image with this color
public func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
| gpl-3.0 | cb4a3b4e129fe2902ba66f20c32b7fc9 | 40.38 | 141 | 0.694055 | 4.914489 | false | false | false | false |
hulinSun/Better | better/better/Classes/Photo/View/GroupTableView.swift | 1 | 1779 | //
// GroupTableView.swift
// better
//
// Created by Hony on 2016/11/22.
// Copyright © 2016年 Hony. All rights reserved.
//
import UIKit
class GroupTableView: UITableView {
var datas: [PhotoGroupItem]?{
didSet{
reloadData()
}
}
typealias clickClosure = (_ tableview: UITableView, _ index: IndexPath, _ collectionData: PhotoGroupItem)-> Void
var clickClosure: clickClosure?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
register(UINib.init(nibName: "PhotoGroupCell", bundle: nil), forCellReuseIdentifier: "PhotoGroupCell")
delegate = self
dataSource = self
separatorStyle = .none
}
}
extension GroupTableView: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas?.count ?? 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoGroupCell") as! PhotoGroupCell
cell.item = datas?[indexPath.row]
cell.backgroundColor = UIColor.rgb(red: 240, green: 240, blue: 240)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.clickClosure?(tableView, indexPath,(datas?[indexPath.item])!)
}
}
| mit | 556b19af64cef4461760bfb460838aea | 28.114754 | 116 | 0.646396 | 4.813008 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Views/MXCalendarView/Views/MXCalendarView.swift | 1 | 5935 | //
// Created by Maxim Pervushin on 14/01/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
public class MXCalendarView: UIView {
// MARK: MXCalendarView @IB
@IBOutlet weak var collectionView: UICollectionView?
// MARK: MXCalendarView public
var dateSelectedHandler: ((date:NSDate) -> Void)?
var cellConfigurationHandler: ((cell:UICollectionViewCell) -> Void)?
var willDisplayMonthHandler: ((month:NSDate) -> Void)?
var calendar = NSCalendar.currentCalendar() {
didSet {
updateUI()
}
}
var startDate = NSDate(timeIntervalSince1970: 0) {
didSet {
updateUI()
}
}
var endDate = NSDate() {
didSet {
updateUI()
}
}
var selectedDate: NSDate? {
didSet {
updateUI()
}
}
func scrollToDate(date: NSDate, animated: Bool) {
if let indexPath = indexPathForDate(date) {
collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: animated)
}
}
public func updateUI() {
dispatch_async(dispatch_get_main_queue()) {
self.collectionView?.reloadData()
}
}
// MARK: MXCalendarView private
private func indexPathForDate(date: NSDate) -> NSIndexPath? {
guard let _ = collectionView else {
return nil
}
let adjustedDate = date.dateByIgnoringTime()
if adjustedDate < startDate || adjustedDate > endDate {
return nil
}
let section = adjustedDate.year() - startYear
var row = adjustedDate.month() - 1
if section == 0 {
row -= startMonth
}
return NSIndexPath(forRow: row, inSection: section)
}
private var startYear: Int {
return calendar.component(.Year, fromDate: startDate)
}
private var startMonth: Int {
return calendar.component(.Month, fromDate: startDate)
}
private var endYear: Int {
return calendar.component(.Year, fromDate: endDate)
}
private var endMonth: Int {
return calendar.component(.Month, fromDate: endDate)
}
}
extension MXCalendarView: UICollectionViewDataSource {
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return endYear - startYear + 1
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 12 - startMonth + 1
} else if section == numberOfSectionsInCollectionView(collectionView) - 1 {
return endMonth
} else {
return 12
}
}
private func monthAtIndexPath(indexPath: NSIndexPath) -> NSDate {
guard let collectionView = collectionView else {
return NSDate(timeIntervalSince1970: 0)
}
var monthToAdd = indexPath.row
if indexPath.section > 0 {
for section in 0 ... indexPath.section - 1 {
monthToAdd += collectionView.numberOfItemsInSection(section)
}
}
return startDate.firstDayOfMonth().dateByAddingMonths(monthToAdd)
}
private func dateSelected(date: NSDate) {
selectedDate = date
dateSelectedHandler?(date: date)
}
private func cellConfiguration(cell: UICollectionViewCell) {
if let dayCell = cell as? MXDayCell {
cellConfigurationHandler?(cell: dayCell)
}
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MXMonthCell.defaultReuseIdentifier, forIndexPath: indexPath) as! MXMonthCell
cell.monthView?.calendar = calendar
cell.monthView?.startDate = startDate
cell.monthView?.endDate = endDate
cell.monthView?.selectedDate = selectedDate
cell.monthView?.month = monthAtIndexPath(indexPath)
cell.monthView?.dateSelectedHandler = dateSelected
cell.monthView?.cellConfigurationHandler = cellConfiguration
return cell
}
}
extension MXCalendarView: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
willDisplayMonthHandler?(month: monthAtIndexPath(indexPath))
}
}
extension MXCalendarView: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.width)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSizeZero
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSizeZero
}
}
| mit | ce70ea235a7e7b0ec359dad3182d5402 | 32.156425 | 185 | 0.681045 | 5.679426 | false | false | false | false |
jregnauld/SwiftyInstagram | SwiftyInstagram/Classes/Manager/LoginManager.swift | 1 | 1897 | //
// LoginManager.swift
// Pods
//
// Created by Julien Regnauld on 8/11/16.
//
//
import Foundation
public typealias InstagramAuthorizationHandler = ((_ result: AuthorizationResult) -> Void)
public enum AuthorizationResult {
case success()
case failure(error: Error)
}
open class LoginManager: AuthorizationDelegate {
fileprivate let _session: Session
fileprivate let _authorizationViewController: AuthorizationViewController
fileprivate var _authorizationHandler: InstagramAuthorizationHandler?
public init(session: Session = Session.sharedSession(), authorizationViewController: AuthorizationViewController? = nil) {
self._session = session
if let authorizationViewController = authorizationViewController {
self._authorizationViewController = authorizationViewController
} else {
self._authorizationViewController = AuthorizationViewController(authorizationURL: self._session.authorizationURL)
}
self._authorizationViewController.delegate = self
}
open func loginFromViewController(_ viewController: UIViewController, completed: @escaping InstagramAuthorizationHandler) {
self._authorizationHandler = completed
let navigationController = UINavigationController(rootViewController: self._authorizationViewController)
viewController.present(navigationController, animated: true, completion: nil)
}
open func getWebViewAnswer(_ url: URL) {
self.checkAnswer(url) { (result) in
self._authorizationHandler!(result)
}
}
func checkAnswer(_ url:URL, completed: InstagramAuthorizationHandler) {
let builder = LoginAnswerBuilder(url: url)
switch builder.getAnswer() {
case is String:
self._session.accessToken = builder.getAnswer() as! String
completed(.success())
case is Error:
completed(.failure(error: builder.getAnswer() as! Error))
default: break
}
}
}
| mit | 6c5a4560bba1c651deaf1bf8c70c05dc | 36.94 | 125 | 0.752768 | 5.058667 | false | false | false | false |
atrick/swift | test/decl/protocol/special/coding/struct_codable_member_type_lookup.swift | 3 | 22791 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// A top-level CodingKeys type to fall back to in lookups below.
public enum CodingKeys : String, CodingKey {
case topLevel
}
// MARK: - Synthesized CodingKeys Enum
// Structs which get synthesized Codable implementations should have visible
// CodingKey enums during member type lookup.
struct SynthesizedStruct : Codable {
let value: String = "foo"
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'value' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualifiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualifiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the SynthesizedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - No CodingKeys Enum
// Structs which don't get synthesized Codable implementations should expose the
// appropriate CodingKeys type.
struct NonSynthesizedStruct : Codable { // expected-note 4 {{'NonSynthesizedStruct' declared here}}
// No synthesized type since we implemented both methods.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should clearly fail -- we shouldn't get a synthesized
// type here.
public func qualifiedFoo(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
internal func qualifiedBar(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
fileprivate func qualifiedBaz(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
private func qualifiedQux(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
// Unqualified lookups should find the public top-level CodingKeys type.
public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.topLevel) }
internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.topLevel) }
fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.topLevel) }
private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.topLevel) }
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
qux(CodingKeys.nested)
}
}
// MARK: - Explicit CodingKeys Enum
// Structs which explicitly define their own CodingKeys types should have
// visible CodingKey enums during member type lookup.
struct ExplicitStruct : Codable {
let value: String = "foo"
public enum CodingKeys {
case a
case b
case c
}
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the ExplicitStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - CodingKeys Enums in Extensions
// Structs which get a CodingKeys type in an extension should be able to see
// that type during member type lookup.
struct ExtendedStruct : Codable {
let value: String = "foo"
// Don't get an auto-synthesized type.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the ExtendedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
extension ExtendedStruct {
enum CodingKeys : String, CodingKey {
case a, b, c
}
}
struct A {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on A.CodingKeys or top-level type.
}
}
}
extension A {
enum CodingKeys : String, CodingKey {
case a
}
}
struct B : Codable {
// So B conforms to Codable using CodingKeys.b below.
var b: Int = 0
struct Inner {
var value: Int = 42
func foo() {
print(CodingKeys.b) // Not found on top-level type.
}
}
}
extension B {
enum CodingKeys : String, CodingKey {
case b
}
}
struct C : Codable {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on C.CodingKeys or top-level type.
}
}
}
extension C.Inner {
enum CodingKeys : String, CodingKey {
case value
}
}
struct GenericCodableStruct<T : Codable> : Codable {}
func foo(_: GenericCodableStruct<Int>.CodingKeys) // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
struct sr6886 {
struct Nested : Codable {}
let Nested: Nested // Don't crash with a coding key that is the same as a nested type name
}
// Don't crash if we have a static property with the same name as an ivar that
// we will encode. We check the actual codegen in a SILGen test.
struct StaticInstanceNameDisambiguation : Codable {
static let version: Float = 0.42
let version: Int = 42
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'version' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
}
| apache-2.0 | 403b2392a2690e99711b4b18869ff83a | 33.067265 | 197 | 0.69545 | 4.756052 | false | false | false | false |
IamAlchemist/Animations | Animations/BezierPathAnimation.swift | 2 | 1850 | //
// BezierPathAnimation.swift
// DemoAnimations
//
// Created by Wizard Li on 4/21/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
class BezierPathViewController : UIViewController {
var shipLayer : CALayer?
override func viewDidLoad() {
super.viewDidLoad()
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 30, y: 150))
bezierPath.addCurveToPoint(CGPoint(x: 330, y:150), controlPoint1: CGPoint(x: 105, y:0), controlPoint2: CGPoint(x: 255, y: 300))
let pathLayer = CAShapeLayer()
pathLayer.path = bezierPath.CGPath
pathLayer.fillColor = UIColor.clearColor().CGColor
pathLayer.strokeColor = UIColor.redColor().CGColor
pathLayer.lineWidth = 3
view.layer.addSublayer(pathLayer)
let shipLayer = CALayer()
shipLayer.frame = CGRect(x: 30, y: 0, width: 64, height: 64)
shipLayer.position = CGPoint(x: 30, y: 150)
shipLayer.contents = UIImage(named: "Ship")?.CGImage
view.layer.addSublayer(shipLayer)
self.shipLayer = shipLayer
let animation = CAKeyframeAnimation()
animation.keyPath = "position"
animation.duration = 4
animation.path = bezierPath.CGPath
animation.rotationMode = kCAAnimationRotateAuto
animation.delegate = self
shipLayer.addAnimation(animation, forKey: nil)
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if flag {
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation"
animation.duration = 2
animation.byValue = NSNumber(double: M_PI * 2)
shipLayer?.addAnimation(animation, forKey: nil)
}
}
}
| mit | f27b0e7cf0a5d1182c1f43b436f588ed | 32.618182 | 135 | 0.625744 | 4.634085 | false | false | false | false |
Yalantis/PullToRefresh | PullToRefresh/UIScrollView+PullToRefresh.swift | 1 | 4768 | //
// Created by Anastasiya Gorban on 4/14/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at https://github.com/Yalantis/PullToRefresh
//
import Foundation
import UIKit
import ObjectiveC
private var topPullToRefreshKey: UInt8 = 0
private var bottomPullToRefreshKey: UInt8 = 0
public extension UIScrollView {
fileprivate(set) var topPullToRefresh: PullToRefresh? {
get {
return objc_getAssociatedObject(self, &topPullToRefreshKey) as? PullToRefresh
}
set {
objc_setAssociatedObject(self, &topPullToRefreshKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate(set) var bottomPullToRefresh: PullToRefresh? {
get {
return objc_getAssociatedObject(self, &bottomPullToRefreshKey) as? PullToRefresh
}
set {
objc_setAssociatedObject(self, &bottomPullToRefreshKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func addPullToRefresh(_ pullToRefresh: PullToRefresh, action: @escaping () -> ()) {
pullToRefresh.scrollView = self
pullToRefresh.action = action
let view = pullToRefresh.refreshView
switch pullToRefresh.position {
case .top:
removePullToRefresh(at: .top)
topPullToRefresh = pullToRefresh
case .bottom:
removePullToRefresh(at: .bottom)
bottomPullToRefresh = pullToRefresh
}
view.frame = defaultFrame(forPullToRefresh: pullToRefresh)
addSubview(view)
#if swift(>=4.2)
sendSubviewToBack(view)
#else
sendSubview(toBack: view)
#endif
}
func refresher(at position: Position) -> PullToRefresh? {
switch position {
case .top:
return topPullToRefresh
case .bottom:
return bottomPullToRefresh
}
}
func removePullToRefresh(at position: Position) {
switch position {
case .top:
topPullToRefresh?.refreshView.removeFromSuperview()
topPullToRefresh = nil
case .bottom:
bottomPullToRefresh?.refreshView.removeFromSuperview()
bottomPullToRefresh = nil
}
}
func removeAllPullToRefresh() {
removePullToRefresh(at: .top)
removePullToRefresh(at: .bottom)
}
func startRefreshing(at position: Position) {
switch position {
case .top:
topPullToRefresh?.startRefreshing()
case .bottom:
bottomPullToRefresh?.startRefreshing()
}
}
func endRefreshing(at position: Position) {
switch position {
case .top:
topPullToRefresh?.endRefreshing()
case .bottom:
bottomPullToRefresh?.endRefreshing()
}
}
func endAllRefreshing() {
endRefreshing(at: .top)
endRefreshing(at: .bottom)
}
}
internal func - (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets(
top: lhs.top - rhs.top,
left: lhs.left - rhs.left,
bottom: lhs.bottom - rhs.bottom,
right: lhs.right - rhs.right
)
}
internal extension UIScrollView {
var normalizedContentOffset: CGPoint {
get {
let contentOffset = self.contentOffset
let contentInset = self.effectiveContentInset
let output = CGPoint(x: contentOffset.x + contentInset.left, y: contentOffset.y + contentInset.top)
return output
}
}
var effectiveContentInset: UIEdgeInsets {
get {
if #available(iOS 11, *) {
return adjustedContentInset
} else {
return contentInset
}
}
set {
if #available(iOS 11.0, *), contentInsetAdjustmentBehavior != .never {
contentInset = newValue - safeAreaInsets
} else {
contentInset = newValue
}
}
}
func defaultFrame(forPullToRefresh pullToRefresh: PullToRefresh) -> CGRect {
let view = pullToRefresh.refreshView
var originY: CGFloat
switch pullToRefresh.position {
case .top:
originY = -view.frame.size.height
case .bottom:
originY = contentSize.height
}
let height = view.frame.height + (pullToRefresh.topPadding ?? 0)
return CGRect(x: 0, y: originY, width: frame.width, height: height)
}
}
| mit | 2af6d314ab9aa95683e20401b02c9fb5 | 27.380952 | 113 | 0.584732 | 5.233809 | false | false | false | false |
domenicosolazzo/practice-swift | Views/Pickers/SimplePicker/SimplePicker/ViewController.swift | 1 | 1412 | //
// ViewController.swift
// SimplePicker
//
// Created by Domenico Solazzo on 04/05/15.
// License MIT
//
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// PickerView
var uiPicker: UIPickerView?
override func viewDidLoad() {
super.viewDidLoad()
uiPicker = UIPickerView()
// Setting the data source
uiPicker?.dataSource = self
// Setting the delegate
uiPicker?.delegate = self
// Setting the picker in the center of the screen
uiPicker?.center = view.center
// Adding a subview
self.view.addSubview(uiPicker!)
}
//- MARK: UIPickerDataSource
// How many components you want the picker to render
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView == uiPicker{
return 1
}
return 0
}
// How many rows you want to render
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == uiPicker{
return 10
}
return 0
}
//- MARK: UIPickerDelegate
// Showing the text for each item
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return "\(row + 1)"
}
}
| mit | 5c5336b78389db9e6965d22fad43c75b | 23.77193 | 111 | 0.604816 | 5.115942 | false | false | false | false |
saroar/barta | Sources/Acronym.swift | 1 | 851 | import StORM
import PostgresStORM
class Acronym: PostgresStORM {
var id: Int = 0
var short: String = ""
var long: String = ""
override open func table() -> String { return "acronyms"}
override func to(_ this: StORMRow) {
id = this.data["id"] as? Int ?? 0
short = this.data["short"] as? String ?? ""
long = this.data["long"] as? String ?? ""
}
func rows() -> [Acronym] {
var rows = [Acronym]()
for i in 0..<self.results.rows.count {
let row = Acronym()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
func asDictionary() -> [String: Any] {
return [
"id": self.id,
"short": self.short,
"long": self.long
]
}
}
| apache-2.0 | 03beffb4e90ed49d43d05b963b717ad2 | 24.029412 | 61 | 0.474736 | 3.868182 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/UpdateMobile/MobileCodeEntry/MobileCodeEntryViewController.swift | 1 | 1858 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformUIKit
import RxRelay
import RxSwift
final class MobileCodeEntryViewController: BaseScreenViewController {
// MARK: - Private IBOutlets
@IBOutlet private var codeEntryTextFieldView: TextFieldView!
@IBOutlet private var descriptionLabel: UILabel!
@IBOutlet private var changeNumberButtonView: ButtonView!
@IBOutlet private var confirmCodeButtonView: ButtonView!
@IBOutlet private var resendCodeButtonView: ButtonView!
// MARK: - Private Properties
private var keyboardInteractionController: KeyboardInteractionController!
private let presenter: MobileCodeEntryScreenPresenter
private let disposeBag = DisposeBag()
// MARK: - Init
init(presenter: MobileCodeEntryScreenPresenter) {
self.presenter = presenter
super.init(nibName: MobileCodeEntryViewController.objectName, bundle: .module)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
set(
barStyle: presenter.barStyle,
leadingButtonStyle: presenter.leadingButton,
trailingButtonStyle: .none
)
titleViewStyle = presenter.titleView
keyboardInteractionController = KeyboardInteractionController(in: self)
codeEntryTextFieldView.setup(viewModel: presenter.codeEntryTextFieldModel, keyboardInteractionController: keyboardInteractionController)
descriptionLabel.content = presenter.descriptionContent
changeNumberButtonView.viewModel = presenter.changeNumberViewModel
resendCodeButtonView.viewModel = presenter.resendCodeViewModel
confirmCodeButtonView.viewModel = presenter.confirmViewModel
}
}
| lgpl-3.0 | d56c0db4546392e2652dd131ffa7e7f0 | 35.411765 | 144 | 0.745288 | 5.661585 | false | false | false | false |
rxwei/cuda-swift | Scripts/kernel_example.swift | 1 | 1174 | #!/usr/bin/swift -F. -L. -L/usr/local/cuda/lib -I. -I/usr/local/cuda/include -target x86_64-apple-macosx10.10
import NVRTC
import Warp
import CUDADriver
guard let device = Device.all.first else {
fatalError("No CUDA device available")
}
/// Data
let n = 1024
var x = DeviceArray<Double>(repeating: 1.0, count: n)
var y = DeviceArray<Double>(fromHost: Array(sequence(first: 0, next: {$0+1}).prefix(n)))
var result = DeviceArray<Double>(capacity: n)
device.withContext { context in
/// SAXPY: Z = a * X + Y
let saxpySource =
"extern \"C\" __global__ void saxpy(size_t n, double a, double *x, double *y, double *z) {"
+ " size_t tid = blockIdx.x * blockDim.x + threadIdx.x;"
+ " if (tid < n) z[tid] = a * x[tid] + y[tid];"
+ "}"
let module = try Module(source: saxpySource, compileOptions: [
.computeCapability(device.computeCapability),
.contractIntoFMAD(false),
.useFastMath
])
let saxpy = module.function(named: "saxpy")!
/// Launch kernel
try saxpy<<<(n/128, 128)>>>[.int(1024), .double(5.1), .array(&x), .array(&y), .array(&result)]
}
print(result.hostArray)
| mit | 67e9c4d05f0a8f50be927dcb8b763261 | 31.611111 | 109 | 0.613288 | 2.964646 | false | false | false | false |
sgrinich/BeatsByKenApp | BeatsByKen/BeatsByKen/CSVTableViewCell.swift | 1 | 2686 | //
// CSVTableViewCell.swift
// BeatsByKen
//
// Created by Stephen Grinich on 9/6/15.
// Copyright (c) 2015 Liz Shank. All rights reserved.
//
import UIKit
class CSVTableViewCell: UITableViewCell{
//
// int HEIGHT = 35;
// int WIDTH = 122;
//
// int PARTICIPANT_X = 18;
// int PARTICIPANT_Y = 29;
//
// int SESSION_X = 139;
// int SESSION_Y = 29;
//
// int TRIAL_X = 261;
// int TRIAL_Y = 29;
//
// int START_TIME_X = 383;
// int START_TIME_Y = 29;
//
// int END_TIME_X = 505;
// int END_TIME_Y = 29;
//
// int BEAT_COUNT_X = 627;
// int BEAT_COUNT_Y = 29;
var participantIDLabel: UILabel!
var sessionLabel: UILabel!
var trialLabel: UILabel!
var startTimeLabel: UILabel!
var endTimeLabel: UILabel!
var beatCountLabel: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
participantIDLabel = UILabel(frame: CGRectMake(contentView.frame.origin.x+10, contentView.frame.origin.y+10, 130, contentView.frame.height/2));
sessionLabel = UILabel(frame: CGRectMake(participantIDLabel.frame.origin.x+participantIDLabel.frame.width, contentView.frame.origin.y+10, 130, contentView.frame.height/2));
trialLabel = UILabel(frame: CGRectMake(sessionLabel.frame.origin.x+sessionLabel.frame.width, contentView.frame.origin.y+10, 100, contentView.frame.height/2));
startTimeLabel = UILabel(frame: CGRectMake(trialLabel.frame.origin.x+trialLabel.frame.width, contentView.frame.origin.y+10, 130, contentView.frame.height/2));
endTimeLabel = UILabel(frame: CGRectMake(startTimeLabel.frame.origin.x+startTimeLabel.frame.width, contentView.frame.origin.y+10, 130, contentView.frame.height/2));
beatCountLabel = UILabel(frame: CGRectMake(endTimeLabel.frame.origin.x+endTimeLabel.frame.width, contentView.frame.origin.y+10, 130, contentView.frame.height/2));
contentView.addSubview(participantIDLabel);
contentView.addSubview(sessionLabel);
contentView.addSubview(trialLabel);
contentView.addSubview(startTimeLabel);
contentView.addSubview(endTimeLabel);
contentView.addSubview(beatCountLabel);
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
| mit | d62b3be4e7aeb34466fec5c6996c3fff | 32.160494 | 180 | 0.668652 | 3.783099 | false | false | false | false |
calebd/swift | test/SILOptimizer/exclusivity_static_diagnostics.swift | 1 | 8643 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
import Swift
func takesTwoInouts<T>(_ p1: inout T, _ p2: inout T) { }
func simpleInoutDiagnostic() {
var i = 7
// FIXME: This diagnostic should be removed if static enforcement is
// turned on by default.
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&i, &i)
}
func inoutOnInoutParameter(p: inout Int) {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'p', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&p, &p)
}
func swapNoSuppression(_ i: Int, _ j: Int) {
var a: [Int] = [1, 2, 3]
// expected-error@+2{{overlapping accesses to 'a', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
swap(&a[i], &a[j]) // no-warning
}
class SomeClass { }
struct StructWithMutatingMethodThatTakesSelfInout {
var f = SomeClass()
mutating func mutate(_ other: inout StructWithMutatingMethodThatTakesSelfInout) { }
mutating func mutate(_ other: inout SomeClass) { }
mutating func callMutatingMethodThatTakesSelfInout() {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self)
}
mutating func callMutatingMethodThatTakesSelfStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self.f)
}
}
var globalStruct1 = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesGlobalStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'globalStruct1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
globalStruct1.mutate(&globalStruct1.f)
}
class ClassWithFinalStoredProp {
final var s1: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var s2: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesClassStoredPropInout() {
s1.mutate(&s2.f) // no-warning
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
s1.mutate(&s1.f)
let local1 = self
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
local1.s1.mutate(&local1.s1.f)
}
}
func violationWithGenericType<T>(_ p: T) {
var local = p
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&local, &local)
}
// Helper.
struct StructWithTwoStoredProp {
var f1: Int = 7
var f2: Int = 8
}
// Take an unsafe pointer to a stored property while accessing another stored property.
func violationWithUnsafePointer(_ s: inout StructWithTwoStoredProp) {
// FIXME: This needs to be statically enforced.
withUnsafePointer(to: &s.f1) { (ptr) in
_ = s.f1
}
// FIXME: We may want to allow this case for known-layout stored properties.
withUnsafePointer(to: &s.f1) { (ptr) in
_ = s.f2
}
}
// Tests for Fix-Its to replace swap(&collection[a], &collection[b]) with
// collection.swapAt(a, b)
struct StructWithField {
var f = 12
}
struct StructWithFixits {
var arrayProp: [Int] = [1, 2, 3]
var dictionaryProp: [Int : Int] = [0 : 10, 1 : 11]
mutating
func shouldHaveFixIts<T>(_ i: Int, _ j: Int, _ param: T, _ paramIndex: T.Index) where T : MutableCollection {
var array1 = [1, 2, 3]
// expected-error@+2{{overlapping accesses}}{{5-41=array1.swapAt(i + 5, j - 2)}}
// expected-note@+1{{conflicting access is here}}
swap(&array1[i + 5], &array1[j - 2])
// expected-error@+2{{overlapping accesses}}{{5-49=self.arrayProp.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &self.arrayProp[j])
var localOfGenericType = param
// expected-error@+2{{overlapping accesses}}{{5-75=localOfGenericType.swapAt(paramIndex, paramIndex)}}
// expected-note@+1{{conflicting access is here}}
swap(&localOfGenericType[paramIndex], &localOfGenericType[paramIndex])
// expected-error@+2{{overlapping accesses}}{{5-39=array1.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
Swift.swap(&array1[i], &array1[j]) // no-crash
}
mutating
func shouldHaveNoFixIts(_ i: Int, _ j: Int) {
var s = StructWithField()
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&s.f, &s.f)
var array1 = [1, 2, 3]
var array2 = [1, 2, 3]
// Swapping between different arrays should cannot have the
// Fix-It.
swap(&array1[i], &array2[j]) // no-warning no-fixit
swap(&array1[i], &self.arrayProp[j]) // no-warning no-fixit
// Dictionaries aren't MutableCollections so don't support swapAt().
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&dictionaryProp[i], &dictionaryProp[j])
// We could safely Fix-It this but don't now because the left and
// right bases are not textually identical.
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &arrayProp[j])
// We could safely Fix-It this but we're not that heroic.
// We don't suppress when swap() is used as a value
let mySwap: (inout Int, inout Int) -> () = swap
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
func myOtherSwap<T>(_ a: inout T, _ b: inout T) {
swap(&a, &b) // no-warning
}
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
}
}
func inoutSeparateStructStoredProperties() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f2) // no-error
}
func inoutSameStoredProperty() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f1)
// expected-error@-1{{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSeparateTupleElements() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.1) // no-error
}
func inoutSameTupleElement() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.0) // no-error
// expected-error@-1{{overlapping accesses to 't.0', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSameTupleNamedElement() {
var t = (name1: 1, name2: 4)
takesTwoInouts(&t.name2, &t.name2) // no-error
// expected-error@-1{{overlapping accesses to 't.name2', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSamePropertyInSameTuple() {
var t = (name1: 1, name2: StructWithTwoStoredProp())
takesTwoInouts(&t.name2.f1, &t.name2.f1) // no-error
// expected-error@-1{{overlapping accesses to 't.name2.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
| apache-2.0 | 66e328e0a046fa5523f2189cb6e4ff91 | 37.932432 | 147 | 0.700683 | 3.849889 | false | false | false | false |
JohnUni/SensorTester | network/AsyncTcpSocket.swift | 1 | 24423 | /*
* TcpSocket.swift
* SensorTester
*
* Created by John Wong on 8/09/2015.
* Copyright (c) 2015-2015, John Wong <john dot innovation dot au at gmail dot com>
*
* All rights reserved.
*
* http://www.bitranslator.com
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
// server socket
@_silgen_name("tcpsocket_listen") func c_tcpsocket_listen(serveraddress: UnsafePointer<UInt8>, port: Int32) -> Int32
@_silgen_name("tcpsocket_accept") func c_tcpsocket_accept(serversocketfd: Int32, remoteip: UnsafePointer<UInt8>, remoteport: UnsafePointer<Int32>) -> Int32
// server check acceptable
@_silgen_name("is_listened") func c_is_listened(socketfd: Int32) -> Int32
@_silgen_name("is_acceptable") func c_is_acceptable(socketfd: Int32) -> Int32
// client socket
@_silgen_name("tcpsocket_connect") func c_tcpsocket_connect(host: UnsafePointer<UInt8>, port: Int32) -> Int32
@_silgen_name("tcpsocket_send") func c_tcpsocket_send(socketfd: Int32, buffer: UnsafePointer<UInt8>, datalen: Int32) -> Int32
@_silgen_name("tcpsocket_recv") func c_tcpsocket_recv(socketfd: Int32, buffer: UnsafePointer<UInt8>, buffersize: Int32, recvdatalen: UnsafePointer<Int32>) -> Int32
// client check connected, readable and writable
@_silgen_name("is_connected") func c_is_connected(socketfd: Int32) -> Int32
@_silgen_name("is_readable") func c_is_readable(socketfd: Int32) -> Int32
@_silgen_name("is_writable") func c_is_writable(socketfd: Int32) -> Int32
// close socket
@_silgen_name("tcpsocket_close") func c_tcpsocket_close(socketfd: Int32) -> Int32
public enum enumAsyncSocketStatus: Int32
{
// for initial
case ASYNC_SOCKET_STATUS_UNKNOWN = 0
case ASYNC_SOCKET_STATUS_INIT = 1
// for server socket
case ASYNC_SOCKET_STATUS_LISTENING = 2
case ASYNC_SOCKET_STATUS_LISTENED = 3
// for client socket
case ASYNC_SOCKET_STATUS_CONNECTING = 4
case ASYNC_SOCKET_STATUS_CONNECTED = 5
// for exception
case ASYNC_SOCKET_STATUS_ERROR = 6
}
//public enum enumAsyncServerSocketStatus: Int32
//{
// case ASYNC_SERVER_SOCKET_STATUS_UNKNOWN = 0
// case ASYNC_SERVER_SOCKET_STATUS_INIT = 1
// case ASYNC_SERVER_SOCKET_STATUS_LISTENING = 2
// case ASYNC_SERVER_SOCKET_STATUS_ERROR = 4
//}
//
//public enum enumAsyncClientSocketStatus: Int32
//{
// case ASYNC_CLIENT_SOCKET_STATUS_UNKNOWN = 0
// case ASYNC_CLIENT_SOCKET_STATUS_INIT = 1
// case ASYNC_CLIENT_SOCKET_STATUS_CONNECTING = 2
// case ASYNC_CLIENT_SOCKET_STATUS_CONNECTED = 3
// case ASYNC_CLIENT_SOCKET_STATUS_ERROR = 4
//}
public class AsyncTcpSocket : NSObject
{
var m_fd: Int32 = 0
var m_bAutoCloseSocketWhenErrorOccurs: Bool = true
var m_nMessageQueueId: Int32 = 1
}
public class AsyncTcpServerSocket : AsyncTcpSocket
{
private var m_nServerSocketStatus: enumAsyncSocketStatus = .ASYNC_SOCKET_STATUS_UNKNOWN
public func getSocketStatus() -> enumAsyncSocketStatus
{
return m_nServerSocketStatus
}
public func reset() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
c_tcpsocket_close( m_fd )
m_fd = 0
}
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_UNKNOWN
bRet = true
return bRet
}
public func startAsyncListen(host: String, port: Int32) -> Bool
{
var bRet: Bool = false
if( .ASYNC_SOCKET_STATUS_ERROR == m_nServerSocketStatus )
{
self.reset()
}
if( .ASYNC_SOCKET_STATUS_UNKNOWN == m_nServerSocketStatus )
{
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_INIT
//@_silgen_name("tcpsocket_listen") func c_tcpsocket_listen(serveraddress: UnsafePointer<Int8>, port: Int32) -> Int32
// RETURN VALUES of socket_fd: fd>0 success, fd<0 failure
// expected status: initial => in-processing or failure
let nListen: Int32 = c_tcpsocket_listen( host, port: port )
if( nListen > 0 )
{
m_fd = nListen
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_LISTENING
bRet = true
}
else if( nListen < 0 )
{
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
print( "TcpSocket startAsyncListen error! nConnect:\(nListen)\n", terminator: "" )
}
else
{
// nothing else
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
}
}
else
{
print( "TcpSocket startAsyncListen status error! \(m_nServerSocketStatus)\n", terminator: "" )
}
return bRet
}
public func isListened() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
if( .ASYNC_SOCKET_STATUS_LISTENED == m_nServerSocketStatus )
{
bRet = true
}
else if( .ASYNC_SOCKET_STATUS_LISTENING == m_nServerSocketStatus )
{
// RETURN VALUES 1=connected, 0=timeout(nothing), <0 is error
let nCheck: Int32 = c_is_listened( m_fd )
if( nCheck > 0 )
{
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_LISTENED
bRet = true
}
else if( 0 == nCheck )
{
// timeout, nothing todo, only wait
}
else if( nCheck < 0 )
{
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket check listened error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket check listened error! not close\n", terminator: "" )
}
}
}
else
{
}
}
return bRet
}
//@_silgen_name("is_acceptable") func c_is_acceptable(socketfd: Int32) -> Int32
public func isAcceptable() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
if( .ASYNC_SOCKET_STATUS_LISTENED == m_nServerSocketStatus )
{
// RETURN VALUES 1=data arrived, 0=timeout(nothing), <0 is error
let nCheck: Int32 = c_is_acceptable( m_fd )
if( nCheck > 0 )
{
bRet = true
}
else if( 0 == nCheck )
{
// timeout, no client try to connect
}
else if( nCheck < 0 )
{
m_nServerSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket check acceptable error! and close error:%d\n", nCheck, terminator: "" )
}
else
{
print( "TcpSocket check acceptable error! not close error:%d\n", nCheck, terminator: "" )
}
}
}
}
return bRet
}
//@_silgen_name("tcpsocket_accept") func c_tcpsocket_accept(serversocketfd: Int32, remoteip: UnsafePointer<Int8>, remoteport: UnsafePointer<Int32>) -> Int32
public func acceptClient() -> AsyncTcpClientSocket?
{
var pClient: AsyncTcpClientSocket?
let bufferSize: Int32 = 4096
var byteIpBuffer:Array<UInt8> = Array<UInt8>(count:Int(bufferSize), repeatedValue:0x0)
var nPort: Int32 = 0
let nAccept: Int32 = c_tcpsocket_accept( m_fd, remoteip: &byteIpBuffer, remoteport: &nPort )
if( nAccept > 0 )
{
print( "accept client. port:\(nPort) \n", terminator: "" )
pClient = AsyncTcpClientSocket( fd: nAccept )
}
else if( nAccept == 0 )
{
// time out
}
else
{
print( "accept eror!! \n", terminator: "" )
}
return pClient
}
}
public class AsyncTcpClientSocket : AsyncTcpSocket
{
private var m_nClientSocketStatus: enumAsyncSocketStatus = .ASYNC_SOCKET_STATUS_UNKNOWN
public func getSocketStatus() -> enumAsyncSocketStatus
{
return m_nClientSocketStatus
}
override init()
{
super.init()
}
init( fd: Int32 )
{
super.init()
m_fd = fd
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_CONNECTED
}
public func reset() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
c_tcpsocket_close( m_fd )
m_fd = 0
}
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_UNKNOWN
bRet = true
return bRet
}
public func startAsyncConnect(host: String, port: Int32) -> Bool
{
var bRet: Bool = false
if( .ASYNC_SOCKET_STATUS_ERROR == m_nClientSocketStatus )
{
self.reset()
}
if( .ASYNC_SOCKET_STATUS_UNKNOWN == m_nClientSocketStatus )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_INIT
//@_silgen_name("tcpsocket_connect") func c_tcpsocket_connect(host: UnsafePointer<Int8>, port: Int32) -> Int32
// RETURN VALUES of socket_fd: fd>0 success, fd<0 failure
// expected status: initial => in-processing or failure
let nConnect: Int32 = c_tcpsocket_connect( host, port: port )
if( nConnect > 0 )
{
m_fd = nConnect
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_CONNECTING
bRet = true
}
else if( nConnect < 0 )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
print( "TcpSocket startAsyncConnect error! nConnect:\(nConnect)\n", terminator: "" )
}
else
{
// nothing else
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
}
}
else
{
print( "TcpSocket startAsyncConnect status error! \(m_nClientSocketStatus)\n", terminator: "" )
}
return bRet
}
//@_silgen_name("is_connected") func c_is_connected(socketfd: Int32) -> Int32
public func isConnected() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus )
{
bRet = true
}
else if( .ASYNC_SOCKET_STATUS_CONNECTING == m_nClientSocketStatus )
{
// RETURN VALUES 1=connected, 0=timeout(nothing), <0 is error
let nCheck: Int32 = c_is_connected( m_fd )
if( nCheck > 0 )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_CONNECTED
bRet = true
}
else if( 0 == nCheck )
{
// timeout, nothing todo, only wait
}
else if( nCheck < 0 )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket check connected error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket check connected error! not close\n", terminator: "" )
}
}
}
else
{
}
}
return bRet
}
//@_silgen_name("is_writable") func c_is_writable(socketfd: Int32) -> Int32
public func isWritable() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus )
{
// RETURN VALUES 1=writable, 0=timeout(nothing), <0 is error
let nCheck: Int32 = c_is_writable( m_fd )
if( nCheck > 0 )
{
bRet = true
}
else if( 0 == nCheck )
{
// timeout, cannot write
}
else if( nCheck < 0 )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket check writable error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket check writable error! not close\n", terminator: "" )
}
}
}
}
return bRet
}
//@_silgen_name("is_readable") func c_is_readable(socketfd: Int32) -> Int32
public func isReadable() -> Bool
{
var bRet: Bool = false
if( m_fd != 0 )
{
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus )
{
// RETURN VALUES 1=data arrived, 0=timeout(nothing), <0 is error
let nCheck: Int32 = c_is_readable( m_fd )
if( nCheck > 0 )
{
bRet = true
}
else if( 0 == nCheck )
{
// timeout, no data arrived
}
else if( nCheck < 0 )
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket check readable error! and close error:%d\n", nCheck, terminator: "" )
}
else
{
print( "TcpSocket check readable error! not close error:%d\n", nCheck, terminator: "" )
}
}
}
}
return bRet
}
public func send(data: Array<UInt8>) -> ( result: Bool, sendCount: Int32 )
{
var bRet: Bool = false
var nSendCount: Int32 = 0
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus && m_fd > 0 )
{
let nDataLen: Int32 = Int32(data.count)
nSendCount = c_tcpsocket_send(m_fd, buffer: data, datalen: nDataLen)
if( nSendCount > 0 )
{
if( nSendCount == nDataLen )
{
bRet = true
}
else
{
bRet = true
print( "TcpSocket send partly, size:\(nDataLen), send:\(nSendCount), as success \n", terminator: "" )
}
}
else
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket send error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket send error! not close\n", terminator: "" )
}
}
}
else
{
print( "TcpSocket cannot send since there is no fd.\n", terminator: "" )
}
return (bRet, nSendCount)
}
public func send(str: String) -> ( result: Bool, sendCount: Int32 )
{
var bRet: Bool = false
var nSendCount: Int32 = 0
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus && m_fd > 0 )
{
let nDataLen: Int32 = Int32(strlen(str))
nSendCount = c_tcpsocket_send(m_fd, buffer: str, datalen: nDataLen)
if( nSendCount > 0 )
{
if( nSendCount == nDataLen )
{
bRet = true
}
else
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
print( "TcpSocket send string partly, size:\(nDataLen), send:\(nSendCount), as failure and close!\n", terminator: "" )
c_tcpsocket_close( m_fd )
m_fd = 0
}
else
{
print( "TcpSocket send string partly, size:\(nDataLen), send:\(nSendCount), as failure but not close!\n", terminator: "" )
}
}
}
else
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket send string error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket send string error! but not close\n", terminator: "" )
}
}
}
else
{
print( "TcpSocket cannot send string since there is no fd.\n", terminator: "" )
}
return (bRet, nSendCount)
}
public func send(data: NSData) -> ( result: Bool, sendCount: Int32 )
{
var bRet: Bool = false
var nSendCount: Int32 = 0
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus && m_fd > 0 )
{
let nDataLen: Int32 = Int32(data.length)
var buffer:Array<UInt8> = Array<UInt8>(count:Int(nDataLen),repeatedValue:0x0)
data.getBytes( &buffer, length: Int(nDataLen) )
nSendCount = c_tcpsocket_send(m_fd, buffer: buffer, datalen: nDataLen)
if( nSendCount > 0 )
{
if( nSendCount == nDataLen )
{
bRet = true
}
else
{
bRet = true
print( "TcpSocket send NSData partly, size:\(nDataLen), send:\(nSendCount), as success!\n", terminator: "" )
}
}
else
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket send NSData error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket send NSData error! but not close\n", terminator: "" )
}
}
}
else
{
print( "TcpSocket cannot send NSData since there is no fd.\n", terminator: "" )
}
return (bRet, nSendCount)
}
public func sendMessage( message: IDataMessage ) -> Bool
{
var bRet: Bool = false
var nSendCount: Int32 = -1
m_nMessageQueueId += 1
message.updateMessageId( m_nMessageQueueId )
let data: NSData? = message.getMessageBuffer()
if( data != nil )
{
if( data!.length > 0 )
{
(bRet, nSendCount) = self.send( data! )
}
}
return bRet
}
public func recv( bufferSize: Int32 ) -> ( result: Bool, data: NSData? )
{
var bRet: Bool = false
var dataRet: NSData? = nil
if( .ASYNC_SOCKET_STATUS_CONNECTED == m_nClientSocketStatus && m_fd > 0 )
{
let buffer:Array<UInt8> = Array<UInt8>(count:Int(bufferSize), repeatedValue:0x0)
// RETURN VALUES: >0 number of bytes recv, 0=closed by peer, -1=failure
var nRecvCount: Int32 = 0
let nResult: Int32 = c_tcpsocket_recv(m_fd, buffer: buffer, buffersize: bufferSize, recvdatalen: &nRecvCount)
if( nResult > 0 )
{
dataRet = NSData( bytes: buffer, length: Int(nRecvCount) )
bRet = true
}
else if( 0 == nResult )
{
bRet = false
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket recv closed by peer! and close\n", terminator: "" )
}
else
{
print( "TcpSocket recv closed by peer! but not close\n", terminator: "" )
}
}
else
{
m_nClientSocketStatus = .ASYNC_SOCKET_STATUS_ERROR
if( m_bAutoCloseSocketWhenErrorOccurs )
{
c_tcpsocket_close( m_fd )
m_fd = 0
print( "TcpSocket recv NSData error! and close\n", terminator: "" )
}
else
{
print( "TcpSocket recv NSData error! but not close\n", terminator: "" )
}
}
}
else
{
print( "TcpSocket cannot recv NSData since there is no fd.\n", terminator: "" )
}
return (result: bRet, data: dataRet)
}
}
| apache-2.0 | 20e9af62961e9245bf047100f95adb3d | 33.790598 | 163 | 0.505384 | 4.334931 | false | false | false | false |
Kruks/AdminSettingsControl | AdminSettingsControl/AdminSettingsConstants.swift | 1 | 3288 | //
// AdminSettingsConstants.swift
// AdminSettingsPodCode
//
// Created by Krutika on 10/16/17.
// Copyright © 2017 kahuna. All rights reserved.
//
import UIKit
public struct AdminSettingsConstants {
public static let adminBundleID = "org.cocoapods.AdminSettingsControl"
public enum UniqueKeyConstants {
static let enableDeviceLogs = "EnableDeviceLogs"
static let enableProfileLogs = "EnableProfileLogs"
public static let titleKey = "title"
public static let userDefaultsKey = "key"
public static let templateURL = "templateURL"
public static let adminSettingsXibName = "AdminSettingsViewController"
}
enum adminStringConstants {
static let notApplicable = "N/A"
static let serverURLSectionTitle = "Server URL"
static let otherDetailsSectionTitle = "Other Details"
static let templateURLAppendString = "%@%@?deviceType=IOS&serviceRequestTypeId=&language=en"
}
enum ColorConstants {
static let lightGrayBorderColor = UIColor(red: 248.0 / 255.0, green: 248.0 / 255.0, blue: 248.0 / 255.0, alpha: 1.0)
}
public enum SettingTableViewOtherDetialsCellIdentifier {
public static let logCampId = "Logcamp App ID"
public static let deviceId = "Device ID"
public static let appVersion = "App Version"
public static let pushNotification = "Push Notification Token"
public static let profileLog = "Enable Profile Logs"
public static let deviceLog = "Enable Device Logs"
public static let emailData = "Email Data"
public static let viewMySrDetailLink = "View My SR Details URL"
public static let createSrTemplateLink = "Create SR Template URL"
public static let viewMySrDetailVer = "View My SR Details Version"
public static let createSrTemplateVer = "Create SR Template Version"
public static let serverURLTitle = "Server URL"
public static let loginServerURLTitle = "Login Server URL"
public static let templateURLTitle = "Template URL"
public static let navigationTitle = "Settings"
public static let uploadtoDriveTitle = "Upload DB To Drive"
public static let selectSSLPinningType = "Select SSL Pinning Type"
}
enum StaticAppMessages {
// Upload To Google Drive Text
static let creatingDBText = "Creating DBBackup folder in your drive"
static let uploadingDBText = "Uploading DBBackup in your drive"
static let sharingFileToUsers = "Sharing DBBackup to developers"
static let uploadingText = "Uploading Image"
static let alertOkTitle = "OK"
}
enum headerFontDetails {
static let backBtnArrowWidth = 34
static let backBtnArrowHeight = 34
static let backBtnArrowNegativeSpacer = -10
static let saveBtnWidth = 71
static let saveBtnHeight = 30
}
public enum SSLPinningConstants {
public static let pinningTypeKey = "SSLPinningType"
public static let publicKeyPinning = "PublickKeyPinning"
public static let ceritificatePinning = "CertificatePinning"
public static let disablePinning = "DisablePinning"
public static let prevPinningTypeKey = "PrevSSLPinningType"
}
}
| mit | 954339bccec19141b665a9ca239e71c2 | 40.607595 | 124 | 0.695771 | 4.715925 | false | false | false | false |
xedin/swift | test/decl/protocol/req/subscript.swift | 2 | 4433 | // RUN: %target-typecheck-verify-swift
protocol P1 {
subscript (i: Int) -> Int { get } // expected-note{{protocol requires subscript with type '(Int) -> Int'}}
}
class C1 : P1 {
subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
struct S1 : P1 {
subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
struct S1Error : P1 { // expected-error{{type 'S1Error' does not conform to protocol 'P1'}}
subscript (i: Int) -> Double { // expected-note{{candidate has non-matching type '(Int) -> Double'}}
get {
return Double(i)
}
set {}
}
}
//===----------------------------------------------------------------------===//
// Get-only subscript requirements
//===----------------------------------------------------------------------===//
protocol SubscriptGet {
subscript(a : Int) -> Int { get } // expected-note {{protocol requires subscript with type '(Int) -> Int'; do you want to add a stub?}}
}
class SubscriptGet_Get : SubscriptGet {
subscript(a : Int) -> Int { return 0 } // ok
// for static cross-conformance test below: expected-note@-1 {{candidate operates on an instance, not a type as required}}
}
class SubscriptGet_GetSet : SubscriptGet {
subscript(a : Int) -> Int { get { return 42 } set {} } // ok
}
//===----------------------------------------------------------------------===//
// Get-set subscript requirements
//===----------------------------------------------------------------------===//
protocol SubscriptGetSet {
subscript(a : Int) -> Int { get set } // expected-note {{protocol requires subscript with type '(Int) -> Int'}}
}
class SubscriptGetSet_Get : SubscriptGetSet { // expected-error {{type 'SubscriptGetSet_Get' does not conform to protocol 'SubscriptGetSet'}}
subscript(a : Int) -> Int { return 0 } // expected-note {{candidate is not settable, but protocol requires it}}
}
class SubscriptGetSet_GetSet : SubscriptGetSet {
subscript(a : Int) -> Int { get { return 42 } set {} } // ok
}
//===----------------------------------------------------------------------===//
// Generic subscript requirements
//===----------------------------------------------------------------------===//
protocol Initable {
init()
}
protocol GenericSubscriptProtocol {
subscript<T : Initable>(t: T.Type) -> T { get set }
// expected-note@-1 {{protocol requires subscript with type '<T where T : Initable> (T.Type) -> T'; do you want to add a stub?}}
}
struct GenericSubscriptWitness : GenericSubscriptProtocol {
subscript<T : Initable>(t: T.Type) -> T {
get {
return t.init()
}
set { }
}
}
struct GenericSubscriptNoWitness : GenericSubscriptProtocol {}
// expected-error@-1 {{type 'GenericSubscriptNoWitness' does not conform to protocol 'GenericSubscriptProtocol'}}
//===----------------------------------------------------------------------===//
// Static subscript requirements
//===----------------------------------------------------------------------===//
protocol StaticSubscriptGet {
static subscript(a : Int) -> Int { get } // expected-note {{protocol requires subscript with type '(Int) -> Int'; do you want to add a stub?}}
}
class StaticSubscriptGet_Get : StaticSubscriptGet {
static subscript(a : Int) -> Int { return 0 } // ok
// for static cross-conformance test below: expected-note@-1 {{candidate operates on a type, not an instance as required}}
}
class StaticSubscriptGet_GetSet : StaticSubscriptGet {
static subscript(a : Int) -> Int { get { return 42 } set {} } // ok
}
protocol StaticSubscriptGetSet {
static subscript(a : Int) -> Int { get set } // expected-note {{protocol requires subscript with type '(Int) -> Int'}}
}
class StaticSubscriptGetSet_Get : StaticSubscriptGetSet { // expected-error {{type 'StaticSubscriptGetSet_Get' does not conform to protocol 'StaticSubscriptGetSet'}}
static subscript(a : Int) -> Int { return 0 } // expected-note {{candidate is not settable, but protocol requires it}}
}
class StaticSubscriptGetSet_GetSet : StaticSubscriptGetSet {
static subscript(a : Int) -> Int { get { return 42 } set {} } // ok
}
extension SubscriptGet_Get: StaticSubscriptGet {} // expected-error {{type 'SubscriptGet_Get' does not conform to protocol 'StaticSubscriptGet'}}
extension StaticSubscriptGet_Get: SubscriptGet {} // expected-error {{type 'StaticSubscriptGet_Get' does not conform to protocol 'SubscriptGet'}}
| apache-2.0 | 2b82cbc456f9483c4cbe6377df19e9ea | 33.905512 | 166 | 0.579517 | 4.428571 | false | false | false | false |
yasuo-/smartNews-clone | SmartNews/News2ViewController.swift | 1 | 12923 | //
// News2ViewController.swift
// SmartNews
//
// CNN(all) RSSのXMLデータをTableControllerに加えていく
// Created by 栗原靖 on 2017/04/03.
// Copyright © 2017年 Yasuo Kurihara. All rights reserved.
//
import UIKit
import SDWebImage
// UIViewController
// UITableViewDelegate
// UITableViewDataSource
// UIWebViewDelegate
// XMLParserDelegate
// これらのメソッドを使う宣言を行う
class News2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, XMLParserDelegate {
// 初期化
var urlArray = [String]()
// tableView
var tableView: UITableView = UITableView()
// 引っ張ってロード
var refreshControl: UIRefreshControl!
// webView
var webView: UIWebView = UIWebView()
// goButton
var goButton: UIButton!
// back Button
var backButton: UIButton!
// cancel Button
var cancelButton: UIButton!
// dots view
var dotsView: DotsLoader! = DotsLoader()
// parser
var parser = XMLParser()
// 両方入るもの
var totalBox = NSMutableArray()
var elements = NSMutableDictionary()
var element = String()
var titleString = NSMutableString()
var linkString = NSMutableString()
var urlString = String()
// はじめに画面が呼ばれた時に出るもの
override func viewDidLoad() {
super.viewDidLoad()
// コードでviewを作る
// 背景画像を作る
let imageView = UIImageView()
// 画面いっぱい広げる
imageView.frame = self.view.bounds
imageView.image = UIImage(named: "2.jpg")
// 画面に貼り付ける
self.view.addSubview(imageView)
// 引っ張って更新
refreshControl = UIRefreshControl()
// ローディングの色
refreshControl.tintColor = UIColor.white
// どのメソッド => 自分
//
refreshControl.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged)
// tableViewを作成する
tableView.delegate = self
tableView.dataSource = self
// x,y軸
// width => 自分のviewの全体の幅
// height => 自分のviewの全体の高さ - 54.0(tabの高さ分)
tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height - 54.0)
// 背景をクリアにすると画像が透けて見える (デフォルトは白)
// tableView.backgroundColor = UIColor.clear
tableView.backgroundColor = UIColor.white
// tableViewとrefreshViewが合体する
tableView.addSubview(refreshControl)
// 自分の画面をつける refreshControlが付いている
self.view.addSubview(tableView)
// webViewの作成
// 大きさ tableViewの大きさにする
webView.frame = tableView.frame
webView.delegate = self
webView.scalesPageToFit = true//self
// .scaleAspectFit => 画面の中に収まる
webView.contentMode = .scaleAspectFit
self.view.addSubview(webView)
// はじめに画面が呼ばれた時にwebViewがあるのは今回はだめ
// Hiddenにしておく
webView.isHidden = true
// webViewを表示するのはtableViewのcellを押した時
// 対象のLinkを表示する
// 1つ進むbutton作成
goButton = UIButton()
// frameを決める
goButton.frame = CGRect(x: self.view.frame.size.width - 50, y: self.view.frame.size.height - 128, width: 50, height: 50)
// 画像つける for => どういう状態の時に表示するか
goButton.setImage(UIImage(named: "go.png"), for: .normal)
// .touchUpInside => ボタンを押して離した
goButton.addTarget(self, action: #selector(nextPage), for: .touchUpInside)
// 画面に付ける
self.view.addSubview(goButton)
// 戻るボタンの作成
backButton = UIButton()
backButton.frame = CGRect(x: 10, y: self.view.frame.size.height - 128, width: 50, height: 50)
backButton.setImage(UIImage(named: "back.png"), for: .normal)
backButton.addTarget(self, action: #selector(backPage), for: .touchUpInside)
self.view.addSubview(backButton)
// キャンセルボタンの作成
cancelButton = UIButton()
cancelButton.frame = CGRect(x: 10, y: 80, width: 50, height: 50)
cancelButton.setImage(UIImage(named: "cancel.png"), for: .normal)
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
self.view.addSubview(cancelButton)
// 作成したボタンをisHidden = trueにする
goButton.isHidden = true
backButton.isHidden = true
cancelButton.isHidden = true
// ドッツビューの作成
dotsView.frame = CGRect(x: 0, y: self.view.frame.size.height / 3, width: self.view.frame.size.width, height: 100)
// 個数
dotsView.dotsCount = 5
// 大きさ
dotsView.dotsRadius = 10
// くっつける
self.view.addSubview(dotsView)
// hiddenにする
dotsView.isHidden = true
// XMLを解析する(パース)
// parser
let url: String = "https://www.cnet.com/rss/all/"
let urlToSend: URL = URL(string: url)!
parser = XMLParser(contentsOf: urlToSend)!
totalBox = []
parser.delegate = self
// 解析する
parser.parse()
// 更新がされる
tableView.reloadData()
// Do any additional setup after loading the view.
}
// refresh
// 下から上に引っ張った時呼ばれる
func refresh() {
// どれだけ時間をおいて元に戻すか 2.0 => 2秒後
perform(#selector(delay), with: nil, afterDelay: 2.0)
}
// delay
func delay() {
// XMLを解析する(パース)
// parser
let url: String = "https://www.cnet.com/rss/all/"
let urlToSend: URL = URL(string: url)!
parser = XMLParser(contentsOf: urlToSend)!
totalBox = []
parser.delegate = self
// 解析する
parser.parse()
// 更新がされる
tableView.reloadData()
// リフレッシュを終わらせる
refreshControl.endRefreshing()
}
// nextPage
// webViewを1page進める
func nextPage() {
webView.goForward()
}
// backPage
// webViewを1ページ戻す
func backPage() {
webView.goBack()
}
// cancel
// webViewを隠す
func cancel() {
webView.isHidden = true
goButton.isHidden = true
backButton.isHidden = true
cancelButton.isHidden = true
}
// tableviewのデリゲート
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return totalBox.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
// ハイライトなくす
cell.selectionStyle = .none
cell.backgroundColor = UIColor.clear
cell.textLabel?.text = (totalBox[indexPath.row] as AnyObject).value(forKey: "title") as? String
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)
//cell.textLabel?.textColor = UIColor.white
cell.textLabel?.textColor = UIColor.darkText
cell.detailTextLabel?.text = (totalBox[indexPath.row] as AnyObject).value(forKey: "link") as? String
cell.detailTextLabel?.font = UIFont.boldSystemFont(ofSize: 12.0)
//cell.detailTextLabel?.textColor = UIColor.white
cell.detailTextLabel?.textColor = UIColor.darkGray
// image add
let urlStr = urlArray[indexPath.row].addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url: URL = URL(string: urlStr)!
cell.imageView?.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholderImage.png"))
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// WebViewを表示する
let linkURL = (totalBox[indexPath.row] as AnyObject).value(forKey: "link") as? String
// let urlStr = linkURL?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url: URL = URL(string: linkURL!)!
let urlRequest = NSURLRequest(url: url)
webView.loadRequest(urlRequest as URLRequest)
}
// webViewDidStartLoad
// load スタート
func webViewDidStartLoad(_ webView: UIWebView) {
dotsView.isHidden = false
dotsView.startAnimating()
}
// webViewDidFinishLoad
// load 終わったら
func webViewDidFinishLoad(_ webView: UIWebView) {
dotsView.isHidden = true
dotsView.stopAnimating()
webView.isHidden = false
goButton.isHidden = false
backButton.isHidden = false
cancelButton.isHidden = false
}
// タグを見つけた時
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
// elementにelementNameを入れて行く
element = elementName
if element == "item" {
elements = NSMutableDictionary()
elements = [:]
titleString = NSMutableString()
titleString = ""
linkString = NSMutableString()
linkString = ""
urlString = String()
} else if element == "media:thumbnail" {
// 画像が入ってるkey => url
urlString = attributeDict["url"]!
urlArray.append(urlString)
}
}
// タグの間にデータがあった時(開始タグと終了タグでくくられた箇所にデータが存在した時に実行されるメソッド)
func parser(_ parser: XMLParser, foundCharacters string: String) {
if element == "title" {
titleString.append(string)
} else if element == "link" {
linkString.append(string)
}
}
// タグの終了を見つけた時
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
// itemという要素の中にあるなら
if elementName == "item" {
// titleString(linkString)の中身が空でないなら
if titleString != "" {
// elementsにkeyを付与しながらtitleString(linkStirng)をセットする
elements.setObject(titleString, forKey: "title" as NSCopying)
}
if linkString != "" {
// elementsにkeyを付与しながらtitleString(linkStirng)をセットする
elements.setObject(linkString, forKey: "link" as NSCopying)
}
// add
elements.setObject(urlString, forKey: "url" as NSCopying)
// totalBoxの中にelementsを入れる
totalBox.add(elements)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | cf59d3ee0072c3bbd68d2fd9efad0a6b | 28.341709 | 179 | 0.576297 | 4.510622 | false | false | false | false |
theMatys/myWatch | myWatch/Source/UI/Controllers/MWDeviceChooserController.swift | 1 | 6868 | //
// MWDeviceChooserController.swift
// myWatch
//
// Created by Máté on 2017. 05. 20..
// Copyright © 2017. theMatys. All rights reserved.
//
import UIKit
class MWDeviceChooserController: MWViewController, MWFirstLaunchViewController, MWBCommunicatorDelegate, UITableViewDataSource
{
//MARK: Member variables
@IBOutlet weak var imageBar: MWFirstLaunchImageBar!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDesc: UILabel!
@IBOutlet weak var tableViewDevices: UITableView!
@IBOutlet weak var stackViewSearching: UIStackView!
@IBOutlet weak var labelNoBluetooth: MWLabel!
@IBOutlet weak var buttonForwarder: MWButton!
private var avaiableDevices: [MWDevice] = [MWDevice]()
fileprivate var selectedDevice: MWDevice?
{
didSet
{
buttonForwarder.isEnabled = selectedDevice != nil
}
}
//MARK: - Inherited functions from: MWViewController
override func viewDidLoad()
{
super.viewDidLoad()
buttonForwarder.disableButton()
buttonForwarder.staysHighlighted = true
setupTableView()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//MARK: Inherited functions form: MWFirstLaunchControllerProtocol
func getFirstLaunchImageBar() -> MWFirstLaunchImageBar!
{
return imageBar
}
//MARK: Inherited functions from: MWFirstLaunchViewController
func getImageBar() -> MWFirstLaunchImageBar
{
return self.imageBar
}
func getButton() -> MWButton?
{
return self.buttonForwarder
}
func viewControllerDidGetPresented()
{
setupBluetooth()
}
//MARK: Inherited functions from: MWBCommunicatorDelegate
func bluetoothCommunicator(_ communicator: MWBCommunicator, didUpdateBluetoothAvailability availability: Bool)
{
if(availability)
{
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseOut, animations: {
self.stackViewSearching.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseIn, animations: {
self.labelNoBluetooth.alpha = 0.0
}, completion: nil)
MWBCommunicator.shared.lookForDevices()
}
else
{
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseOut, animations: {
self.labelNoBluetooth.alpha = 1.0
}, completion: nil)
}
}
func bluetoothCommunicator(_ communicator: MWBCommunicator, didFindCompatibleDevice device: MWDevice)
{
avaiableDevices.append(device)
let indexPath: IndexPath = IndexPath(row: avaiableDevices.count - 1, section: 0)
tableViewDevices.insertRows(at: [indexPath], with: .fade)
}
//MARK: Inherted functions from: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return avaiableDevices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
guard let cell = tableView.dequeueReusableCell(withIdentifier: MWIdentifiers.CellIdentifiers.deviceChooserDeviceCell, for: indexPath) as? MWDeviceCell else
{
fatalError("The dequed cell is not an instance of \"MWDeviceCell\".")
}
cell.prepare(device: avaiableDevices[indexPath.row], controller: self)
return cell
}
//MARK: Private functions
private func setupTableView()
{
tableViewDevices.dataSource = self
tableViewDevices.tableFooterView = UIView(frame: .zero)
}
private func setupBluetooth()
{
MWBCommunicator.shared.initializeBluetooth(with: self)
}
//MARK: Navigation functions
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
super.prepare(for: segue, sender: sender)
var destination: MWConnectingController!
MWUtil.downcast(to: &destination, from: segue.destination)
destination.device = selectedDevice! //It should not be nil, because we only allow to forward when there is a device selected from the list.
}
}
//MARK: -
class MWDeviceCell: UITableViewCell
{
//MARK: Member variables
@IBOutlet weak var imageViewIcon: MWImageView!
@IBOutlet weak var labelText: UILabel!
@IBOutlet weak var line: UIView!
private var device: MWDevice!
private var controller: MWDeviceChooserController?
private var appendedID: Bool = false
//MARK: - Instance functions
func prepare(device: MWDevice, controller: MWDeviceChooserController)
{
self.device = device
self.controller = controller
if(!appendedID)
{
labelText.text = labelText.text?.appending(device.identifier)
appendedID = true
}
if(controller.tableViewDevices.visibleCells.count >= 1)
{
line.alpha = 0.0
}
else
{
line.backgroundColor = controller.tableViewDevices.separatorColor
}
}
//MARK: Inherited functions from: UITableViewCell
internal override func setSelected(_ selected: Bool, animated: Bool)
{
MWUtil.execute(ifNotNil: controller) {
if(selected)
{
UIView.transition(with: self.imageViewIcon, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.imageViewIcon.tintingColor = MWDefaults.Colors.defaultTintColor
}, completion: nil)
UIView.transition(with: self.labelText, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.labelText.textColor = MWDefaults.Colors.defaultTintColor
}, completion: nil)
self.controller!.selectedDevice = self.device
}
else
{
UIView.transition(with: self.imageViewIcon, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.imageViewIcon.tintingColor = UIColor.white
}, completion: nil)
UIView.transition(with: self.labelText, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.labelText.textColor = UIColor.white
}, completion: nil)
self.controller!.selectedDevice = nil
}
}
}
}
| gpl-3.0 | 7b5fb452d7901755a6c24ab0ae9ff6e0 | 31.382075 | 163 | 0.6252 | 5.100297 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_B019_ApplicativeFunctorsArrays.playground/section-2.swift | 2 | 1811 | import UIKit
/*
// Applicative Functors - Arrays
//
// Based on:
// http://www.objc.io/books/ (Chapter 14, Functors, Applicative Functors, and Monads)
// (Functional Programming in Swift, by Chris Eidhof, Florian Kugler, and Wouter Swierstra)
/===================================*/
/*---------------------------------------------------------------------/
// pure
/---------------------------------------------------------------------*/
func pure<A>(value: A) -> [A] {
return [value]
}
func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { x in { y in f(x, y) } }
}
/*---------------------------------------------------------------------/
// <*>
/---------------------------------------------------------------------*/
infix operator <*> { associativity left precedence 150 }
func <*><A, B>(fs: [(A -> B)], xs: [A]) -> [B] {
if fs.isEmpty { return [] }
return reduce(fs, []) { $0 + xs.map($1) }
}
/*---------------------------------------------------------------------/
// Example: List comprehensions... non-deterministic computations
/---------------------------------------------------------------------*/
let mapList = pure({ $0 + 1 }) <*> [1, 2, 3]
mapList
let mapList2 = pure(curry(+)) <*> [10, 20, 30] <*> [1, 2, 3]
let comboList = [{ $0 + 1 }, { $0 + 100 }] <*> [1, 2, 3]
comboList
let comboList2 = [curry(+), curry(*)] <*> [10, 20, 30] <*> [1, 2, 3]
/*---------------------------------------------------------------------/
// </>
//
// ==> Haskell's <$>
//
// (<$>) :: (Functor f) => (a -> b) -> f a -> f b
// f <$> x = fmap f x
/---------------------------------------------------------------------*/
infix operator </> { precedence 170 }
public func </> <A, B>(l: A -> B, r: [A]) -> [B] {
return pure(l) <*> r
}
curry(+) </> [10, 20, 30] <*> [1, 2, 3]
| gpl-3.0 | d64e836c19d5fa431ea3a1b4af135d1e | 27.296875 | 94 | 0.335726 | 3.804622 | false | false | false | false |
rugheid/Swift-MathEagle | MathEagle/Linear Algebra/MatrixVector.swift | 1 | 1478 | //
// MatrixVector.swift
// SwiftMath
//
// Created by Rugen Heidbuchel on 11/01/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Foundation
// MARK: Vector - Matrix Product
public func * <T: MatrixCompatible> (left: Vector<T>, right: Matrix<T>) -> Vector<T> {
if left.length != right.dimensions.rows {
NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The vector's length (\(left.length)) is not equal to the matrix's number of rows (\(right.dimensions.rows)).", userInfo: nil).raise()
}
if left.length == 0 { return Vector() }
var elements = [T]()
var i = 0
while i < left.length {
elements.append(left.dotProduct(right.column(i)))
i += 1
}
return Vector(elements)
}
public func * <T: MatrixCompatible> (left: Matrix<T>, right: Vector<T>) -> Vector<T> {
if right.length != left.dimensions.columns {
NSException(name: NSExceptionName(rawValue: "Unequal dimensions"), reason: "The vector's length (\(right.length)) is not equal to the matrix's number of columns (\(left.dimensions.columns)).", userInfo: nil).raise()
}
if right.length == 0 { return Vector() }
var elements = [T]()
var i = 0
while i < right.length {
elements.append(right.dotProduct(left.row(i)))
i += 1
}
return Vector(elements)
}
| mit | c7005c5f0e6e9e7d297610abcd334457 | 24.929825 | 223 | 0.596076 | 3.951872 | false | false | false | false |
iOSTestApps/WordPress-iOS | WordPress/WordPressTest/MockWordPressComApi.swift | 15 | 786 | import Foundation
class MockWordPressComApi : WordPressComApi {
var postMethodCalled = false
var URLStringPassedIn:String?
var parametersPassedIn:AnyObject?
var successBlockPassedIn:((AFHTTPRequestOperation!, AnyObject!) -> Void)?
var failureBlockPassedIn:((AFHTTPRequestOperation!, NSError!) -> Void)?
override func POST(URLString: String!, parameters: AnyObject!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) -> AFHTTPRequestOperation! {
postMethodCalled = true
URLStringPassedIn = URLString
parametersPassedIn = parameters
successBlockPassedIn = success
failureBlockPassedIn = failure
return AFHTTPRequestOperation()
}
}
| gpl-2.0 | d15968d5c74f6d60a2c2307c92a83a68 | 40.368421 | 211 | 0.711196 | 6 | false | false | false | false |
drodriguez56/lotifyMeSwift | LotifyMe/HTTP.swift | 1 | 4161 | //
// HTTP.swift
// LotifyMe
//
// Created by Daniel K. Chan on 1/26/15.
// Copyright (c) 2015 LocoLabs. All rights reserved.
//
import Foundation
// NEW PICK POST REQUEST FUNCTION
func newPickPostRequest(popupViewControllerCallingViewController: AnyObject) {
struct Status : JSONJoy {
var status: String?
init() {
}
init(_ decoder: JSONDecoder) {
status = decoder["status"].string
}
}
var postRequest = HTTPTask()
let pick: Dictionary<String,String> = [
"email": "\(retrieveSession())",
"game": cleanGameTypeInput(gameTypeGlobal),
"draw_date": dateGlobal,
"number1": numberGlobal[0],
"number2": numberGlobal[1],
"number3": numberGlobal[2],
"number4": numberGlobal[3],
"number5": numberGlobal[4],
"number6": numberGlobal[5],
"multiplier": "\(multiGlobal)"
]
let params: Dictionary<String,AnyObject> = [
"pick": pick
]
println("Ready to send postRequest for Pick#create, with the following parameters: \(params)") // Report
postRequest.POST(
"\(rootPath)/picks",
parameters: params,
success: {
(response: HTTPResponse) in
println("newPickPostRequest() called: Server returned success") // Report
println("*")
println(response.text())
var jsonAsString = "\(response.text())" as String
if oldTicket(jsonParseOldTicketDate(jsonAsString)) == 1 {
var result = jsonParseOldTicketResult(jsonAsString)
alert(
"Game Results",
"This game has already been drawn, and your result is: \(result). Best of luck as always!",
popupViewControllerCallingViewController
)
} else {
alert(
"\(gameTypeGlobal) Ticket Submitted",
"You will receive an email at \(retrieveSession()) when the results come out.",
popupViewControllerCallingViewController
)
}
if response.responseObject != nil {
let resp = Status(JSONDecoder(response.responseObject!))
println("Response from server has content: \(response.text())") // Report
resetNewPickInputVariables()
println("Expecting resetNewPickInputVariables() to have been called") // Report
}
},
failure: {
(error: NSError, response: HTTPResponse?) in
println("newPickPostRequest() called: Server returned failure") // Report
if "\(response?.text())" == "Optional(\"fail to create pick\")" {
println("Reason for failure: Invalid pick, server rollback") // Report
alert(
"Duplicate Ticket",
"Looks like you've already submitted that ticket before...",
popupViewControllerCallingViewController
)
} else if "\(response?.text())" == "nil" {
println("Reason for failure: Cannot contact server") // Report
alert(
"No Internet Connection",
"Looks like you don't have a connection right now...",
popupViewControllerCallingViewController
)
} else {
println("Reason for failure: Uncaught exception") // Report
alert(
"Oops",
"Looks like something went wrong. Please try again!",
popupViewControllerCallingViewController
)
}
}
)
} | mit | 5eb4a2757a32125e2a5df033c068c688 | 39.019231 | 115 | 0.489546 | 5.852321 | false | false | false | false |
neoneye/SwiftyFORM | Source/Cells/TextFieldCell.swift | 1 | 12364 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public class CustomTextField: UITextField {
public func configure() {
backgroundColor = .clear
autocapitalizationType = .sentences
autocorrectionType = .default
spellCheckingType = .no
returnKeyType = .done
}
}
public enum TextCellState {
case noMessage
case temporaryMessage(message: String)
case persistentMessage(message: String)
}
public struct TextFieldFormItemCellSizes {
public let titleLabelFrame: CGRect
public let textFieldFrame: CGRect
public let errorLabelFrame: CGRect
public let cellHeight: CGFloat
}
public struct TextFieldFormItemCellModel {
var title: String = ""
var toolbarMode: ToolbarMode = .simple
var placeholder: String = ""
var keyboardType: UIKeyboardType = .default
var returnKeyType: UIReturnKeyType = .default
var autocorrectionType: UITextAutocorrectionType = .no
var autocapitalizationType: UITextAutocapitalizationType = .none
var spellCheckingType: UITextSpellCheckingType = .no
var secureTextEntry = false
var textAlignment: NSTextAlignment = .left
var clearButtonMode: UITextField.ViewMode = .whileEditing
var titleTextColor: UIColor = Colors.text
var titleFont: UIFont = .preferredFont(forTextStyle: .body)
var detailTextColor: UIColor = Colors.secondaryText
var detailFont: UIFont = .preferredFont(forTextStyle: .body)
var errorFont: UIFont = .preferredFont(forTextStyle: .caption2)
var errorTextColor: UIColor = UIColor.red
var model: TextFieldFormItem! = nil
var valueDidChange: (String) -> Void = { (value: String) in
SwiftyFormLog("value \(value)")
}
var didEndEditing: (String) -> Void = { (value: String) in
SwiftyFormLog("value \(value)")
}
}
public class TextFieldFormItemCell: UITableViewCell, AssignAppearance {
public let model: TextFieldFormItemCellModel
public let titleLabel = UILabel()
public let textField = CustomTextField()
public let errorLabel = UILabel()
public var state: TextCellState = .noMessage
public init(model: TextFieldFormItemCellModel) {
self.model = model
super.init(style: .default, reuseIdentifier: nil)
self.addGestureRecognizer(tapGestureRecognizer)
selectionStyle = .none
titleLabel.textColor = model.titleTextColor
titleLabel.font = model.titleFont
textField.textColor = model.detailTextColor
textField.font = model.detailFont
errorLabel.font = model.errorFont
errorLabel.textColor = model.errorTextColor
errorLabel.numberOfLines = 0
textField.configure()
textField.delegate = self
textField.addTarget(self, action: #selector(TextFieldFormItemCell.valueDidChange), for: UIControl.Event.editingChanged)
if #available(iOS 11, *) {
contentView.insetsLayoutMarginsFromSafeArea = true
}
contentView.addSubview(titleLabel)
contentView.addSubview(textField)
contentView.addSubview(errorLabel)
titleLabel.text = model.title
textField.placeholder = model.placeholder
textField.autocapitalizationType = model.autocapitalizationType
textField.autocorrectionType = model.autocorrectionType
textField.keyboardType = model.keyboardType
textField.returnKeyType = model.returnKeyType
textField.spellCheckingType = model.spellCheckingType
textField.isSecureTextEntry = model.secureTextEntry
textField.textAlignment = model.textAlignment
textField.clearButtonMode = model.clearButtonMode
if self.model.toolbarMode == .simple {
textField.inputAccessoryView = toolbar
}
updateErrorLabel(model.model.liveValidateValueText())
// titleLabel.backgroundColor = UIColor.blueColor()
// textField.backgroundColor = UIColor.greenColor()
// errorLabel.backgroundColor = UIColor.yellowColor()
clipsToBounds = true
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public lazy var toolbar: SimpleToolbar = {
let instance = SimpleToolbar()
instance.jumpToPrevious = { [weak self] in
self?.gotoPrevious()
}
instance.jumpToNext = { [weak self] in
self?.gotoNext()
}
instance.dismissKeyboard = { [weak self] in
self?.dismissKeyboard()
}
return instance
}()
public func updateToolbarButtons() {
if model.toolbarMode == .simple {
toolbar.updateButtonConfiguration(self)
}
}
public func gotoPrevious() {
SwiftyFormLog("make previous cell first responder")
form_makePreviousCellFirstResponder()
}
public func gotoNext() {
SwiftyFormLog("make next cell first responder")
form_makeNextCellFirstResponder()
}
public func dismissKeyboard() {
SwiftyFormLog("dismiss keyboard")
_ = resignFirstResponder()
}
@objc public func handleTap(_ sender: UITapGestureRecognizer) {
textField.becomeFirstResponder()
}
public lazy var tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TextFieldFormItemCell.handleTap(_:)))
public enum TitleWidthMode {
case auto
case assign(width: CGFloat)
}
public var titleWidthMode: TitleWidthMode = .auto
public func compute() -> TextFieldFormItemCellSizes {
let cellWidth: CGFloat = contentView.bounds.width
var titleLabelFrame = CGRect.zero
var textFieldFrame = CGRect.zero
var errorLabelFrame = CGRect.zero
var cellHeight: CGFloat = 0
let veryTallCell = CGRect(x: 0, y: 0, width: cellWidth, height: CGFloat.greatestFiniteMagnitude)
var layoutMargins = contentView.layoutMargins
layoutMargins.top = 0
layoutMargins.bottom = 0
let area = veryTallCell.inset(by: layoutMargins)
let (topRect, _) = area.divided(atDistance: 44, from: .minYEdge)
do {
let size = titleLabel.sizeThatFits(area.size)
var titleLabelWidth = size.width
switch titleWidthMode {
case .auto:
break
case let .assign(width):
let w = CGFloat(width)
if w > titleLabelWidth {
titleLabelWidth = w
}
}
var (slice, remainder) = topRect.divided(atDistance: titleLabelWidth, from: .minXEdge)
titleLabelFrame = slice
(_, remainder) = remainder.divided(atDistance: 10, from: .minXEdge)
remainder.size.width += 4
textFieldFrame = remainder
cellHeight = ceil(textFieldFrame.height)
}
do {
let size = errorLabel.sizeThatFits(area.size)
// SwiftyFormLog("error label size \(size)")
if size.height > 0.1 {
var r = topRect
r.origin.y = topRect.maxY - 6
let (slice, _) = r.divided(atDistance: size.height, from: .minYEdge)
errorLabelFrame = slice
cellHeight = ceil(errorLabelFrame.maxY + 10)
}
}
return TextFieldFormItemCellSizes(titleLabelFrame: titleLabelFrame, textFieldFrame: textFieldFrame, errorLabelFrame: errorLabelFrame, cellHeight: cellHeight)
}
public override func layoutSubviews() {
super.layoutSubviews()
//SwiftyFormLog("layoutSubviews")
let sizes: TextFieldFormItemCellSizes = compute()
titleLabel.frame = sizes.titleLabelFrame
textField.frame = sizes.textFieldFrame
errorLabel.frame = sizes.errorLabelFrame
}
@objc public func valueDidChange() {
model.valueDidChange(textField.text ?? "")
let result: ValidateResult = model.model.liveValidateValueText()
switch result {
case .valid:
SwiftyFormLog("valid")
case .hardInvalid:
SwiftyFormLog("hard invalid")
case .softInvalid:
SwiftyFormLog("soft invalid")
}
}
public func setValueWithoutSync(_ value: String) {
SwiftyFormLog("set value \(value)")
textField.text = value
_ = validateAndUpdateErrorIfNeeded(value, shouldInstallTimer: false, checkSubmitRule: false)
}
public func updateErrorLabel(_ result: ValidateResult) {
switch result {
case .valid:
errorLabel.text = nil
case .hardInvalid(let message):
errorLabel.text = message
case .softInvalid(let message):
errorLabel.text = message
}
}
public var lastResult: ValidateResult?
public var hideErrorMessageAfterFewSecondsTimer: Timer?
public func invalidateTimer() {
if let timer = hideErrorMessageAfterFewSecondsTimer {
timer.invalidate()
hideErrorMessageAfterFewSecondsTimer = nil
}
}
public func installTimer() {
invalidateTimer()
let timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(TextFieldFormItemCell.timerUpdate), userInfo: nil, repeats: false)
hideErrorMessageAfterFewSecondsTimer = timer
}
// Returns true when valid
// Returns false when invalid
public func validateAndUpdateErrorIfNeeded(_ text: String, shouldInstallTimer: Bool, checkSubmitRule: Bool) -> Bool {
let tableView: UITableView? = form_tableView()
let result: ValidateResult = model.model.validateText(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: checkSubmitRule)
if let lastResult = lastResult {
if lastResult == result {
switch result {
case .valid:
//SwiftyFormLog("same valid")
return true
case .hardInvalid:
//SwiftyFormLog("same hard invalid")
invalidateTimer()
if shouldInstallTimer {
installTimer()
}
return false
case .softInvalid:
//SwiftyFormLog("same soft invalid")
invalidateTimer()
if shouldInstallTimer {
installTimer()
}
return true
}
}
}
lastResult = result
switch result {
case .valid:
//SwiftyFormLog("different valid")
if let tv = tableView {
tv.beginUpdates()
errorLabel.text = nil
setNeedsLayout()
tv.endUpdates()
invalidateTimer()
}
return true
case let .hardInvalid(message):
//SwiftyFormLog("different hard invalid")
if let tv = tableView {
tv.beginUpdates()
errorLabel.text = message
setNeedsLayout()
tv.endUpdates()
invalidateTimer()
if shouldInstallTimer {
installTimer()
}
}
return false
case let .softInvalid(message):
//SwiftyFormLog("different soft invalid")
if let tv = tableView {
tv.beginUpdates()
errorLabel.text = message
setNeedsLayout()
tv.endUpdates()
invalidateTimer()
if shouldInstallTimer {
installTimer()
}
}
return true
}
}
@objc public func timerUpdate() {
invalidateTimer()
//SwiftyFormLog("timer update")
let s = textField.text ?? ""
_ = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: false)
}
public func reloadPersistentValidationState() {
invalidateTimer()
//SwiftyFormLog("reload persistent message")
let s = textField.text ?? ""
_ = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: true)
}
// MARK: UIResponder
public override var canBecomeFirstResponder: Bool {
true
}
public override func becomeFirstResponder() -> Bool {
textField.becomeFirstResponder()
}
public override func resignFirstResponder() -> Bool {
textField.resignFirstResponder()
}
public func assignDefaultColors() {
titleLabel.textColor = model.titleTextColor
}
public func assignTintColors() {
titleLabel.textColor = tintColor
}
}
extension TextFieldFormItemCell: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
updateToolbarButtons()
assignTintColors()
}
public func textFieldDidEndEditing(_ textField: UITextField) {
assignDefaultColors()
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldString: NSString = textField.text as NSString? ?? ""
let s = textFieldString.replacingCharacters(in: range, with:string)
let valid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: false)
return valid
}
// Hide the keyboard when the user taps the return key in this UITextField
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let s = textField.text ?? ""
let isTextValid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: true)
if isTextValid {
textField.resignFirstResponder()
model.didEndEditing(s)
}
return false
}
}
extension TextFieldFormItemCell: CellHeightProvider {
public func form_cellHeight(indexPath: IndexPath, tableView: UITableView) -> CGFloat {
let sizes: TextFieldFormItemCellSizes = compute()
let value = sizes.cellHeight
//SwiftyFormLog("compute height of row: \(value)")
return value
}
}
| mit | e4c99c55e3e8cb41e6c95d1139dac91a | 27.753488 | 159 | 0.730427 | 4.206873 | false | false | false | false |
piglikeYoung/iOS8-day-by-day | 28-document-picker/EdTxt/EdTxt/ViewController.swift | 22 | 2040 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIDocumentMenuDelegate, UIDocumentPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func handleImportMenuPressed(sender: AnyObject) {
let importMenu = UIDocumentMenuViewController(documentTypes: [kUTTypeText as NSString], inMode: .Import)
importMenu.delegate = self
importMenu.addOptionWithTitle("Create New Document", image: nil, order: .First, handler: { println("New Doc Requested") })
presentViewController(importMenu, animated: true, completion: nil)
}
@IBAction func handleImportPickerPressed(sender: AnyObject) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeText as NSString], inMode: .Import)
documentPicker.delegate = self
presentViewController(documentPicker, animated: true, completion: nil)
}
// MARK:- UIDocumentMenuDelegate
func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
presentViewController(documentPicker, animated: true, completion: nil)
}
// MARK:- UIDocumentPickerDelegate
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
// Do something
println(url)
}
}
| apache-2.0 | 92d5a84bb5e2539f832aa0de6b9d1a27 | 36.777778 | 135 | 0.762745 | 5 | false | false | false | false |
carabina/SwiftCSP | SwiftCSP/SwiftCSP/CircuitBoardConstraint.swift | 1 | 3299 | //
// CircuitBoardConstraint.swift
// SwiftCSP
//
// The SwiftCSP License (MIT)
//
// Copyright (c) 2015 David Kopec
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
//A binary constraint that makes sure two Chip variables do not overlap.
class CircuitBoardConstraint<V, D>: BinaryConstraint<CircuitBoard, (Int, Int)> {
override init(variable1: CircuitBoard, variable2: CircuitBoard) {
super.init(variable1: variable1, variable2: variable2)
//println(self.variable1.width)
//println(self.variable2.width)
}
override func isSatisfied(assignment: Dictionary<CircuitBoard, (Int, Int)>) -> Bool {
//if either variable is not in the assignment then it must be consistent
//since they still have their domain
// println(assignment)
// println(variable1.width)
// println(variable2.width)
// println(variable1.height)
// println(variable2.height)
if assignment[variable1] == nil || assignment[variable2] == nil {
return true
}
//check that var1 does not overlap var2
let rect1 = CGRect(x: assignment[variable1]!.0, y: assignment[variable1]!.1, width: variable1.width, height: variable1.height)
let rect2 = CGRect(x: assignment[variable2]!.0, y: assignment[variable2]!.1, width: variable2.width, height: variable2.height)
return !CGRectIntersectsRect(rect1, rect2)
//got the overlapping rectangle formula from
//http://codesam.blogspot.com/2011/02/check-if-two-rectangles-intersect.html
/*let x1: Int = assignment[variable1]!.0
let y1: Int = assignment[variable1]!.1
let x2: Int = variable1.width - 1 + x1
let y2: Int = y1 - Int(variable1.height + 1
let x3: Int = assignment[variable2]!.0
let y3: Int = Int(assignment[variable2]!.1)
let x4: Int = Int(variable2.width) - 1 + x3
let y4: Int = y3 - Int(variable2.height) + 1
//print x1, y1, self.var1.name
//print x2, y2, self.var1.name
//print x3, y3, self.var2.name
//print x4, y4, self.var2.name
//print (x1 > x4 or x2 < x3 or y1 < y4 or y2 > y3)
return (x1 > x4 || x2 < x3 || y1 < y4 || y2 > y3)*/
}
} | mit | f7d47d7321390a345e10290df5371be5 | 44.833333 | 134 | 0.672628 | 3.809469 | false | false | false | false |
svdo/swift-SelfSignedCert | SelfSignedCert/SecIdentity+SelfSigned.swift | 1 | 5161 | // Copyright © 2016 Stefan van den Oord. All rights reserved.
import Foundation
import Security
import IDZSwiftCommonCrypto
import SecurityExtensions
extension SecIdentity
{
/**
* Create an identity using a self-signed certificate. This can fail in many ways, in which case it will return `nil`.
* Since potential failures are non-recoverable, no details are provided in that case.
*
* - parameter ofSize: size of the keys, in bits; default is 3072
* - parameter subjectCommonName: the common name of the subject of the self-signed certificate that is created
* - parameter subjectEmailAddress: the email address of the subject of the self-signed certificate that is created
* - returns: The created identity, or `nil` when there was an error.
*/
public static func create(
ofSize bits:UInt = 3072,
subjectCommonName name:String,
subjectEmailAddress email:String,
validFrom:Date? = nil,
validTo:Date? = nil
) -> SecIdentity? {
let privKey: SecKey
let pubKey: SecKey
do {
(privKey,pubKey) = try SecKey.generateKeyPair(ofSize: bits)
}
catch {
return nil
}
let certRequest = CertificateRequest(
forPublicKey:pubKey,
subjectCommonName: name,
subjectEmailAddress: email,
keyUsage: [.DigitalSignature, .DataEncipherment],
validFrom: validFrom,
validTo: validTo
)
guard let signedBytes = certRequest.selfSign(withPrivateKey:privKey),
let signedCert = SecCertificateCreateWithData(nil, Data(signedBytes) as CFData) else {
return nil
}
let err = signedCert.storeInKeychain()
guard err == errSecSuccess else {
return nil
}
return findIdentity(forPrivateKey:privKey, publicKey:pubKey)
}
/**
* Helper method that tries to load an identity from the keychain.
*
* - parameter forPrivateKey: the private key for which the identity should be searched
* - parameter publicKey: the public key for which the identity should be searched; should match the private key
* - returns: The identity if found, or `nil`.
*/
private static func findIdentity(forPrivateKey privKey:SecKey, publicKey pubKey:SecKey) -> SecIdentity? {
guard let identity = SecIdentity.find(withPublicKey:pubKey) else {
return nil
}
// Since the way identities are stored in the keychain is sparsely documented at best,
// double-check that this identity is the one we're looking for.
guard let priv = identity.privateKey,
let retrievedKeyData = priv.keyData,
let originalKeyData = privKey.keyData, retrievedKeyData == originalKeyData else {
return nil
}
return identity
}
/**
* Finds the identity in the keychain based on the given public key.
* The identity that is returned is the one that has the public key's digest
* as label.
*
* - parameter withPublicKey: the public key that should be used to find the identity, based on it's digest
* - returns: The identity if found, or `nil`.
*/
public static func find(withPublicKey pubKey:SecKey) -> SecIdentity? {
guard let identities = findAll(withPublicKey: pubKey), identities.count == 1 else {
return nil
}
return identities[0]
}
/**
* Finds all identities in the keychain based on the given public key.
* The identities that are returned are the ones that have the public key's digest
* as label. Because of the keychain query filters, and on current iOS versions,
* this should return 0 or 1 identity, not more...
*
* - parameter withPublicKey: the public key that should be used to find the identity, based on it's digest
* - returns: an array of identities if found, or `nil`
*/
static func findAll(withPublicKey pubKey:SecKey) -> [SecIdentity]? {
guard let keyData = pubKey.keyData else {
return nil
}
let sha1 = Digest(algorithm: .sha1)
_ = sha1.update(buffer: keyData, byteCount: keyData.count)
let digest = sha1.final()
let digestData = Data(digest)
var out: AnyObject?
let query : [NSString:AnyObject] = [kSecClass as NSString: kSecClassIdentity as NSString,
kSecAttrKeyClass as NSString: kSecAttrKeyClassPrivate as NSString,
kSecMatchLimit as NSString : kSecMatchLimitAll as NSString,
kSecReturnRef as NSString : NSNumber(value: true),
kSecAttrApplicationLabel as NSString : digestData as NSData ]
let err = SecItemCopyMatching(query as CFDictionary, &out)
guard err == errSecSuccess else {
return nil
}
let identities = out! as! [SecIdentity]
return identities
}
}
| mit | a9e01123902c6fdced145716b5866e83 | 39.629921 | 122 | 0.626938 | 5.00485 | false | false | false | false |
antitypical/TesseractCore | TesseractCore/Endpoint.swift | 1 | 1038 | // Copyright (c) 2015 Rob Rix. All rights reserved.
public protocol EndpointType {
typealias Nodes: CollectionType
var nodeIndex: Nodes.Index { get }
var endpointIndex: Int { get }
}
public struct Source<C: CollectionType>: EndpointType, Printable {
public init(nodeIndex: C.Index, outputIndex: Int = 0) {
self.nodeIndex = nodeIndex
self.outputIndex = outputIndex
}
public typealias Nodes = C
public let nodeIndex: C.Index
public let outputIndex: Int
public var endpointIndex: Int { return outputIndex }
public var description: String {
return "Source(\(nodeIndex), \(outputIndex))"
}
}
public struct Destination<C: CollectionType>: EndpointType, Printable {
public init(nodeIndex: C.Index, inputIndex: Int = 0) {
self.nodeIndex = nodeIndex
self.inputIndex = inputIndex
}
public typealias Nodes = C
public let nodeIndex: C.Index
public let inputIndex: Int
public var endpointIndex: Int { return inputIndex }
public var description: String {
return "Destination(\(nodeIndex), \(inputIndex))"
}
}
| mit | 128f63f8c00309dfb665194e6c2142ef | 23.139535 | 71 | 0.734104 | 3.604167 | false | false | false | false |
Johnykutty/JSONModeller | JSONModeller/Model/Constants.swift | 1 | 750 | //
// Constants.swift
// JSONModeller
//
// Created by Johnykutty on 28/05/15.
// Copyright (c) 2015 Johnykutty. All rights reserved.
//
import Foundation
let kClassNamePlaceholder = "[#ClassName#]"
let kAuthorNamePlaceholder = "[#AuthorName#]"
let kCompanyNamePlaceholder = "[#CompanyName#]"
let kCreatedDatePlaceholder = "[#CreatedDate#]"
let kCopyrightYearPlaceholder = "[#CopyrightYear#]"
let kImportsPlaceholder = "[#Imports#]"
let kDescriptionPlaceholder = "[#DescriptionMethodBody#]"
let kForwardDeclarationsPlaceholder = "[#ForwardDeclarations#]"
let kPropertyDeclarationsPlaceholder = "[#PropertyDeclarations#]"
let kKeymapperPlaceholder = "[#KeyMapper#]" | mit | 9a21d28f65ca44eeca25d1d059a1e048 | 36.55 | 66 | 0.68 | 4.054054 | false | false | false | false |
JGiola/swift-package-manager | Sources/PackageModel/Manifest.swift | 1 | 13775 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import Utility
/// The supported manifest versions.
public enum ManifestVersion: String, Codable, CustomStringConvertible {
case v4
case v4_2
case v5
/// The Swift language version to use when parsing the manifest file.
public var swiftLanguageVersion: SwiftLanguageVersion {
// FIXME: This is not very scalable. We need to store the tools
// version in the manifest and then use that to compute the right
// Swift version instead of relying on the manifest version. The
// manifest version is just the version that was used to load the
// manifest and shouldn't contribute to what Swift version is
// chosen. For e.g., we might have a new manifest version 4.3, but
// the language version should still be 4.2.
switch self {
case .v4: return .v4
case .v4_2: return .v4_2
case .v5: return .v5
}
}
public var description: String {
switch self {
case .v4: return "4"
case .v4_2: return "4.2"
case .v5: return "5"
}
}
/// Subpath to the the runtime for this manifest version.
public var runtimeSubpath: RelativePath {
switch self {
case .v4:
return RelativePath("4")
case .v4_2, .v5:
// PackageDescription 4.2 and 5 are source compatible so they're contained in the same dylib.
return RelativePath("4_2")
}
}
}
/// This contains the declarative specification loaded from package manifest
/// files, and the tools for working with the manifest.
public final class Manifest: ObjectIdentifierProtocol, CustomStringConvertible, Codable {
/// The standard filename for the manifest.
public static let filename = basename + ".swift"
/// The standard basename for the manifest.
public static let basename = "Package"
// FIXME: This doesn't belong here, we want the Manifest to be purely tied
// to the repository state, it shouldn't matter where it is.
//
/// The path of the manifest file.
public let path: AbsolutePath
// FIXME: This doesn't belong here, we want the Manifest to be purely tied
// to the repository state, it shouldn't matter where it is.
//
/// The repository URL the manifest was loaded from.
public let url: String
/// The version this package was loaded from, if known.
public let version: Version?
/// The version of manifest.
public let manifestVersion: ManifestVersion
/// The name of the package.
public let name: String
/// The declared platforms in the manifest.
public let platforms: [PlatformDescription]
/// The declared package dependencies.
public let dependencies: [PackageDependencyDescription]
/// The targets declared in the manifest.
public let targets: [TargetDescription]
/// The products declared in the manifest.
public let products: [ProductDescription]
/// The C language standard flag.
public let cLanguageStandard: String?
/// The C++ language standard flag.
public let cxxLanguageStandard: String?
/// The supported Swift language versions of the package.
public let swiftLanguageVersions: [SwiftLanguageVersion]?
/// The pkg-config name of a system package.
public let pkgConfig: String?
/// The system package providers of a system package.
public let providers: [SystemPackageProviderDescription]?
public init(
name: String,
platforms: [PlatformDescription],
path: AbsolutePath,
url: String,
version: Utility.Version? = nil,
manifestVersion: ManifestVersion,
pkgConfig: String? = nil,
providers: [SystemPackageProviderDescription]? = nil,
cLanguageStandard: String? = nil,
cxxLanguageStandard: String? = nil,
swiftLanguageVersions: [SwiftLanguageVersion]? = nil,
dependencies: [PackageDependencyDescription] = [],
products: [ProductDescription] = [],
targets: [TargetDescription] = []
) {
self.name = name
self.platforms = platforms
self.path = path
self.url = url
self.version = version
self.manifestVersion = manifestVersion
self.pkgConfig = pkgConfig
self.providers = providers
self.cLanguageStandard = cLanguageStandard
self.cxxLanguageStandard = cxxLanguageStandard
self.swiftLanguageVersions = swiftLanguageVersions
self.dependencies = dependencies
self.products = products
self.targets = targets
}
public var description: String {
return "<Manifest: \(name)>"
}
/// Coding user info key for dump-package command.
///
/// Presence of this key will hide some keys when encoding the Manifest object.
public static let dumpPackageKey: CodingUserInfoKey = CodingUserInfoKey(rawValue: "dumpPackage")!
}
extension Manifest {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
// Hide the keys that users shouldn't see when
// we're encoding for the dump-package command.
if encoder.userInfo[Manifest.dumpPackageKey] == nil {
try container.encode(path, forKey: .path)
try container.encode(url, forKey: .url)
try container.encode(version, forKey: .version)
}
try container.encode(manifestVersion, forKey: .manifestVersion)
try container.encode(pkgConfig, forKey: .pkgConfig)
try container.encode(providers, forKey: .providers)
try container.encode(cLanguageStandard, forKey: .cLanguageStandard)
try container.encode(cxxLanguageStandard, forKey: .cxxLanguageStandard)
try container.encode(swiftLanguageVersions, forKey: .swiftLanguageVersions)
try container.encode(dependencies, forKey: .dependencies)
try container.encode(products, forKey: .products)
try container.encode(targets, forKey: .targets)
}
}
/// The description of an individual target.
public struct TargetDescription: Equatable, Codable {
/// The target type.
public enum TargetType: String, Equatable, Codable {
case regular
case test
case system
}
/// Represents a target's dependency on another entity.
public enum Dependency: Equatable, ExpressibleByStringLiteral {
case target(name: String)
case product(name: String, package: String?)
case byName(name: String)
public init(stringLiteral value: String) {
self = .byName(name: value)
}
public static func product(name: String) -> Dependency {
return .product(name: name, package: nil)
}
}
/// The name of the target.
public let name: String
/// The custom path of the target.
public let path: String?
/// The custom sources of the target.
public let sources: [String]?
/// The exclude patterns.
public let exclude: [String]
// FIXME: Kill this.
//
/// Returns true if the target type is test.
public var isTest: Bool {
return type == .test
}
/// The declared target dependencies.
public let dependencies: [Dependency]
/// The custom public headers path.
public let publicHeadersPath: String?
/// The type of target.
public let type: TargetType
/// The pkg-config name of a system library target.
public let pkgConfig: String?
/// The providers of a system library target.
public let providers: [SystemPackageProviderDescription]?
/// The target-specific build settings declared in this target.
public let settings: [TargetBuildSettingDescription.Setting]
public init(
name: String,
dependencies: [Dependency] = [],
path: String? = nil,
exclude: [String] = [],
sources: [String]? = nil,
publicHeadersPath: String? = nil,
type: TargetType = .regular,
pkgConfig: String? = nil,
providers: [SystemPackageProviderDescription]? = nil,
settings: [TargetBuildSettingDescription.Setting] = []
) {
switch type {
case .regular, .test:
precondition(pkgConfig == nil && providers == nil)
case .system: break
}
self.name = name
self.dependencies = dependencies
self.path = path
self.publicHeadersPath = publicHeadersPath
self.sources = sources
self.exclude = exclude
self.type = type
self.pkgConfig = pkgConfig
self.providers = providers
self.settings = settings
}
}
/// The product description
public struct ProductDescription: Equatable, Codable {
/// The name of the product.
public let name: String
/// The targets in the product.
public let targets: [String]
/// The type of product.
public let type: ProductType
public init(
name: String,
type: ProductType,
targets: [String]
) {
precondition(type != .test, "Declaring test products isn't supported: \(name):\(targets)")
self.name = name
self.type = type
self.targets = targets
}
}
/// Represents system package providers.
public enum SystemPackageProviderDescription: Equatable {
case brew([String])
case apt([String])
}
/// Represents a package dependency.
public struct PackageDependencyDescription: Equatable, Codable {
/// The dependency requirement.
public enum Requirement: Equatable, Hashable, CustomStringConvertible {
case exact(Version)
case range(Range<Version>)
case revision(String)
case branch(String)
case localPackage
public static func upToNextMajor(from version: Utility.Version) -> Requirement {
return .range(version..<Version(version.major + 1, 0, 0))
}
public static func upToNextMinor(from version: Utility.Version) -> Requirement {
return .range(version..<Version(version.major, version.minor + 1, 0))
}
public var description: String {
switch self {
case .exact(let version):
return version.description
case .range(let range):
return range.description
case .revision(let revision):
return "revision[\(revision)]"
case .branch(let branch):
return "branch[\(branch)]"
case .localPackage:
return "local"
}
}
}
/// The url of the dependency.
public let url: String
/// The dependency requirement.
public let requirement: Requirement
/// Create a dependency.
public init(url: String, requirement: Requirement) {
self.url = url
self.requirement = requirement
}
}
public struct PlatformDescription: Codable, Equatable {
public let platformName: String
public let version: String
public init(name: String, version: String) {
self.platformName = name
self.version = version
}
}
/// A namespace for target-specific build settings.
public enum TargetBuildSettingDescription {
/// Represents a build settings condition.
public struct Condition: Codable, Equatable {
public let platformNames: [String]
public let config: String?
public init(platformNames: [String] = [], config: String? = nil) {
assert(!(platformNames.isEmpty && config == nil))
self.platformNames = platformNames
self.config = config
}
}
/// The tool for which a build setting is declared.
public enum Tool: String, Codable, Equatable, CaseIterable {
case c
case cxx
case swift
case linker
}
/// The name of the build setting.
public enum SettingName: String, Codable, Equatable {
case headerSearchPath
case define
case linkedLibrary
case linkedFramework
case unsafeFlags
}
/// An individual build setting.
public struct Setting: Codable, Equatable {
/// The tool associated with this setting.
public let tool: Tool
/// The name of the setting.
public let name: SettingName
/// The condition at which the setting should be applied.
public let condition: Condition?
/// The value of the setting.
///
/// This is kind of like an "untyped" value since the length
/// of the array will depend on the setting type.
public let value: [String]
public init(
tool: Tool,
name: SettingName,
value: [String],
condition: Condition? = nil
) {
switch name {
case .headerSearchPath: fallthrough
case .define: fallthrough
case .linkedLibrary: fallthrough
case .linkedFramework:
assert(value.count == 1, "\(tool) \(name) \(value)")
break
case .unsafeFlags:
assert(value.count >= 1, "\(tool) \(name) \(value)")
break
}
self.tool = tool
self.name = name
self.value = value
self.condition = condition
}
}
}
| apache-2.0 | 4fb0703f256743ed551aba2c6131dd11 | 30.449772 | 105 | 0.633321 | 4.857193 | false | false | false | false |
nfeld9807/game_jam | GameJam/CannonNode.swift | 1 | 5859 | //
// CannonNode.swift
// GameJam
//
// Created by Nathan Feldsien on 1/30/16.
// Copyright © 2016 CodeDezyn. All rights reserved.
//
import SpriteKit
protocol CannonNodeDelegate {
func cannonStartGame()
}
class CannonNode: SKSpriteNode {
enum CannonType: Int {
case BIRTH = 0
case PARTY
case MARRIAGE
case TRAVEL
case FOOD
case RETIREMENT
}
var ammoNode:SKNode? = nil
var used:Bool = false
var hasBegunGame = true
var cannonNodeDelegate: CannonNodeDelegate?
init(withAmmo: Bool, hasBegunGame: Bool = true) {
let size = CGSize(width: 100, height: 100)
self.hasBegunGame = hasBegunGame
var cannonTexture = SKTexture(imageNamed: "birthcannon")
switch (Int(arc4random_uniform(6))) {
case CannonType.BIRTH.rawValue:
cannonTexture = SKTexture(imageNamed: "birthcannon")
break
case CannonType.PARTY.rawValue:
cannonTexture = SKTexture(imageNamed: "partycannon")
break
case CannonType.MARRIAGE.rawValue:
cannonTexture = SKTexture(imageNamed: "weddingcannon")
break
case CannonType.TRAVEL.rawValue:
cannonTexture = SKTexture(imageNamed: "travelcannon")
break
case CannonType.FOOD.rawValue:
cannonTexture = SKTexture(imageNamed: "turkeycannon")
break
case CannonType.RETIREMENT.rawValue:
cannonTexture = SKTexture(imageNamed: "retirementcannon")
break
default:
break
}
super.init(texture: nil, color: .clearColor(), size: size)
physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 50, height: 100))
physicsBody?.mass = 8
physicsBody?.affectedByGravity = false
physicsBody?.dynamic = true
physicsBody?.collisionBitMask = CategoryType.Cannon.rawValue
physicsBody?.categoryBitMask = CategoryType.Cannon.rawValue
physicsBody?.contactTestBitMask = CategoryType.Projectile.rawValue
let cannonNode = SKSpriteNode(texture: cannonTexture, color: .clearColor(), size: size)
cannonNode.zPosition = 10
addChild(cannonNode)
userInteractionEnabled = true
if (withAmmo) {
let ammoNode = PlayerNode()
loadAmmo(ammoNode)
}
rotateAction()
moveToBottomAction()
}
func rotateAction() {
let rotateLeftInitialAction = SKAction.rotateToAngle(CGFloat(M_PI_4), duration: 0.5)
runAction(rotateLeftInitialAction) {
let rotateLeftAction = SKAction.rotateToAngle(CGFloat(M_PI_4), duration: 1)
let rotateRightAction = SKAction.rotateToAngle(-CGFloat(M_PI_4), duration: 1)
let rotateArray = SKAction.sequence([rotateRightAction, rotateLeftAction])
let repeatAction = SKAction.repeatActionForever(rotateArray)
self.runAction(repeatAction)
}
}
func moveToBottomAction() {
let moveToBottomAction = SKAction.moveToY(-80, duration: 8)
runAction(moveToBottomAction) {
self.removeFromParent()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (hasBegunGame) {
shootNode()
}
else {
hasBegunGame = true
physicsBody?.dynamic = true
moveToBottomAction()
self.cannonNodeDelegate?.cannonStartGame()
}
}
func shootNode() {
guard
let ammoNode = self.ammoNode as? PlayerNode,
let parent = self.parent
else {
return
}
used = true
let parentPosition = convertPoint(ammoNode.position, toNode: parent)
ammoNode.removeFromParent()
ammoNode.position = parentPosition
self.parent?.addChild(ammoNode)
ammoNode.shootPlayer()
ammoNode.physicsBody = SKPhysicsBody(rectangleOfSize: ammoNode.size)
ammoNode.physicsBody?.dynamic = true
ammoNode.physicsBody?.mass = ammoNode.curPlayer.mass.rawValue
ammoNode.physicsBody?.categoryBitMask = CategoryType.Projectile.rawValue
ammoNode.physicsBody?.collisionBitMask = CategoryType.Projectile.rawValue
ammoNode.physicsBody?.contactTestBitMask = CategoryType.Cannon.rawValue
let dx = CGFloat(tanf(Float(self.zRotation))) * -5000
ammoNode.physicsBody?.applyImpulse(CGVector(dx: dx, dy: 10000))
let rotateAction = SKAction.rotateByAngle(1, duration: 0.25)
let repeatRotateAction = SKAction.repeatActionForever(rotateAction)
ammoNode.runAction(repeatRotateAction)
userInteractionEnabled = false
self.ammoNode = nil
}
func loadAmmo(ammoNode:PlayerNode) {
self.ammoNode = ammoNode
guard let ammoNode = self.ammoNode
else {
return
}
playCannonLoad()
ammoNode.hidden = true
ammoNode.removeAllActions()
ammoNode.physicsBody = nil
addChild(ammoNode)
ammoNode.position = CGPoint(x: 0, y: 30)
ammoNode.zPosition = 1
ammoNode.zRotation = 0
ammoNode.hidden = false
}
}
| mit | 106260a756ff5c95b98b2a6d3cb7801e | 29.670157 | 95 | 0.582281 | 4.935131 | false | false | false | false |
spacedrabbit/100-days | One00Days/One00Days/Day36ViewController.swift | 1 | 989 | //
// Day36ViewController.swift
// One00Days
//
// Created by Louis Tur on 3/27/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
// https://leetcode.com/problems/add-digits/
// Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
//
// For example:
// Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
//
// Follow up:
// Could you do it without any loop/recursion in O(1) runtime?
import UIKit
class Day36ViewController: UIViewController {
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.
}
func splitNumberIntoComponents(_ num: Int) {
let nsnum: NSNumber = NSNumber(value: num as Int)
let stringNum: String = nsnum.stringValue
}
}
| mit | 1bd3ae89550caf87dec5020321bc9c13 | 23.7 | 103 | 0.678138 | 3.905138 | false | false | false | false |
djtone/VIPER | VIPER-SWIFT/Classes/Modules/Add/User Interface/View/AddViewController.swift | 2 | 2080 | //
// AddViewController.swift
// VIPER TODO
//
// Created by Conrad Stoll on 6/4/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
import UIKit
class AddViewController: UIViewController, UITextFieldDelegate, AddViewInterface {
var eventHandler : AddModuleInterface?
@IBOutlet var nameTextField : UITextField!
@IBOutlet var datePicker : UIDatePicker!
var minimumDate : NSDate = NSDate()
var transitioningBackgroundView : UIView = UIView()
@IBAction func save(sender: AnyObject) {
eventHandler?.saveAddActionWithName(nameTextField!.text, dueDate: datePicker!.date)
}
@IBAction func cancel(sender: AnyObject) {
nameTextField.resignFirstResponder()
eventHandler?.cancelAddAction()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var gestureRecognizer = UITapGestureRecognizer()
gestureRecognizer.addTarget(self, action: Selector("dismiss"))
transitioningBackgroundView.userInteractionEnabled = true
nameTextField.becomeFirstResponder()
if let realDatePicker = datePicker {
realDatePicker.minimumDate = minimumDate
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
nameTextField.resignFirstResponder()
}
func dismiss() {
eventHandler?.cancelAddAction()
}
func setEntryName(name: String) {
nameTextField.text = name
}
func setEntryDueDate(date: NSDate) {
if let realDatePicker = datePicker {
realDatePicker.minimumDate = date
}
}
func setMinimumDueDate(date: NSDate) {
minimumDate = date
if let realDatePicker = datePicker {
realDatePicker.minimumDate = date
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
} | mit | beaba6ef92f3b7272305d0cda73cc251 | 25.679487 | 91 | 0.64375 | 5.636856 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/Views/MarkdownTextView+Recognizers.swift | 1 | 2509 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
extension MarkdownTextView {
func setupGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapTextView(_:)))
tapRecognizer.delegate = self
addGestureRecognizer(tapRecognizer)
}
@objc func didTapTextView(_ recognizer: UITapGestureRecognizer) {
var location = recognizer.location(in: self)
location.x -= textContainerInset.left
location.y -= textContainerInset.top
let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
selectTextAttachmentIfNeeded(at: characterIndex)
}
func selectTextAttachmentIfNeeded(at index: Int) {
guard attributedText.wholeRange.contains(index) else { return }
let attributes = attributedText.attributes(at: index, effectiveRange: nil)
guard attributes[NSAttributedString.Key.attachment] as? MentionTextAttachment != nil else { return }
guard let start = position(from: beginningOfDocument, offset: index) else { return }
guard let end = position(from: start, offset: 1) else { return }
selectedTextRange = textRange(from: start, to: end)
}
}
extension MarkdownTextView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// prevent recognizing other UIPanGestureRecognizers at the same time, e.g. SplitViewController's panGestureRecognizers will dismiss the keyboard and this MarkdownTextView moves down immediately
if otherGestureRecognizer is UIPanGestureRecognizer {
return false
}
return true
}
}
| gpl-3.0 | 7a852eebedd1891a50f4a35499d061f9 | 40.131148 | 202 | 0.735751 | 5.151951 | false | false | false | false |
orucanil/StringFormatter | StringFormatterDemo/StringFormatter/ViewController.swift | 1 | 1572 | //
// ViewController.swift
// StringFormatter
//
// Created by Anil ORUC on 21/07/2017.
// Copyright © 2017 Anil ORUC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textfieldPhoneNumber: UITextField!
@IBOutlet weak var textfieldCreditCard: UITextField!
@IBOutlet weak var textfieldSerialNumber: UITextField!
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.
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String
if textfieldPhoneNumber == textField {
textField.text = lastText.format("(NNN) NNN NN NN", oldString: text)
return false
} else if textfieldCreditCard == textField {
textField.text = lastText.format("nnnn nnnn nnnn nnnn", oldString: text)
return false
} else if textfieldSerialNumber == textField {
textField.text = lastText.format("XX NNNN", oldString: text)
return false
}
return true
}
}
| mit | d6ce5fea7821e62fcd955bda40652a8f | 29.803922 | 129 | 0.65436 | 5.100649 | false | false | false | false |
Noobish1/KeyedAPIParameters | KeyedAPIParametersTests/Protocols/APIParametersSpec.swift | 1 | 1900 | import Quick
import Nimble
import Fakery
@testable import KeyedAPIParameters
fileprivate struct ParamThing {
fileprivate let property: String
}
extension ParamThing: APIParameters {
fileprivate func toParamDictionary() -> [String : APIParamConvertible] {
return ["stringProperty" : property]
}
}
internal final class APIParametersSpec: QuickSpec {
internal override func spec() {
describe("APIParameters") {
let faker = Faker()
describe("it's toDictionary") {
var actual: [String : String]!
var expected: [String : String]!
beforeEach {
let property = faker.lorem.characters()
let thing = ParamThing(property: property)
actual = thing.toDictionary(forHTTPMethod: .get) as? [String : String]
expected = ["stringProperty" : property]
}
it("should take the result of the toParamDictionary function and turn the values of the dictionary into their valueForHTTPMethod") {
expect(actual) == expected
}
}
describe("it's valueForHTTPMethod") {
var actual: [String : String]!
var expected: [String : String]!
beforeEach {
let property = faker.lorem.characters()
let thing = ParamThing(property: property)
actual = thing.value(forHTTPMethod: .get) as? [String : String]
expected = ["stringProperty" : property]
}
it("should return the same result as the toDictionary function") {
expect(actual) == expected
}
}
}
}
}
| mit | b163106838b9fe62cb6e2efdee0926be | 34.185185 | 148 | 0.521579 | 5.792683 | false | false | false | false |
edwardvalentini/Q | Pod/Classes/QOperation.swift | 1 | 6488 | //
// QOperation.swift
// Pods
//
// Created by Edward Valentini on 1/28/16.
//
import UIKit
import CocoaLumberjack
open class QOperation: Operation {
open let queue: Q
open var operationID: String
open var operationName: String
open var retries: Int
open var retryCount: Int = 0
open let created: Date
open var started: Date?
open var userInfo: AnyObject?
open var retryDelay: Int
var error: NSError?
open var operationBlock: QOperationBlock?
var _executing: Bool = false
var _finished: Bool = false
open override var name: String? {get {return operationID } set { } }
open override var isExecuting: Bool {
get { return _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
open override var isFinished: Bool {
get { return _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
public init(queue: Q, operationID: String? = nil, operationName: String, userInfo: AnyObject? = nil,
created: Date = Date(), started: Date? = nil ,
retries: Int = 0, retryDelay: Int = 0, operationBlock: QOperationBlock? = nil) {
self.queue = queue
self.operationID = operationID ?? UUID().uuidString
self.operationName = operationName
self.retries = retries
self.created = created
self.userInfo = userInfo
self.retryDelay = retryDelay
self.operationBlock = operationBlock
self.started = started
super.init()
}
public convenience init(queue: Q, name: String, userInfo: AnyObject? = nil, retries: Int = 0, retryDelay: Int = 0, operationBlock: QOperationBlock? = nil) {
self.init(queue: queue, operationName: name, userInfo:userInfo, retries:retries, retryDelay: retryDelay, operationBlock: operationBlock)
}
public init?(dictionary: QJSONDictionary, queue: Q) {
if let operationID = dictionary["operationID"] as? String,
let operationName = dictionary["operationName"] as? String,
let data: AnyObject? = dictionary["userInfo"] as AnyObject??,
let createdStr = dictionary["created"] as? String,
let startedStr: String? = dictionary["started"] as? String ?? nil,
let retries = dictionary["retries"] as? Int? ?? 0,
let retryDelay = dictionary["retryDelay"] as? Int? ?? 0
{
let created = Date(dateString: createdStr) ?? Date()
let started = (startedStr != nil) ? Date(dateString: startedStr!) : nil
self.queue = queue
self.operationID = operationID ?? UUID().uuidString
self.operationName = operationName
self.retries = retries
self.created = created
self.userInfo = data
self.retryDelay = retryDelay
self.started = started
super.init()
} else {
//self.init(queue: queue, operationID: "", operationName: "")
self.queue = queue
self.operationName = ""
self.operationID = ""
self.retries = 0
self.created = Date()
self.userInfo = nil
self.retryDelay = 0
self.started = nil
super.init()
return nil
}
}
public convenience init?(json: String, queue: Q) {
do {
if let dict = try QJSON.fromJSON(json) as? [String: AnyObject] {
self.init(dictionary: dict, queue: queue)
} else {
return nil
}
} catch {
return nil
}
}
open func completeOperation() {
self.completeOperation(nil)
}
open func failedRetries() -> Bool {
return retryCount >= min(queue.maxRetries,retries)
}
open func completeOperation(_ error: NSError?) {
if (!isExecuting) {
isFinished = true
return
}
if let error = error {
self.error = error
self.retryCount += 1
if failedRetries() {
cancel()
isExecuting = false
isFinished = true
return
}
DDLogVerbose("INSIDE THE QOperation: Operation \(operationName) failed and we are on retry number \(retryCount) of \(min(queue.maxRetries,retries)) times with \(retryDelay) seconds between retries...")
let delayTime = DispatchTime.now() + Double(Int64(Double(retryDelay) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.main()
}
} else {
isExecuting = false
isFinished = true
}
}
// MARK: - overide method
override open func main() {
if isCancelled && !isFinished { isFinished = true }
if isFinished { return }
super.main()
if let block = self.operationBlock {
block(self)
}
}
open override func start() {
super.start()
isExecuting = true
}
open override func cancel() {
super.cancel()
isFinished = true
}
// MARK: - JSON Helpers
open func toJSONString() -> String? {
let dict = toDictionary()
let nsdict = NSMutableDictionary(capacity: dict.count)
for (key, value) in dict {
nsdict[key] = value ?? NSNull()
}
do {
let json = try QJSON.toJSON(nsdict)
return json
} catch {
return nil
}
}
open func toDictionary() -> [AnyHashable: Any] {
var dict : [AnyHashable: Any] = [:]
dict["operationID"] = self.operationID
dict["operationName"] = self.operationName
dict["created"] = self.created.toISOString()
dict["started"] = self.started!.toISOString()
dict["retries"] = self.retries
dict["userInfo"] = self.userInfo
dict["retryDelay"] = self.retryDelay
return dict
}
}
| mit | 532325e8f9cb2fa570b6968694816859 | 29.895238 | 213 | 0.546239 | 4.87453 | false | false | false | false |
aleph7/PlotKit | PlotKitDemo/SinCosViewController.swift | 1 | 1928 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of PlotKit. The full PlotKit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Cocoa
import PlotKit
class SinCosViewController: NSViewController {
let π = M_PI
let sampleCount = 1024
let font = NSFont(name: "Optima", size: 16)!
@IBOutlet weak var plotView: PlotView!
override func viewDidLoad() {
super.viewDidLoad()
createAxes()
createSinePlot()
createCosinePlot()
}
func createAxes() {
let ticks = [
TickMark(π/2, label: "π/2"),
TickMark(π, label: "π"),
TickMark(3*π/2, label: "3π/2"),
TickMark(2*π, label: "2π"),
]
var xaxis = Axis(orientation: .horizontal, ticks: .list(ticks))
xaxis.position = .value(0)
xaxis.labelAttributes = [NSFontAttributeName: font]
plotView.addAxis(xaxis)
var yaxis = Axis(orientation: .vertical, ticks: .distance(0.5))
yaxis.labelAttributes = [NSFontAttributeName: font]
yaxis.position = .value(0)
plotView.addAxis(yaxis)
}
func createSinePlot() {
let t = (0..<sampleCount).map({ 2*π * Double($0) / Double(sampleCount - 1) })
let y = t.map({ sin($0) })
let pointSet = PointSet(points: (0..<sampleCount).map{ Point(x: t[$0], y: y[$0]) })
plotView.addPointSet(pointSet, title: "sin")
}
func createCosinePlot() {
let t = (0..<sampleCount).map({ 2*π * Double($0) / Double(sampleCount - 1) })
let y = t.map({ cos($0) })
let pointSet = PointSet(points: (0..<sampleCount).map{ Point(x: t[$0], y: y[$0]) })
pointSet.lineColor = NSColor.blue
plotView.addPointSet(pointSet, title: "cos")
}
}
| mit | 0082bd6f79d44af6000fef1c0b93cde5 | 32.034483 | 91 | 0.600209 | 3.677543 | false | false | false | false |
gottesmm/swift | test/SILGen/reabstract_lvalue.swift | 3 | 2599 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct MyMetatypeIsThin {}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue19consumeGenericInOut{{.*}} : $@convention(thin) <T> (@inout T) -> ()
func consumeGenericInOut<T>(_ x: inout T) {}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue9transformFSiSd : $@convention(thin) (Int) -> Double
func transform(_ i: Int) -> Double {
return Double(i)
}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue23reabstractFunctionInOutFT_T_ : $@convention(thin) () -> ()
func reabstractFunctionInOut() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned (Int) -> Double }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[ARG:%.*]] = function_ref @_TF17reabstract_lvalue9transformFSiSd
// CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
// CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]]
// CHECK: [[FUNC:%.*]] = function_ref @_TF17reabstract_lvalue19consumeGenericInOut
// CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_owned (@in Int) -> @out Double
// CHECK: [[THICK_ARG:%.*]] = load [copy] [[PB]]
// CHECK: [[THUNK1:%.*]] = function_ref @_TTRXFo_dSi_dSd_XFo_iSi_iSd_
// CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [[THUNK1]]([[THICK_ARG]])
// CHECK: store [[ABSTRACTED_ARG]] to [init] [[ABSTRACTED_BOX]]
// CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]])
// CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [take] [[ABSTRACTED_BOX]]
// CHECK: [[THUNK2:%.*]] = function_ref @_TTRXFo_iSi_iSd_XFo_dSi_dSd_
// CHECK: [[NEW_ARG:%.*]] = partial_apply [[THUNK2]]([[NEW_ABSTRACTED_ARG]])
var minimallyAbstracted = transform
consumeGenericInOut(&minimallyAbstracted)
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dSi_dSd_XFo_iSi_iSd_ : $@convention(thin) (@in Int, @owned @callee_owned (Int) -> Double) -> @out Double
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iSi_iSd_XFo_dSi_dSd_ : $@convention(thin) (Int, @owned @callee_owned (@in Int) -> @out Double) -> Double
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue23reabstractMetatypeInOutFT_T_ : $@convention(thin) () -> ()
func reabstractMetatypeInOut() {
var thinMetatype = MyMetatypeIsThin.self
// CHECK: [[FUNC:%.*]] = function_ref @_TF17reabstract_lvalue19consumeGenericInOut
// CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type
// CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type
// CHECK: store [[THICK]] to [trivial] [[BOX]]
// CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]])
consumeGenericInOut(&thinMetatype)
}
| apache-2.0 | bac8b4dc6fbcb103198ce33c9f5105cb | 55.5 | 176 | 0.654867 | 3.327785 | false | false | false | false |
tbajis/Bop | Bop/ActivityIndicator.swift | 1 | 2100 | //
// ActivityIndicator.swift
// VirtualTourist
//
// Created by Thomas Manos Bajis on 3/24/17.
// Copyright © 2017 Thomas Manos Bajis. All rights reserved.
//
import UIKit
// MARK: - ActivityIndicator
class ActivityIndicator {
// MARK: Properties
private var container = UIView()
private var loadingView = UIView()
private var activityIndicator = UIActivityIndicatorView()
// MARK: Convenience Methods
func startActivityIndicator(inView hostView: UIView) {
container.tag = 100
container.frame = hostView.frame
container.center = hostView.center
container.backgroundColor = UIColor(red: 0.77, green: 0.75, blue: 0.75, alpha: 0.6)
loadingView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
loadingView.center = hostView.center
loadingView.backgroundColor = UIColor(red: 0.77, green: 0.75, blue: 0.75, alpha: 0.9)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
activityIndicator.hidesWhenStopped = true
activityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0)
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
activityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2)
loadingView.addSubview(activityIndicator)
container.addSubview(loadingView)
activityIndicator.startAnimating()
hostView.addSubview(container)
UIApplication.shared.beginIgnoringInteractionEvents()
}
func stopActivityIndicator(inView hostView: UIView) {
activityIndicator.stopAnimating()
hostView.viewWithTag(100)?.removeFromSuperview()
UIApplication.shared.endIgnoringInteractionEvents()
}
// MARK: Shared Instance
class func sharedInstance() -> ActivityIndicator {
struct Singleton {
static var sharedInstance = ActivityIndicator()
}
return Singleton.sharedInstance
}
}
| apache-2.0 | f8714e8f8c9d045a39af7394a65c2a0a | 32.854839 | 117 | 0.670319 | 4.973934 | false | false | false | false |
qingcai518/MyFacePlus | MyFacePlus/FaceCameraViewModel.swift | 1 | 1315 | //
// FaceCameraViewModel.swift
// MyFacePlus
//
// Created by liqc on 2017/07/10.
// Copyright © 2017年 RN-079. All rights reserved.
//
import UIKit
import RxSwift
class FaceCameraViewModel {
var mode = Variable(CameraMode.normal)
var faceType = FaceType.normal
var faceInfos = Variable([FaceInfo]())
func getFaceInfos() {
var result = [FaceInfo]()
result.append(FaceInfo(UIImage(named: "icon_face0")!, false))
result.append(FaceInfo(UIImage(named: "icon_face1")!, false))
result.append(FaceInfo(UIImage(named: "icon_face2")!, false))
result.append(FaceInfo(UIImage(named: "icon_face3")!, false))
result.append(FaceInfo(UIImage(named: "icon_face4")!, false))
result.append(FaceInfo(UIImage(named: "icon_face5")!, false))
result.append(FaceInfo(UIImage(named: "icon_face6")!, false))
result.append(FaceInfo(UIImage(named: "icon_face7")!, false))
result.append(FaceInfo(UIImage(named: "icon_face8")!, false))
result.append(FaceInfo(UIImage(named: "icon_face9")!, false))
result.append(FaceInfo(UIImage(named: "icon_face10")!, false))
let _ = (0..<result.count).filter{faceType.rawValue == $0}.map{result[$0].isSelected.value = true}
faceInfos.value = result
}
}
| apache-2.0 | 5c9ba5fbdea2f0294cf3908b661d2731 | 37.588235 | 106 | 0.64939 | 3.526882 | false | false | false | false |
Molbie/Outlaw | Sources/Outlaw/Types/ValueWithContext/Set+ValueWithContext.swift | 1 | 1864 | //
// Set+ValueWithContext.swift
// Outlaw
//
// Created by Brian Mullen on 11/15/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public extension Set {
static func mappedValue<Element: ValueWithContext>(from object: Any, using context: Element.Context) throws -> Set<Element> {
let anyArray: [Element] = try [Element].mappedValue(from: object, using: context)
return Set<Element>(anyArray)
}
}
// MARK: -
// MARK: Transforms
public extension Set {
static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element, Element.Context) throws -> T) throws -> Set<T> {
let anyArray: [T] = try [Element].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray)
}
static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element?, Element.Context) throws -> T) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element, Element.Context) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element?, Element.Context) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
}
| mit | ae45b84cdaf2597f956b4c1c04e0db19 | 43.357143 | 182 | 0.674181 | 3.778905 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModel/Private/Services/ConcretePrivateMessagesService.swift | 1 | 4633 | import EventBus
class ConcretePrivateMessagesService: PrivateMessagesService {
private let eventBus: EventBus
private let api: API
private lazy var state: State = UnauthenticatedState(service: self)
private var observers = [PrivateMessagesObserver]()
private var localMessages: [MessageImpl] = .empty {
didSet {
observers.forEach({ $0.privateMessagesServiceDidFinishRefreshingMessages(messages: localMessages) })
}
}
private class MarkMessageAsReadHandler: EventConsumer {
private let service: ConcretePrivateMessagesService
init(service: ConcretePrivateMessagesService) {
self.service = service
}
func consume(event: MessageImpl.ReadEvent) {
service.state.markMessageAsRead(event.message)
}
}
init(eventBus: EventBus, api: API) {
self.eventBus = eventBus
self.api = api
eventBus.subscribe(userLoggedIn)
eventBus.subscribe(userLoggedOut)
eventBus.subscribe(consumer: MarkMessageAsReadHandler(service: self))
}
func add(_ observer: PrivateMessagesObserver) {
observers.append(observer)
observer.privateMessagesServiceDidUpdateUnreadMessageCount(to: determineUnreadMessageCount())
observer.privateMessagesServiceDidFinishRefreshingMessages(messages: localMessages)
}
func refreshMessages() {
refreshMessages(completionHandler: nil)
}
func fetchMessage(identifiedBy identifier: MessageIdentifier) -> Message? {
return localMessages.first(where: { $0.identifier == identifier })
}
func refreshMessages(completionHandler: (() -> Void)? = nil) {
state.refreshMessages(completionHandler: completionHandler)
}
private func updateEntities(from messages: [MessageCharacteristics]) {
localMessages = messages.map(makeMessage).sorted()
updateObserversWithUnreadMessageCount()
}
private func notifyDidFailToLoadMessages() {
observers.forEach({ $0.privateMessagesServiceDidFailToLoadMessages() })
}
private func updateObserversWithUnreadMessageCount() {
let unreadCount = determineUnreadMessageCount()
observers.forEach({ $0.privateMessagesServiceDidUpdateUnreadMessageCount(to: unreadCount) })
}
private func determineUnreadMessageCount() -> Int {
return localMessages.filter({ $0.isRead == false }).count
}
private func makeMessage(from characteristics: MessageCharacteristics) -> MessageImpl {
return MessageImpl(eventBus: eventBus, characteristics: characteristics)
}
private func userLoggedIn(_ event: DomainEvent.LoggedIn) {
state = AuthenticatedState(service: self, token: event.authenticationToken)
}
private func userLoggedOut(_ event: DomainEvent.LoggedOut) {
localMessages.removeAll()
state = UnauthenticatedState(service: self)
}
// MARK: State Machine
private class State {
unowned let service: ConcretePrivateMessagesService
init(service: ConcretePrivateMessagesService) {
self.service = service
}
func refreshMessages(completionHandler: (() -> Void)? = nil) { }
func markMessageAsRead(_ message: Message) { }
}
private class UnauthenticatedState: State {
override func refreshMessages(completionHandler: (() -> Void)?) {
service.notifyDidFailToLoadMessages()
completionHandler?()
}
}
private class AuthenticatedState: State {
private let token: String
init(service: ConcretePrivateMessagesService, token: String) {
self.token = token
super.init(service: service)
}
override func refreshMessages(completionHandler: (() -> Void)?) {
service.api.loadPrivateMessages(authorizationToken: token) { (messages) in
if let messages = messages {
self.service.updateEntities(from: messages)
} else {
self.service.notifyDidFailToLoadMessages()
}
completionHandler?()
}
}
override func markMessageAsRead(_ message: Message) {
service.api.markMessageWithIdentifierAsRead(message.identifier.rawValue, authorizationToken: token)
service.updateObserversWithUnreadMessageCount()
}
}
}
| mit | a1b7ff942d430485d04fbf1ad97cf97c | 32.092857 | 112 | 0.64278 | 5.595411 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Starter/BabiFud/Workaround.swift | 2 | 3465 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import UIKit
import CloudKit
import CoreLocation
func upload(db: CKDatabase,
imageName: String,
placeName: String,
latitude: CLLocationDegrees,
longitude: CLLocationDegrees,
changingTable : ChangingTableLocation,
seatType: SeatingType,
healthy: Bool,
kidsMenu: Bool,
ratings: [UInt]) {
let imURL = NSBundle.mainBundle().URLForResource(imageName, withExtension: "jpeg")
let coverPhoto = CKAsset(fileURL: imURL)
let location = CLLocation(latitude: latitude, longitude: longitude)
let establishment = CKRecord(recordType: "Establishment")
establishment.setObject(coverPhoto, forKey: "CoverPhoto")
establishment.setObject(placeName, forKey: "Name")
establishment.setObject(location, forKey: "Location")
establishment.setObject(changingTable.toRaw(), forKey: "ChangingTable")
establishment.setObject(changingTable.toRaw(), forKey: "SeatingType")
establishment.setObject(healthy, forKey: "HealthyOption")
establishment.setObject(kidsMenu, forKey: "KidsMenu")
db.saveRecord(establishment) { record, error in
if error != nil {
println("error setting up record \(error)")
return
}
println("saved: \(record)")
for rating in ratings {
let ratingRecord = CKRecord(recordType: "Rating")
ratingRecord.setObject(rating, forKey: "Rating")
let ref = CKReference(record: record, action: CKReferenceAction.DeleteSelf)
ratingRecord.setObject(ref, forKey: "Establishment")
db.saveRecord(ratingRecord) { record, error in
if error != nil {
println("error setting up record \(error)")
return
}
}
}
}
}
func doWorkaround() {
let container = CKContainer.defaultContainer()
let db = container.publicCloudDatabase;
//Apple Campus location = 37.33182, -122.03118
upload(db, "pizza", "Ceasar's Pizza Palace", 37.332, -122.03, ChangingTableLocation.Womens, SeatingType.HighChair | SeatingType.Booster, false, true, [0, 1, 2])
upload(db, "chinese", "King Wok", 37.1, -122.1, ChangingTableLocation.None, SeatingType.HighChair, true, false, [])
upload(db, "steak", "The Back Deck", 37.4, -122.03, ChangingTableLocation.Womens | ChangingTableLocation.Mens, SeatingType.HighChair | SeatingType.Booster, true, true, [5, 5, 4])
} | mit | 246e018588b4517c3dc0c486de73308f | 40.759036 | 180 | 0.717749 | 4.189843 | false | false | false | false |
grachro/swift-layout | swift-layout/sampleViewControllers/HorizontalEvenSpaceViewController.swift | 1 | 2721 | //
// HorizontalEvenSpaceViewController.swift
// swift-layout
//
// Created by grachro on 2014/09/07.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class HorizontalEvenSpaceViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
coverSpace()
nonCoverSpace()
//戻るボタン
addReturnBtn()
}
fileprivate func coverSpace() {
let l1 = UILabel()
l1.text = "l1"
l1.backgroundColor = UIColor.red
Layout.addSubView(l1, superview: self.view)
.top(30).fromSuperviewTop()
.width(30)
.height(50)
let l2 = UILabel()
l2.text = "l2"
l2.backgroundColor = UIColor.green
Layout.addSubView(l2, superview: self.view)
.verticalCenterIsSame(l1)
.widthIsSame(l1)
.height(60)
let l3 = UILabel()
l3.text = "l3"
l3.backgroundColor = UIColor.blue
Layout.addSubView(l3, superview: self.view)
.verticalCenterIsSame(l1)
.widthIsSame(l1)
.height(60)
Layout.horizontalEvenSpaceInCotainer(superview: self.view, views: [l1,l2,l3], coverSpace: true)
}
fileprivate func nonCoverSpace() {
let l1 = UILabel()
l1.text = "l1"
l1.backgroundColor = UIColor.red
Layout.addSubView(l1, superview: self.view)
.bottom(30).fromSuperviewBottom()
.width(30)
.height(50)
let l2 = UILabel()
l2.text = "l2"
l2.backgroundColor = UIColor.green
Layout.addSubView(l2, superview: self.view)
.verticalCenterIsSame(l1)
.widthIsSame(l1)
.height(60)
let l3 = UILabel()
l3.text = "l3"
l3.backgroundColor = UIColor.blue
Layout.addSubView(l3, superview: self.view)
.verticalCenterIsSame(l1)
.widthIsSame(l1)
.height(60)
Layout.horizontalEvenSpaceInCotainer(superview: self.view, views: [l1,l2,l3], coverSpace: false)
}
fileprivate func addReturnBtn() {
let btn = Layout.createSystemTypeBtn("return")
Layout.addSubView(btn, superview: self.view)
.bottomIsSameSuperview()
.rightIsSameSuperview()
TouchBlocks.append(btn){
self.dismiss(animated: true, completion:nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 496270a96d5ca36d6f913128e83d82ab | 25.558824 | 104 | 0.557032 | 4.043284 | false | false | false | false |
chengxianghe/MissGe | MissGe/MissGe/Class/Project/Request/Square/MLPostTopicRequest.swift | 1 | 3008 | //
// MLPostTopicRequest.swift
// MissLi
//
// Created by chengxianghe on 16/7/20.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=addpost&token=X%2FZTO4eBrq%2FnmgZSoqA9eshEbpWRSs7%2B%2BkqAtMZAf5mvzTo&fid=3&detail=有工程师给看看么?这是怎么了?&title=有工程师给看看么?这&anonymous=0&ids=25339,25340
class MLPostTopicRequest: MLBaseRequest {
var anonymous = 0
var detail = ""
var ids:[String]?
//c=post&a=addpost&token=X%2FZTO4eBrq%2FnmgZSoqA9eshEbpWRSs7%2B%2BkqAtMZAf5mvzTo&fid=3&detail=有工程师给看看么?这是怎么了?&title=有工程师给看看么?这&anonymous=0&ids=25339,25340
override func requestParameters() -> [String : Any]? {
let title: String = detail.length > 10 ? (detail as NSString).substring(to: 10) : detail;
var dict: [String : String] = ["c":"post","a":"addpost","token":MLNetConfig.shareInstance.token,"detail":"\(detail)","anonymous":"\(anonymous)", "title":title, "fid":"3"]
if ids != nil && ids!.count > 0 {
dict["ids"] = ids!.joined(separator: ",")
}
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
/*
传图
POST http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=upload&a=postUpload&token=X%252FZTO4eBrq%252FnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5mvzTo
body 带图
返回
{"result":"200","msg":"\u56fe\u50cf\u4e0a\u4f20\u6210\u529f","content":{"image_name":"uploadImg_0.png","url":"http:\/\/img.gexiaojie.com\/post\/2016\/0718\/160718100723P003873V86.png","image_id":25339}}
*/
//class MLUploadImageRequest: MLBaseRequest {
//
// var fileURL: NSURL!
// var fileBodyblock: AFConstructingBlock!
// var uploadProgress: AFProgressBlock = { (progress: NSProgress) in
// print("uploadProgressBlock:" + progress.localizedDescription)
// }
//
//
// override func requestMethod() -> TURequestMethod {
// return TURequestMethod.Post
// }
//
// //c=upload&a=postUpload&token=X%252FZTO4eBrq%252FnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5mvzTo
//
// override func requestUrl() -> String {
// return "c=upload&a=postUpload&token=\(MLNetConfig.shareInstance.token)"
// }
//
// override func requestHandleResult() {
// print("requestHandleResult -- \(self.classForCoder)")
// }
//
// override func requestVerifyResult() -> Bool {
// return (self.responseObject?["result"] as? String) == "200"
// }
//
//}
| mit | f8b37be2438537e18963df116a1cf61e | 35.620253 | 285 | 0.663671 | 2.87289 | false | false | false | false |
louisdh/lioness | Sources/Lioness/AST/Nodes/Loops/LoopNode.swift | 1 | 1280 | //
// LoopNode.swift
// Lioness
//
// Created by Louis D'hauwe on 09/12/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
protocol LoopNode: ASTNode {
func compileLoop(with ctx: BytecodeCompiler, scopeStart: Int) throws -> BytecodeBody
}
extension LoopNode {
public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody {
var bytecode = BytecodeBody()
ctx.enterNewScope()
let skipExitInstrLabel = ctx.nextIndexLabel()
let exitLoopInstrLabel = ctx.nextIndexLabel()
ctx.pushLoopHeader(exitLoopInstrLabel)
let loopScopeStart = ctx.peekNextIndexLabel()
let compiledLoop = try compileLoop(with: ctx, scopeStart: loopScopeStart)
let loopEndLabel = ctx.peekNextIndexLabel()
let skipExitInstruction = BytecodeInstruction(label: skipExitInstrLabel, type: .goto, arguments: [.index(loopScopeStart)], comment: "skip exit instruction")
bytecode.append(skipExitInstruction)
let exitLoopInstruction = BytecodeInstruction(label: exitLoopInstrLabel, type: .goto, arguments: [.index(loopEndLabel)], comment: "exit loop")
bytecode.append(exitLoopInstruction)
bytecode.append(contentsOf: compiledLoop)
ctx.popLoopHeader()
try ctx.leaveCurrentScope()
return bytecode
}
}
| mit | 14b146169b082ce041a64ae6438c55b0 | 23.596154 | 158 | 0.757623 | 3.523416 | false | false | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/ViewControllers/ChatViewController/ChatViewController/ChatViewController+UITableView.swift | 1 | 9078 | //
// ChatViewController+UITableView.swift
// WebimClientLibrary_Example
//
// Created by Anna Frolova on 21.01.2022.
// Copyright © 2022 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import WebimClientLibrary
extension ChatViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
if !messages().isEmpty {
tableView.backgroundView = nil
return 1
} else {
tableView.emptyTableView(
message: "Send first message to start chat.".localized
)
return 0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages().count
}
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
guard indexPath.row < messages().count else { return UITableViewCell() }
let message = messages()[indexPath.row]
return updatedCellGeneration(message)
}
@available(iOS 11.0, *)
func tableView(
_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let message = messages()[indexPath.row]
if message.isSystemType() || message.isOperatorType() || !message.canBeReplied() {
return nil
}
let replyAction = UIContextualAction(
style: .normal,
title: nil,
handler: { (_, _, completionHandler) in
self.selectedMessage = message
self.addQuoteEditBar()
completionHandler(true)
}
)
// Workaround for iOS < 13
if let cgImageReplyAction = trailingSwipeActionImage.cgImage {
replyAction.image = CustomUIImage(
cgImage: cgImageReplyAction,
scale: UIScreen.main.nativeScale,
orientation: .up
)
}
replyAction.backgroundColor = tableView.backgroundColor
return UISwipeActionsConfiguration(actions: [replyAction])
}
@available(iOS 11.0, *)
func tableView(
_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let message = messages()[indexPath.row]
if message.isSystemType() || message.isVisitorType() || !message.canBeReplied() {
return nil
}
let replyAction = UIContextualAction(
style: .normal,
title: nil,
handler: { (_, _, completionHandler) in
self.selectedMessage = message
self.addQuoteReplyBar()
completionHandler(true)
}
)
// Workaround for iOS < 13
if let cgImageReplyAction = leadingSwipeActionImage.cgImage {
replyAction.image = CustomUIImage(
cgImage: cgImageReplyAction,
scale: UIScreen.main.nativeScale,
orientation: .up
)
}
replyAction.backgroundColor = tableView.backgroundColor
return UISwipeActionsConfiguration(actions: [replyAction])
}
func tableView(
_ tableView: UITableView,
editingStyleForRowAt indexPath: IndexPath
) -> UITableViewCell.EditingStyle { .none }
// Dynamic Cell Sizing
func tableView(
_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath
) {
cellHeights[indexPath] = cell.frame.size.height
}
func tableView(
_ tableView: UITableView,
estimatedHeightForRowAt indexPath: IndexPath
) -> CGFloat { cellHeights[indexPath] ?? 70.0 }
func messages() -> [Message] {
return showSearchResult ? searchMessages : chatMessages
}
func showSearchResult(messages: [Message]?) {
if let messages = messages {
self.searchMessages = messages
self.showSearchResult = true
} else {
self.searchMessages = []
self.showSearchResult = false
}
self.chatTableView.reloadData()
}
func updatedCellGeneration(_ message: Message) -> UITableViewCell {
var isImage = false
var isFile = false
var hasQuote = false
var hasQuoteImage = false
var hasQuoteFile = false
if let quote = message.getQuote() {
hasQuote = true
if quote.getMessageAttachment() != nil {
hasQuoteImage = MimeType.isImage(contentType: quote.getMessageAttachment()?.getContentType() ?? "")
hasQuoteFile = !isImage
}
} else {
if let attachment = message.getData()?.getAttachment() {
isImage = MimeType.isImage(contentType: attachment.getFileInfo().getContentType() ?? "")
isFile = !isImage
}
}
if message.getType() == .info || message.getType() == .contactInformationRequest || message.getType() == .operatorBusy {
return self.messageCellWithType(WMInfoCell.self, message: message)
}
if message.getType() == .keyboard {
return self.messageCellWithType(WMBotButtonsTableViewCell.self, message: message)
}
if message.isVisitorType() {
if hasQuote {
if hasQuoteImage {
return self.messageCellWithType(WMVisitorQuoteImageCell.self, message: message)
}
if hasQuoteFile {
return self.messageCellWithType(WMVisitorQuoteFileCell.self, message: message)
}
return self.messageCellWithType(WMVisitorQuoteMessageCell.self, message: message)
} else {
if isFile {
return self.messageCellWithType(WMVisitorFileCell.self, message: message)
}
if isImage {
return self.messageCellWithType(WMVisitorImageCell.self, message: message)
}
}
return self.messageCellWithType(WMVisitorMessageCell.self, message: message)
}
if message.isOperatorType() {
if hasQuote {
if hasQuoteImage {
return self.messageCellWithType(WMOperatorQuoteImageCell.self, message: message)
}
if hasQuoteFile {
return self.messageCellWithType(WMOperatorQuoteFileCell.self, message: message)
}
return self.messageCellWithType(WMOperatorQuoteMessageCell.self, message: message)
} else {
if isFile {
return self.messageCellWithType(WMOperatorFileCell.self, message: message)
}
if isImage {
return self.messageCellWithType(WMOperatorImageCell.self, message: message)
}
return self.messageCellWithType(WMOperatorMessageCell.self, message: message)
}
}
#if DEBUG
fatalError("no correct cell type")
#else
print("no correct cell type")
#endif
return self.messageCellWithType(WMInfoCell.self, message: message)
}
func messageCellWithType<T: WMMessageTableCell>(_ type: T.Type, message: Message) -> T {
let cell = self.chatTableView.dequeueReusableCellWithType(type)
cell.delegate = self
_ = cell.initialSetup()
cell.setMessage(message: message, tableView: self.chatTableView)
cell.delegate = self
return cell
}
}
| mit | bade6db54e2e57afb220ed6df3014984 | 35.163347 | 128 | 0.598215 | 5.380557 | false | false | false | false |
Mobilette/AniMee | Pods/PromiseKit/Categories/Foundation/NSURLConnection+Promise.swift | 15 | 2235 | import Foundation
import OMGHTTPURLRQ
#if !COCOAPODS
import PromiseKit
#endif
/**
To import the `NSURLConnection` category:
use_frameworks!
pod "PromiseKit/Foundation"
Or `NSURLConnection` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
import PromiseKit
*/
extension NSURLConnection {
public class func GET(URL: String, query: [NSObject:AnyObject]? = nil) -> URLDataPromise {
return go(try OMGHTTPURLRQ.GET(URL, query))
}
public class func POST(URL: String, formData: [NSObject:AnyObject]? = nil) -> URLDataPromise {
return go(try OMGHTTPURLRQ.POST(URL, formData))
}
public class func POST(URL: String, JSON: [NSObject:AnyObject]) -> URLDataPromise {
return go(try OMGHTTPURLRQ.POST(URL, JSON: JSON))
}
public class func POST(URL: String, multipartFormData: OMGMultipartFormData) -> URLDataPromise {
return go(try OMGHTTPURLRQ.POST(URL, multipartFormData))
}
public class func PUT(URL: String, formData: [NSObject:AnyObject]? = nil) -> URLDataPromise {
return go(try OMGHTTPURLRQ.PUT(URL, formData))
}
public class func PUT(URL: String, JSON: [NSObject:AnyObject]) -> URLDataPromise {
return go(try OMGHTTPURLRQ.PUT(URL, JSON: JSON))
}
public class func DELETE(URL: String) -> URLDataPromise {
return go(try OMGHTTPURLRQ.DELETE(URL, nil))
}
public class func promise(request: NSURLRequest) -> URLDataPromise {
return go(request)
}
}
private func go(@autoclosure body: () throws -> NSURLRequest) -> URLDataPromise {
do {
var request = try body()
if request.valueForHTTPHeaderField("User-Agent") == nil {
let rq = request.mutableCopy() as! NSMutableURLRequest
rq.setValue(OMGUserAgent(), forHTTPHeaderField: "User-Agent")
request = rq
}
return URLDataPromise.go(request) { completionHandler in
NSURLConnection.sendAsynchronousRequest(request, queue: Q, completionHandler: { completionHandler($1, $0, $2) })
}
} catch {
return URLDataPromise(error: error)
}
}
private let Q = NSOperationQueue()
| mit | 10c38954ce0ea9470be1fd3fe0d8bc25 | 29.202703 | 124 | 0.668904 | 4.100917 | false | false | false | false |
FilipLukac/makac | SidebarMenu/WeatherViewController.swift | 1 | 1111 | //
// ActivityViewController.swift
// Makac
//
// Created by Filip Lukac on 13/12/15.
// Copyright © 2015 Hardsun. All rights reserved.
//
import UIKit
class WeatherViewController: UIViewController {
@IBOutlet weak var menuButton:UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 4b07f574c8a2d5750a405cb2477af811 | 29.833333 | 113 | 0.668468 | 5.692308 | false | false | false | false |
KrishMunot/swift | stdlib/public/core/Unicode.swift | 2 | 30000 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// A unicode scalar value, an indication that no more unicode scalars
/// are available, or an indication of a decoding error.
public enum UnicodeDecodingResult : Equatable {
case scalarValue(UnicodeScalar)
case emptyInput
case error
}
public func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
/// A Unicode [encoding scheme](http://www.unicode.org/glossary/#character_encoding_scheme).
///
/// Consists of an underlying [code unit](http://www.unicode.org/glossary/#code_unit)
/// and functions to translate between sequences of these code units and
/// [unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value).
public protocol UnicodeCodec {
/// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit)
/// values for this encoding.
associatedtype CodeUnit
init()
/// Start or continue decoding a UTF sequence.
///
/// In order to decode a code unit sequence completely, this function should
/// be called repeatedly until it returns `UnicodeDecodingResult.emptyInput`.
/// Checking that the iterator was exhausted is not sufficient. The decoder
/// can have an internal buffer that is pre-filled with data from the input
/// iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// - Parameter next: An iterator of code units to be decoded. Repeated
/// calls to this method on the same instance should always pass the same
/// iterator and the iterator or copies thereof should not be used for
/// anything else between calls. Failing to do so will yield unspecified
/// results.
mutating func decode<
I : IteratorProtocol where I.Element == CodeUnit
>(_ next: inout I) -> UnicodeDecodingResult
/// Encode a `UnicodeScalar` as a series of `CodeUnit`s by
/// calling `processCodeUnit` on each `CodeUnit`.
static func encode(
_ input: UnicodeScalar,
@noescape sendingOutputTo processCodeUnit: (CodeUnit) -> Void
)
}
/// A codec for [UTF-8](http://www.unicode.org/glossary/#UTF_8).
public struct UTF8 : UnicodeCodec {
// See Unicode 8.0.0, Ch 3.9, UTF-8.
// http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf
/// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit)
/// values for this encoding.
public typealias CodeUnit = UInt8
public init() {}
/// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at MSB,
/// and bytes are read at LSB. Note that we need to use a buffer, because
/// in case of invalid subsequences we sometimes don't know whether we should
/// consume a certain byte before looking at it.
internal var _decodeBuffer: UInt32 = 0
/// The number of bits in `_decodeBuffer` that are current filled.
internal var _bitsInBuffer: UInt8 = 0
/// Whether we have exhausted the iterator. Note that this doesn't mean
/// we are done decoding, as there might still be bytes left in the buffer.
internal var _didExhaustIterator: Bool = false
/// Start or continue decoding a UTF-8 sequence.
///
/// In order to decode a code unit sequence completely, this function should
/// be called repeatedly until it returns `UnicodeDecodingResult.emptyInput`.
/// Checking that the iterator was exhausted is not sufficient. The decoder
/// can have an internal buffer that is pre-filled with data from the input
/// iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// - Parameter next: An iterator of code units to be decoded. Repeated
/// calls to this method on the same instance should always pass the same
/// iterator and the iterator or copies thereof should not be used for
/// anything else between calls. Failing to do so will yield unspecified
/// results.
public mutating func decode<
I : IteratorProtocol where I.Element == CodeUnit
>(_ next: inout I) -> UnicodeDecodingResult {
refillBuffer: if !_didExhaustIterator {
// Bufferless ASCII fastpath.
if _fastPath(_bitsInBuffer == 0) {
if let codeUnit = next.next() {
if codeUnit & 0x80 == 0 {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_decodeBuffer = UInt32(codeUnit)
_bitsInBuffer = 8
} else {
_didExhaustIterator = true
return .emptyInput
}
} else if (_decodeBuffer & 0x80 == 0) {
// ASCII in buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
break refillBuffer
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
_sanityCheck(_bitsInBuffer < 32)
repeat {
if let codeUnit = next.next() {
// We use & 0x1f to make the compiler omit a bounds check branch.
_decodeBuffer |= (UInt32(codeUnit) << UInt32(_bitsInBuffer & 0x1f))
_bitsInBuffer = _bitsInBuffer &+ 8
} else {
_didExhaustIterator = true
if _bitsInBuffer == 0 { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _bitsInBuffer < 32
} else if _bitsInBuffer == 0 {
return .emptyInput
}
// Decode one unicode scalar.
// Note our empty bytes are always 0x00, which is required for this call.
let (result, length) = UTF8._decodeOne(_decodeBuffer)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let bitsConsumed = 8 &* length
_sanityCheck(1...4 ~= length && bitsConsumed <= _bitsInBuffer)
// Swift doesn't allow shifts greater than or equal to the type width.
// _decodeBuffer >>= UInt32(bitsConsumed) // >>= 32 crashes.
// Mask with 0x3f to let the compiler omit the '>= 64' bounds check.
_decodeBuffer = UInt32(truncatingBitPattern:
UInt64(_decodeBuffer) >> (UInt64(bitsConsumed) & 0x3f))
_bitsInBuffer = _bitsInBuffer &- bitsConsumed
if _fastPath(result != nil) {
return .scalarValue(UnicodeScalar(_unchecked: result!))
} else {
return .error // Ill-formed UTF-8 code unit sequence.
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
@warn_unused_result
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ … … … CU0 ].
let value = buffer & 0xff
return (value, 1)
}
// Determine sequence length using high 5 bits of 1st byte. We use a
// look-up table to branch less. 1-byte sequences are handled above.
//
// case | pattern | description
// ----------------------------
// 00 | 110xx | 2-byte sequence
// 01 | 1110x | 3-byte sequence
// 10 | 11110 | 4-byte sequence
// 11 | other | invalid
//
// 11xxx 10xxx 01xxx 00xxx
let lut0: UInt32 = 0b1011_0000__1111_1111__1111_1111__1111_1111
let lut1: UInt32 = 0b1100_0000__1111_1111__1111_1111__1111_1111
let index = (buffer >> 3) & 0x1f
let bit0 = (lut0 >> index) & 1
let bit1 = (lut1 >> index) & 1
switch (bit1, bit0) {
case (0, 0): // 2-byte sequence, buffer: [ … … CU1 CU0 ].
// Require 10xx xxxx 110x xxxx.
if _slowPath(buffer & 0xc0e0 != 0x80c0) { return (nil, 1) }
// Disallow xxxx xxxx xxx0 000x (<= 7 bits case).
if _slowPath(buffer & 0x001e == 0x0000) { return (nil, 1) }
// Extract data bits.
let value = (buffer & 0x3f00) >> 8
| (buffer & 0x001f) << 6
return (value, 2)
case (0, 1): // 3-byte sequence, buffer: [ … CU2 CU1 CU0 ].
// Disallow xxxx xxxx xx0x xxxx xxxx 0000 (<= 11 bits case).
if _slowPath(buffer & 0x00200f == 0x000000) { return (nil, 1) }
// Disallow xxxx xxxx xx1x xxxx xxxx 1101 (surrogate code points).
if _slowPath(buffer & 0x00200f == 0x00200d) { return (nil, 1) }
// Require 10xx xxxx 10xx xxxx 1110 xxxx.
if _slowPath(buffer & 0xc0c0f0 != 0x8080e0) {
if buffer & 0x00c000 != 0x008000 { return (nil, 1) }
return (nil, 2) // All checks on CU0 & CU1 passed.
}
// Extract data bits.
let value = (buffer & 0x3f0000) >> 16
| (buffer & 0x003f00) >> 2
| (buffer & 0x00000f) << 12
return (value, 3)
case (1, 0): // 4-byte sequence, buffer: [ CU3 CU2 CU1 CU0 ].
// Disallow xxxx xxxx xxxx xxxx xx00 xxxx xxxx x000 (<= 16 bits case).
if _slowPath(buffer & 0x00003007 == 0x00000000) { return (nil, 1) }
// If xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx.
if buffer & 0x00000004 == 0x00000004 {
// Require xxxx xxxx xxxx xxxx xx00 xxxx xxxx xx00 (<= 0x10FFFF).
if _slowPath(buffer & 0x00003003 != 0x00000000) { return (nil, 1) }
}
// Require 10xx xxxx 10xx xxxx 10xx xxxx 1111 0xxx.
if _slowPath(buffer & 0xc0c0c0f8 != 0x808080f0) {
if buffer & 0x0000c000 != 0x00008000 { return (nil, 1) }
// All other checks on CU0, CU1 & CU2 passed.
if buffer & 0x00c00000 != 0x00800000 { return (nil, 2) }
return (nil, 3)
}
// Extract data bits.
let value = (buffer & 0x3f000000) >> 24
| (buffer & 0x003f0000) >> 10
| (buffer & 0x00003f00) << 4
| (buffer & 0x00000007) << 18
return (value, 4)
default: // Invalid sequence (CU0 invalid).
return (nil, 1)
}
}
/// Encode a `UnicodeScalar` as a series of `CodeUnit`s by
/// calling `processCodeUnit` on each `CodeUnit`.
public static func encode(
_ input: UnicodeScalar,
@noescape sendingOutputTo processCodeUnit: (CodeUnit) -> Void
) {
var c = UInt32(input)
var buf3 = UInt8(c & 0xFF)
if c >= UInt32(1<<7) {
c >>= 6
buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx
var buf2 = UInt8(c & 0xFF)
if c < UInt32(1<<5) {
buf2 |= 0xC0 // 110xxxxx
}
else {
c >>= 6
buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx
var buf1 = UInt8(c & 0xFF)
if c < UInt32(1<<4) {
buf1 |= 0xE0 // 1110xxxx
}
else {
c >>= 6
buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx
processCodeUnit(UInt8(c | 0xF0)) // 11110xxx
}
processCodeUnit(buf1)
}
processCodeUnit(buf2)
}
processCodeUnit(buf3)
}
/// Returns `true` if `byte` is a continuation byte of the form
/// `0b10xxxxxx`.
@warn_unused_result
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
}
/// A codec for [UTF-16](http://www.unicode.org/glossary/#UTF_16).
public struct UTF16 : UnicodeCodec {
/// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit)
/// values for this encoding.
public typealias CodeUnit = UInt16
public init() {}
/// A lookahead buffer for one UTF-16 code unit.
internal var _decodeLookahead: UInt32 = 0
/// Flags with layout: `0b0000_00xy`.
///
/// `y` is the EOF flag.
///
/// `x` is set when `_decodeLookahead` contains a code unit.
internal var _lookaheadFlags: UInt8 = 0
/// Start or continue decoding a UTF sequence.
///
/// In order to decode a code unit sequence completely, this function should
/// be called repeatedly until it returns `UnicodeDecodingResult.emptyInput`.
/// Checking that the iterator was exhausted is not sufficient. The decoder
/// can have an internal buffer that is pre-filled with data from the input
/// iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// - Parameter next: An iterator of code units to be decoded. Repeated
/// calls to this method on the same instance should always pass the same
/// iterator and the iterator or copies thereof should not be used for
/// anything else between calls. Failing to do so will yield unspecified
/// results.
public mutating func decode<
I : IteratorProtocol where I.Element == CodeUnit
>(_ input: inout I) -> UnicodeDecodingResult {
if _lookaheadFlags & 0b01 != 0 {
return .emptyInput
}
// Note: maximal subpart of ill-formed sequence for UTF-16 can only have
// length 1. Length 0 does not make sense. Neither does length 2 -- in
// that case the sequence is valid.
var unit0: UInt32
if _fastPath(_lookaheadFlags & 0b10 == 0) {
if let first = input.next() {
unit0 = UInt32(first)
} else {
// Set EOF flag.
_lookaheadFlags |= 0b01
return .emptyInput
}
} else {
// Fetch code unit from the lookahead buffer and note this fact in flags.
unit0 = _decodeLookahead
_lookaheadFlags &= 0b01
}
// A well-formed pair of surrogates looks like this:
// [1101 10ww wwxx xxxx] [1101 11xx xxxx xxxx]
if _fastPath((unit0 >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- sequence of 1 code unit,
// decoding is trivial.
return .scalarValue(UnicodeScalar(unit0))
}
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
return .error
}
// At this point we know that `unit0` is a high-surrogate.
var unit1: UInt32
if let second = input.next() {
unit1 = UInt32(second)
} else {
// EOF reached. Set EOF flag.
_lookaheadFlags |= 0b01
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence.
return .error
}
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate pair.
let result = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
return .scalarValue(UnicodeScalar(result))
}
// Otherwise, we have an ill-formed sequence. These are the possible
// cases:
//
// * `unit1` is a high-surrogate, so we have a pair of two high-surrogates.
//
// * `unit1` is not a surrogate. We have an ill-formed sequence:
// high-surrogate followed by a non-surrogate.
// Save the second code unit in the lookahead buffer.
_decodeLookahead = unit1
_lookaheadFlags |= 0b10
return .error
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<
I : IteratorProtocol where I.Element == CodeUnit
>(_ input: inout I) -> (UnicodeDecodingResult, Int) {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encode a `UnicodeScalar` as a series of `CodeUnit`s by
/// calling `processCodeUnit` on each `CodeUnit`.
public static func encode(
_ input: UnicodeScalar,
@noescape sendingOutputTo processCodeUnit: (CodeUnit) -> Void
) {
let scalarValue: UInt32 = UInt32(input)
if scalarValue <= UInt32(UInt16.max) {
processCodeUnit(UInt16(scalarValue))
}
else {
let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10)
processCodeUnit(UInt16(lead_offset + (scalarValue >> 10)))
processCodeUnit(UInt16(0xdc00 + (scalarValue & 0x3ff)))
}
}
}
/// A codec for [UTF-32](http://www.unicode.org/glossary/#UTF_32).
public struct UTF32 : UnicodeCodec {
/// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit)
/// values for this encoding.
public typealias CodeUnit = UInt32
public init() {}
/// Start or continue decoding a UTF sequence.
///
/// In order to decode a code unit sequence completely, this function should
/// be called repeatedly until it returns `UnicodeDecodingResult.emptyInput`.
/// Checking that the iterator was exhausted is not sufficient. The decoder
/// can have an internal buffer that is pre-filled with data from the input
/// iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// - Parameter next: An iterator of code units to be decoded. Repeated
/// calls to this method on the same instance should always pass the same
/// iterator and the iterator or copies thereof should not be used for
/// anything else between calls. Failing to do so will yield unspecified
/// results.
public mutating func decode<
I : IteratorProtocol where I.Element == CodeUnit
>(_ input: inout I) -> UnicodeDecodingResult {
return UTF32._decode(&input)
}
internal static func _decode<
I : IteratorProtocol where I.Element == CodeUnit
>(_ input: inout I) -> UnicodeDecodingResult {
guard let x = input.next() else { return .emptyInput }
if _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff) {
return .scalarValue(UnicodeScalar(x))
} else {
return .error
}
}
/// Encode a `UnicodeScalar` as a series of `CodeUnit`s by
/// calling `processCodeUnit` on each `CodeUnit`.
public static func encode(
_ input: UnicodeScalar,
@noescape sendingOutputTo processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translate `input`, in the given `InputEncoding`, into `processCodeUnit`, in
/// the given `OutputEncoding`.
///
/// - Parameter stopOnError: Causes encoding to stop when an encoding
/// error is detected in `input`, if `true`. Otherwise, U+FFFD
/// replacement characters are inserted for each detected error.
public func transcode<
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec
where InputEncoding.CodeUnit == Input.Element
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
@noescape sendingOutputTo processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var inputDecoder = inputEncoding.init()
var hadError = false
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
OutputEncoding.encode(us, sendingOutputTo: processCodeUnit)
case .emptyInput:
break loop
case .error:
hadError = true
if stopOnError {
break loop
}
OutputEncoding.encode("\u{fffd}", sendingOutputTo: processCodeUnit)
}
}
return hadError
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
@warn_unused_result
internal func _transcodeSomeUTF16AsUTF8<
Input : Collection
where
Input.Iterator.Element == UInt16>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk) {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = sizeof(_UTF8Chunk.self)
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.Index.Distance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) << shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u >> 6
r |= (u & 0b11_1111) << 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u >> 12
r |= ((u >> 6) & 0b11_1111) << 8
r |= (u & 0b11_1111) << 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(nextIndex.advanced(by: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[nextIndex.advanced(by: 1)])
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v >> 18
r |= ((v >> 12) & 0b11_1111) << 8
r |= ((v >> 6) & 0b11_1111) << 16
r |= (v & 0b11_1111) << 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) << shift
utf8Count += scalarUtf8Length
}
nextIndex = nextIndex.advanced(by: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < sizeofValue(result) {
result |= ~0 << numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
@warn_unused_result
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
@warn_unused_result
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode `x`.
@warn_unused_result
public static func width(_ x: UnicodeScalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high surrogate code unit of a [surrogate pair](http://www.unicode.org/glossary/#surrogate_pair) representing
/// `x`.
///
/// - Precondition: `width(x) == 2`.
@warn_unused_result
public static func leadSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800
}
/// Returns the low surrogate code unit of a [surrogate pair](http://www.unicode.org/glossary/#surrogate_pair) representing
/// `x`.
///
/// - Precondition: `width(x) == 2`.
@warn_unused_result
public static func trailSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit(
(x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1)
) + 0xDC00
}
@warn_unused_result
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
@warn_unused_result
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if strideof(T.self) == strideof(U.self) {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(strideof(U.self)))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a bit describing if the sequence
/// was found to contain only ASCII characters.
///
/// If `repairIllFormedSequences` is `true`, the function always succeeds.
/// If it is `false`, `nil` is returned if an ill-formed code unit sequence is
/// found in `input`.
@warn_unused_result
public static func transcodedLength<
Encoding : UnicodeCodec, Input : IteratorProtocol
where Encoding.CodeUnit == Input.Element
>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)? {
var input = input
var count = 0
var isAscii = true
var inputDecoder = Encoding()
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
if us.value > 0x7f {
isAscii = false
}
count += width(us)
case .emptyInput:
break loop
case .error:
if !repairingIllFormedSequences {
return nil
}
isAscii = false
count += width(UnicodeScalar(0xfffd))
}
}
return (count, isAscii)
}
}
// Unchecked init to avoid precondition branches in hot code paths were we
// already know the value is a valid unicode scalar.
extension UnicodeScalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:sendingOutputTo:)'")
public func transcode<
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec
where InputEncoding.CodeUnit == Input.Element
>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stoppingOnError stopOnError: Bool
) -> Bool {
fatalError("unavailable function can't be called")
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<
Encoding : UnicodeCodec, Input : IteratorProtocol
where Encoding.CodeUnit == Input.Element
>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)? {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | 6bcab062303ed776c36bc46e7a38488a | 34.404959 | 126 | 0.63392 | 3.866925 | false | false | false | false |
DannyKG/BoLianEducation | BoLianEducation/Task/ViewController/LeftAlignedLayoutSwift.swift | 1 | 4387 | //
// LeftAlignedLayoutSwift.swift
// BoLianEducation
//
// Created by BoLian on 2017/8/24.
// Copyright © 2017年 BoLian. All rights reserved.
//
import UIKit
extension UICollectionViewLayoutAttributes {
func leftAlignFrameWithSectionInset(_ sectionInset:UIEdgeInsets){
var frame = self.frame
frame.origin.x = sectionInset.left
self.frame = frame
}
}
class LeftAlignedLayoutSwift: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributesCopy: [UICollectionViewLayoutAttributes] = []
if let attributes = super.layoutAttributesForElements(in: rect) {
attributes.forEach({ attributesCopy.append($0.copy() as! UICollectionViewLayoutAttributes) })
}
for attributes in attributesCopy {
if attributes.representedElementKind == nil {
let indexpath = attributes.indexPath
if let attr = layoutAttributesForItem(at: indexpath) {
attributes.frame = attr.frame
}
}
}
return attributesCopy
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let currentItemAttributes = super.layoutAttributesForItem(at: indexPath as IndexPath)?.copy() as? UICollectionViewLayoutAttributes {
let sectionInset = self.evaluatedSectionInsetForItem(at: indexPath.section)
let isFirstItemInSection = indexPath.item == 0
let layoutWidth = self.collectionView!.frame.width - sectionInset.left - sectionInset.right
if (isFirstItemInSection) {
currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset)
return currentItemAttributes
}
let previousIndexPath = IndexPath.init(row: indexPath.item - 1, section: indexPath.section)
let previousFrame = layoutAttributesForItem(at: previousIndexPath)?.frame ?? CGRect.zero
let previousFrameRightPoint = previousFrame.origin.x + previousFrame.width
let currentFrame = currentItemAttributes.frame
let strecthedCurrentFrame = CGRect.init(x: sectionInset.left,
y: currentFrame.origin.y,
width: layoutWidth,
height: currentFrame.size.height)
// if the current frame, once left aligned to the left and stretched to the full collection view
// widht intersects the previous frame then they are on the same line
let isFirstItemInRow = !previousFrame.intersects(strecthedCurrentFrame)
if (isFirstItemInRow) {
// make sure the first item on a line is left aligned
currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset)
return currentItemAttributes
}
var frame = currentItemAttributes.frame
frame.origin.x = previousFrameRightPoint + evaluatedMinimumInteritemSpacing(at: indexPath.section)
currentItemAttributes.frame = frame
return currentItemAttributes
}
return nil
}
func evaluatedMinimumInteritemSpacing(at sectionIndex:Int) -> CGFloat {
if let delegate = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout {
let inteitemSpacing = delegate.collectionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAt: sectionIndex)
if let inteitemSpacing = inteitemSpacing {
return inteitemSpacing
}
}
return self.minimumInteritemSpacing
}
func evaluatedSectionInsetForItem(at index: Int) ->UIEdgeInsets {
if let delegate = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout {
let insetForSection = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: index)
if let insetForSectionAt = insetForSection {
return insetForSectionAt
}
}
return self.sectionInset
}
}
| apache-2.0 | 97a0f79e4515a26f20b18ef85dcccee2 | 43.734694 | 145 | 0.637318 | 6.131469 | false | false | false | false |
gabrielrigon/OnboardingKit | Example/Athlee-Onboarding/Athlee-Onboarding/DataModel.swift | 1 | 4191 | //
// DataModel.swift
// Athlee-Onboarding
//
// Created by mac on 06/07/16.
// Copyright © 2016 Athlee. All rights reserved.
//
import UIKit
import OnboardingKit
public final class DataModel: NSObject, OnboardingViewDelegate, OnboardingViewDataSource {
public var didShow: ((Int) -> Void)?
public var willShow: ((Int) -> Void)?
public func numberOfPages() -> Int {
return 5
}
public func onboardingView(onboardingView: OnboardingView, configurationForPage page: Int) -> OnboardingConfiguration {
switch page {
case 0:
return OnboardingConfiguration(
image: UIImage(named: "PageHeartImage")!,
itemImage: UIImage(named: "ItemHeartIcon")!,
pageTitle: "PhotoFIT",
pageDescription: "A new kind of fittness tracking! \n\n100% free, because great health should be accessible to all!",
backgroundImage: UIImage(named: "BackgroundRed"),
topBackgroundImage: nil,
bottomBackgroundImage: UIImage(named: "WavesImage")
)
case 1:
return OnboardingConfiguration(
image: UIImage(named: "PageMetricsImage")!,
itemImage: UIImage(named: "ItemMetricsIcon")!,
pageTitle: "Body Metrics",
pageDescription: "Body metrics will never be the same! \n\nTrack bodyweight, body fat, and add a snap shot of your progress!",
backgroundImage: UIImage(named: "BackgroundBlue"),
topBackgroundImage: nil,
bottomBackgroundImage: UIImage(named: "WavesImage")
)
case 2:
return OnboardingConfiguration(
image: UIImage(named: "PageActivityImage")!,
itemImage: UIImage(named: "ItemActivityIcon")!,
pageTitle: "Activity",
pageDescription: "View activity collected by your fitness trackers and your other mobile apps! \n\nData has never been more beautiful or easier to understand!",
backgroundImage: UIImage(named: "BackgroundOrange"),
topBackgroundImage: nil,
bottomBackgroundImage: UIImage(named: "WavesImage")
)
case 3:
return OnboardingConfiguration(
image: UIImage(named: "PageNutritionImage")!,
itemImage: UIImage(named: "ItemNutritionIcon")!,
pageTitle: "Nutrition",
pageDescription: "Nutrition tracking can be difficult! \n\nContinue to use your favorite calorie tracking apps if you want, but check out your results here and make sure your macros are in check!",
backgroundImage: UIImage(named: "BackgroundGreen"),
topBackgroundImage: nil,
bottomBackgroundImage: UIImage(named: "WavesImage")
)
case 4:
return OnboardingConfiguration(
image: UIImage(named: "PageTimelapseImage")!,
itemImage: UIImage(named: "ItemTimelapseIcon")!,
pageTitle: "PhotoLAPSE",
pageDescription: "Your progress photos are being put to good use! \n\nThe photoLAPSE feature allows you to view your results over custom time periods!",
backgroundImage: UIImage(named: "BackgroundPurple"),
topBackgroundImage: nil,
bottomBackgroundImage: UIImage(named: "WavesImage")
)
default:
fatalError("Out of range!")
}
}
public func onboardingView(onboardingView: OnboardingView, configurePageView pageView: PageView, atPage page: Int) {
pageView.titleLabel.textColor = UIColor.whiteColor()
pageView.titleLabel.layer.shadowOpacity = 0.6
pageView.titleLabel.layer.shadowColor = UIColor.blackColor().CGColor
pageView.titleLabel.layer.shadowOffset = CGSize(width: 0, height: 1)
pageView.titleLabel.layer.shouldRasterize = true
pageView.titleLabel.layer.rasterizationScale = UIScreen.mainScreen().scale
if DeviceTarget.IS_IPHONE_4 {
pageView.titleLabel.font = UIFont.boldSystemFontOfSize(30)
pageView.descriptionLabel.font = UIFont.systemFontOfSize(15)
}
}
public func onboardingView(onboardingView: OnboardingView, didSelectPage page: Int) {
print("Did select pge \(page)")
didShow?(page)
}
public func onboardingView(onboardingView: OnboardingView, willSelectPage page: Int) {
print("Will select page \(page)")
willShow?(page)
}
} | mit | add12d907fe92dfc03a6fb562b69284c | 38.168224 | 205 | 0.68926 | 4.655556 | false | true | false | false |
scottrhoyt/Cider | Sources/Cider/Client/CiderClient.swift | 1 | 7734 | //
// CiderClient.swift
// Cider
//
// Created by Scott Hoyt on 8/4/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import Foundation
/// A client for submitting requests to the Apple Music API.
public struct CiderClient {
private let urlBuilder: UrlBuilder
private let fetcher: UrlFetcher
// MARK: URLFetcher
/**
Default `UrlFetcher`
A `URLSession` with the default `URLSessionConfiguration`
*/
public static var defaultURLFetcher: UrlFetcher {
return URLSession(configuration: URLSessionConfiguration.default)
}
// MARK: Initialization
init(urlBuilder: UrlBuilder, urlFetcher: UrlFetcher = CiderClient.defaultURLFetcher) {
self.urlBuilder = urlBuilder
self.fetcher = urlFetcher
}
/**
Initialize a `CiderClient`
- parameters:
- storefront: The `Storefront` to submit requests to.
- developerToken: The Apple Music developer token to use in requests.
- urlFetcher: The `UrlFetcher` to use for processing requests. Defaults to a `URLSession` with the default `URLSessionConfiguration`.
*/
public init(storefront: Storefront, developerToken: String, urlFetcher: UrlFetcher = CiderClient.defaultURLFetcher) {
let urlBuilder = CiderUrlBuilder(storefront: storefront, developerToken: developerToken)
self.init(urlBuilder: urlBuilder, urlFetcher: urlFetcher)
}
// MARK: Search
/**
Search the Apple Music catalog.
- parameters:
- term: The term to search for.
- limit: The amount of results to return.
- offset: The offset to use for paginating results.
- types: The `MediaType`s to limit the search to.
- completion: The completion handler to call with the results of the search.
*/
public func search(term: String, limit: Int? = nil, offset: Int? = nil, types: [MediaType]? = nil, completion: ((SearchResults?, Error?) -> Void)?) {
let request = urlBuilder.searchRequest(term: term, limit: limit, offset: offset, types: types)
fetch(request) { (results: ResponseRoot<SearchResults>?, error) in completion?(results?.results, error) }
}
/**
Get hints for search terms to use searching the Apple Music catalog.
- parameters:
- term: The term to search for.
- limit: The amount of results to return.
- types: The `MediaType`s to limit the search to.
- completion: The completion handler to call with the results of the search hints.
*/
public func searchHints(term: String, limit: Int? = nil, types: [MediaType]? = nil, completion: ((SearchHints?, Error?) -> Void)?) {
let request = urlBuilder.searchHintsRequest(term: term, limit: limit, types: types)
fetch(request) { (results: ResponseRoot<SearchHints>?, error) in completion?(results?.results, error) }
}
// MARK: Lookup
/**
Lookup an artist by id.
- parameters:
- id: The id of the artist to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func artist(id: String, include: [Include]? = nil, completion: ((Artist?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .artists, id: id, include: include)
fetch(request) { (results: ResponseRoot<Artist>?, error) in completion?(results?.data?.first, error) }
}
/**
Lookup an album by id.
- parameters:
- id: The id of the album to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func album(id: String, include: [Include]? = nil, completion: ((Album?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .albums, id: id, include: include)
fetch(request) { (results: ResponseRoot<Album>?, error) in completion?(results?.data?.first, error) }
}
/**
Lookup a song by id.
- parameters:
- id: The id of the song to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func song(id: String, include: [Include]? = nil, completion: ((Track?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .songs, id: id, include: include)
fetch(request) { (results: ResponseRoot<Track>?, error) in completion?(results?.data?.first, error) }
}
/**
Lookup a playlist by id.
- parameters:
- id: The id of the playlist to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func playlist(id: String, include: [Include]? = nil, completion: ((Playlist?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .playlists, id: id, include: include)
fetch(request) { (results: ResponseRoot<Playlist>?, error) in completion?(results?.data?.first, error) }
}
/**
Lookup a music video by id.
- parameters:
- id: The id of the music video to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func musicVideo(id: String, include: [Include]? = nil, completion: ((MusicVideo?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .musicVideos, id: id, include: include)
fetch(request) { (results: ResponseRoot<MusicVideo>?, error) in completion?(results?.data?.first, error) }
}
/**
Lookup a curator by id.
- parameters:
- id: The id of the curator to lookup.
- include: The relationships to include in the lookup.
- completion: The handler to call with the results.
*/
public func curator(id: String, include: [Include]? = nil, completion: ((Curator?, Error?) -> Void)?) {
let request = urlBuilder.fetchRequest(mediaType: .curators, id: id, include: include)
fetch(request) { (results: ResponseRoot<Curator>?, error) in completion?(results?.data?.first, error) }
}
// MARK: Relationships
/**
Get the related resources for a `Relationship`.
- parameters:
- related: The relationship to get.
- limit: The maximum amount of results to return.
- offset: The offset to use for pagination.
- completion: The handler to call with the results.
*/
public func get<T>(related: Relationship<T>, limit: Int? = nil, offset: Int? = nil, completion: (([T]?, Error?) -> Void)?) {
let path = related.href
let request = urlBuilder.relationshipRequest(path: path, limit: limit, offset: offset)
fetch(request) { (results: ResponseRoot<T>?, error) in completion?(results?.data, error) }
}
// MARK: Helpers
private func fetch<T>(_ request: URLRequest, completion: ((ResponseRoot<T>?, Error?) -> Void)?) {
fetcher.fetch(request: request) { (data, error) in
guard let data = data else {
completion?(nil, error)
return
}
do {
let decoder = JSONDecoder()
let results = try decoder.decode(ResponseRoot<T>.self, from: data)
// If we have any errors, callback with the first error. Otherwise callback with the results
if let error = results.errors?.first {
completion?(nil, error)
} else {
completion?(results, nil)
}
} catch {
completion?(nil, error)
}
}
}
}
| mit | 08a9eeb61b912c6f60631ac2a0a955ac | 37.859296 | 153 | 0.629251 | 4.312883 | false | false | false | false |
bestwpw/RxSwift | RxSwift/Observables/Implementations/SubscribeOn.swift | 2 | 1793 | //
// SubscribeOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SubscribeOnSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = SubscribeOn<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
observer?.on(event)
if event.isStopEvent {
self.dispose()
}
}
func run() -> Disposable {
let disposeEverything = SerialDisposable()
let cancelSchedule = SingleAssignmentDisposable()
disposeEverything.disposable = cancelSchedule
cancelSchedule.disposable = parent.scheduler.schedule(()) { (_) -> Disposable in
let subscription = self.parent.source.subscribeSafe(self)
disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription)
return NopDisposable.instance
}
return disposeEverything
}
}
class SubscribeOn<Element> : Producer<Element> {
let source: Observable<Element>
let scheduler: ImmediateScheduler
init(source: Observable<Element>, scheduler: ImmediateScheduler) {
self.source = source
self.scheduler = scheduler
}
override func run<O : ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | mit | a87c90ad73a83767eee17f8373413f8d | 28.9 | 140 | 0.640825 | 4.743386 | false | false | false | false |
WSUCSClub/upac-ios | UPAC/RaffleManager.swift | 1 | 4117 | //
// RaffleManager.swift
// UPAC
//
// Created by Marquez, Richard A on 10/25/14.
// Copyright (c) 2014 wsu-cs-club. All rights reserved.
//
import Foundation
import CoreData
let raffleMgr = RaffleManager()
class Raffle: NSManagedObject {
@NSManaged var id: String
@NSManaged var date: NSDate
@NSManaged var endDate: NSDate
@NSManaged var localEntry: String
var timeRemaining: String = { return "endDate - date" }() //TODO: it
func addEntry() -> String {
var code = generateCode()
// Save to Core Data
localEntry = code
coreDataHelper.saveData()
// Push to Parse
var query = PFQuery(className: "Raffle")
query.whereKey("eventId", equalTo: id)
query.getFirstObjectInBackgroundWithBlock{ event, error in
if error == nil {
event.addObject(self.localEntry, forKey: "entries")
event.saveInBackgroundWithBlock{ void in }
} else {
println(error)
}
}
return code
}
private func generateCode() -> String {
let date = String(Int(NSDate().timeIntervalSince1970))
let hash = date.md5() as NSString
let code = hash.substringWithRange(NSRange(location: 0, length: 5)).uppercaseString
return code
}
}
class RaffleManager {
var list = [Raffle]()
init() {
getRaffles()
}
func fetchStored() -> [Raffle] {
let fetchRequest = NSFetchRequest(entityName: "Raffle")
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [ sortDescriptor ]
return coreDataHelper.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [Raffle]!
}
func getRaffles() {
list = fetchStored()
var query = PFQuery(className: "Raffle")
query.findObjectsInBackgroundWithBlock { parseList, error in
if let error = error {
println("Could not retrieve raffles from Parse: \(error)")
} else {
// Delete local raffle if it no longer exists in Parse
for localRaffle in self.list {
var stillExists = false
for parseRaffle in parseList {
if localRaffle.id == parseRaffle["eventId"] as! String {
stillExists = true
}
}
if !stillExists {
coreDataHelper.managedObjectContext!.deleteObject(localRaffle)
coreDataHelper.saveData()
self.list = self.fetchStored()
}
}
// Only add to local storage if does not already exist
for parseRaffle in parseList {
if self.getForID(parseRaffle["eventId"] as! String) == nil {
// Add to Core Data
let newRaffle = NSEntityDescription.insertNewObjectForEntityForName("Raffle", inManagedObjectContext: coreDataHelper.managedObjectContext!) as! Raffle
newRaffle.id = parseRaffle["eventId"] as! String
newRaffle.date = parseRaffle["date"] as! NSDate
newRaffle.endDate = parseRaffle["endDate"] as! NSDate
newRaffle.localEntry = ""
self.list.append(newRaffle)
}
}
coreDataHelper.saveData()
__eventsTableView!.reloadData()
}
}
}
func getForID(id: String) -> Raffle? {
var result: Raffle? = nil
for r in self.list {
if (r).id == id {
result = r
}
}
return result
}
} | gpl-3.0 | f6df4b6485d85f7281c08ceec21aeb7a | 30.435115 | 174 | 0.510323 | 5.114286 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Filters.playground/Pages/High Pass Butterworth Filter.xcplaygroundpage/Contents.swift | 1 | 1478 | //: ## High Pass Butterworth Filter
//: A high-pass filter takes an audio signal as an input, and cuts out the
//: low-frequency components of the audio signal, allowing for the higher frequency
//: components to "pass through" the filter.
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var filter = AKHighPassButterworthFilter(player)
filter.cutoffFrequency = 6_900 // Hz
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("High Pass Butterworth Filter")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop") { button in
filter.isStarted ? filter.stop() : filter.play()
button.title = filter.isStarted ? "Stop" : "Start"
})
addView(AKSlider(property: "Cutoff Frequency",
value: filter.cutoffFrequency,
range: 20 ... 22_050,
taper: 5,
format: "%0.1f Hz"
) { sliderValue in
filter.cutoffFrequency = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | eb9ded3464c794166440533dec8d6c33 | 29.163265 | 96 | 0.665765 | 4.692063 | false | false | false | false |
goldenplan/Pattern-on-Swift | Bridge/Bridge/MyView.swift | 1 | 3035 | //
// MyView.swift
// Bridge
//
// Created by Snake on 24/07/2017.
// Copyright © 2017 Snake. All rights reserved.
//
import UIKit
class MyView: UIView {
var points: [CGPoint] = []
var nibName = "MyView"
var view = UIView()
let shapeLayer = CAShapeLayer()
var lineArray: [Int] = []
init(frame: CGRect, points: [CGPoint], lineArray: [Int]) {
super.init(frame: frame)
self.points = points
self.lineArray = lineArray
setup(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
//если меняются размеры, то вьюха будет себя перерисовывать
contentMode = .redraw
}
func setup(frame: CGRect){
view = loadFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
draw(view: view)
}
func loadFromNib() -> UIView{
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
func draw(view: UIView){
shapeLayer.frame = self.view.frame
shapeLayer.backgroundColor = UIColor.green.withAlphaComponent(0.7).cgColor
shapeLayer.strokeColor = UIColor.black.withAlphaComponent(0.7).cgColor
shapeLayer.fillColor = UIColor.magenta.cgColor
shapeLayer.lineDashPattern = lineArray as [NSNumber]
shapeLayer.lineWidth = 3
let startPoint = convertedPoint(point: points.first!)
let endPoint = convertedPoint(point: points.last!)
let path = CGMutablePath()
path.move(to: startPoint)
for point in points[1...points.count - 1]{
path.addLine(to: convertedPoint(point: point))
}
path.addLine(to: endPoint)
path.closeSubpath()
shapeLayer.path = path
let lineDashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
lineDashAnimation.fromValue = 0
lineDashAnimation.toValue = shapeLayer.lineDashPattern?.reduce(0) { $0 + $1.intValue }
lineDashAnimation.duration = 0.5
lineDashAnimation.repeatCount = Float.greatestFiniteMagnitude
shapeLayer.add(lineDashAnimation, forKey: nil)
view.layer.addSublayer(shapeLayer)
}
func convertedPoint(point: CGPoint) -> CGPoint{
let center = CGPoint(x: bounds.midX,
y: bounds.midY)
return CGPoint(x: center.x - point.x,
y: center.y - point.y)
}
}
| mit | 2cf3732c3a9efebf000b45dde252da76 | 23.875 | 94 | 0.560469 | 4.745628 | false | false | false | false |
mikaelm1/Teach-Me-Fast | Teach Me Fast/PostFeedVC.swift | 1 | 10836 | //
// MathVC.swift
// Teach Me Fast
//
// Created by Mikael Mukhsikaroyan on 6/6/16.
// Copyright © 2016 MSquaredmm. All rights reserved.
//
import UIKit
import Firebase
import GoogleMobileAds
class PostFeedVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var menuButton: UIBarButtonItem!
static var imageCache = Cache<AnyObject, AnyObject>()
var categorySelected: String?
var posts = [LessonPost]()
var selectedPost: LessonPost?
var userLoggedIn = false
var currentUser: User?
var animatedCells = Set<IndexPath>()
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barStyle = .black
print("POSTFEEDVC VIewDidLoad")
if categorySelected == nil {
categorySelected = Category.recent.rawValue
}
if UserDefaults.standard().value(forKey: Constants.key_uid) != nil {
userLoggedIn = true
getCurrentUserInfo()
} else {
userLoggedIn = false
}
tableView.dataSource = self
tableView.delegate = self
if revealViewController() != nil {
menuButton.target = revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
view.addGestureRecognizer(revealViewController().panGestureRecognizer())
} else {
print("RVC is nil")
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
downloadPosts()
print("Selected Category: \(categorySelected)")
print("Current User: \(currentUser)")
title = categorySelected
}
deinit {
print("DEINIT")
FirebaseClient.sharedInstance.refPosts.removeAllObservers()
FirebaseClient.sharedInstance.refUsers.removeAllObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("POSTFEED WILL DISAPPEAR")
//FirebaseClient.sharedInstance.REF_POSTS.removeAllObservers()
//FirebaseClient.sharedInstance.REF_USERS.removeAllObservers()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .lightContent
}
// MARK: Helper methods
func getCurrentUserInfo() {
//print("UID: \(FIRAuth.auth()?.currentUser?.uid)")
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
print("Didn't get uid")
return
}
_ = FirebaseClient.sharedInstance.refUsers.observeSingleEvent(of: .value, with: { snapshot in
guard let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] else {
print("Didn't get back snapshots")
return
}
for snap in snapshots {
guard let userDict = snap.value as? [String: AnyObject] else {
print("Didn't get the user dict")
return
}
if uid == snap.key {
print("Got matching user")
self.currentUser = User(userDict: userDict)
//print("User Dict: \(userDict)")
}
}
})
}
func downloadByRecent() {
FirebaseClient.sharedInstance.refPosts.queryOrdered(byChild: "timestamp").observe(.value, with: { (snapshot) in
print("SNAPSHOT: \(snapshot)")
guard let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] else {
print("Didn't get back snapshots")
return
}
self.posts = []
for snap in snapshots.reversed() {
print("SNAP: \(snap)")
guard let postDict = snap.value as? [String: AnyObject] else {
print("Didn't get the post dict")
return
}
let key = snap.key
//print("Post key: \(key)")
let post = LessonPost(postKey: key, dictionary: postDict)
self.posts.append(post)
}
self.tableView.reloadData()
})
}
func downloadByCategory() {
FirebaseClient.sharedInstance.refPosts.observe(.value, with: { (snapshot) in
//print(snapshot)
print("Post observer fired")
guard let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] else {
print("Didn't get back snapshots")
return
}
self.posts = []
//print("SNapshots: \(snapshots)")
for snap in snapshots {
//print("SNAP: \(snap)")
guard let postDict = snap.value as? [String: AnyObject] else {
print("Didn't get the post dict")
return
}
if self.categorySelected == "My Posts" {
// TODO: Handle this
if self.currentUser?.posts == nil {
print("NO POSTS FOR THIS USER")
} else {
for k in (self.currentUser?.posts?.keys)! {
if snap.key == k {
let post = LessonPost(postKey: snap.key, dictionary: postDict)
self.posts.append(post)
}
}
}
} else {
if let category = postDict["category"] as? String {
//print("Category: \(category)")
//print("Current Category: \(self.categorySelected)")
if self.categorySelected == category {
let key = snap.key
//print("Post key: \(key)")
let post = LessonPost(postKey: key, dictionary: postDict)
self.posts.append(post)
}
}
}
}
self.tableView.reloadData()
})
}
func downloadPosts() {
print("Download posts")
if categorySelected == Category.recent.rawValue {
print("Get the recent posts")
downloadByRecent()
} else {
downloadByCategory()
}
}
// MARK: Action
@IBAction func postNewButtonPressed(_ sender: UIButton) {
if userLoggedIn {
print("User is logged in")
performSegue(withIdentifier: Constants.segueToCreateNewPost, sender: nil)
} else {
print("User not logged in")
_ = SweetAlert().showAlert("Error", subTitle: "Only the initiated can contribute to the knowledge base.", style: AlertStyle.error, buttonTitle: "Login", buttonColor: Constants.lightBlueColor, otherButtonTitle: "Later", action: { (isOtherButton) in
if isOtherButton {
//Login button tapped
self.gotoLogin()
} else {
print("Later pressed")
}
})
}
}
// MARK: Segue helper
func gotoLogin() {
let vc = storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
present(vc, animated: true, completion: nil)
}
// MARK: Segue
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constants.segueToCreateNewPost {
let vc = segue.destinationViewController as! CreateNewPostVC
vc.currentUser = self.currentUser!
navigationItem.backBarButtonItem?.title = "Cancel"
} else if segue.identifier == Constants.segueToPostDetail {
navigationItem.backBarButtonItem?.title = " "
let vc = segue.destinationViewController as! PostDetailController
vc.post = selectedPost!
if let url = selectedPost!.postImageUrl {
if let img = PostFeedVC.imageCache.object(forKey: url) as? Data {
vc.postImageData = img
}
}
if let user = currentUser {
vc.currentUser = user
}
}
}
func gotoPostDetailVC(post: LessonPost) {
let vc = storyboard?.instantiateViewController(withIdentifier: "PostDetailVC") as! PostDetailVC
vc.post = post
if let user = currentUser {
vc.currentUser = user
}
navigationController?.pushViewController(vc, animated: true)
}
}
extension PostFeedVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = posts[(indexPath as NSIndexPath).row]
var img: Data?
if let url = post.profilImageeUrl {
img = PostFeedVC.imageCache.object(forKey: url) as? Data
}
cell.configureCell(posts[(indexPath as NSIndexPath).row], image: img, currentUser: currentUser)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if !animatedCells.contains(indexPath) {
animatedCells.insert(indexPath)
// initial state
cell.alpha = 0
let transform = CATransform3DTranslate(CATransform3DIdentity, -500, 20, 0)
cell.layer.transform = transform
UIView.animate(withDuration: 0.7, delay: 0, options: .curveEaseOut, animations: {
cell.alpha = 1
cell.layer.transform = CATransform3DIdentity
}, completion: { (finished) in
// do something
})
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = posts[(indexPath as NSIndexPath).row]
selectedPost = post
//performSegue(withIdentifier: Constants.segueToPostDetail, sender: nil)
gotoPostDetailVC(post: post)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
}
| mit | 8df8f0bb3dea698c04f6331fec548c0a | 34.877483 | 259 | 0.550162 | 5.366518 | false | false | false | false |
Neft-io/neft | packages/neft-runtime-ios/Neft/Reader.swift | 1 | 1605 | import UIKit
class Reader {
private var actions = NSArray()
private var booleans = NSArray()
private var integers = NSArray()
private var floats = NSArray()
private var strings = NSArray()
private var actionsIndex = 0
private var booleansIndex = 0
private var integersIndex = 0
private var floatsIndex = 0
private var stringsIndex = 0
func reload(_ body: AnyObject){
let dict = body as! NSDictionary
self.actions = dict.object(forKey: "actions") as! NSArray
self.booleans = dict.object(forKey: "booleans") as! NSArray
self.integers = dict.object(forKey: "integers") as! NSArray
self.floats = dict.object(forKey: "floats") as! NSArray
self.strings = dict.object(forKey: "strings") as! NSArray
actionsIndex = 0
booleansIndex = 0
integersIndex = 0
floatsIndex = 0
stringsIndex = 0
}
func getAction() -> InAction? {
if (actionsIndex >= actions.count){
return nil
}
actionsIndex += 1
return InAction(rawValue: actions[actionsIndex - 1] as! Int)
}
func getBoolean() -> Bool {
booleansIndex += 1
return booleans[booleansIndex - 1] as! Bool
}
func getInteger() -> Int {
integersIndex += 1
return integers[integersIndex - 1] as! Int
}
func getFloat() -> CGFloat {
floatsIndex += 1
return floats[floatsIndex - 1] as! CGFloat
}
func getString() -> String {
stringsIndex += 1
return strings[stringsIndex - 1] as! String
}
}
| apache-2.0 | 3b8660ba465044e97ebd1fc60036c67a | 26.672414 | 68 | 0.601869 | 4.421488 | false | false | false | false |
24/ios-o2o-c | gxc/OpenSource/ExSwift/ExSwiftTest/ExSwiftArrayTests.swift | 1 | 13273 | ////
//// ExtensionsTests.swift
//// ExtensionsTests
////
//// Created by pNre on 03/06/14.
//// Copyright (c) 2014 pNre. All rights reserved.
////
//
//import XCTest
//
//class ExtensionsArrayTests: XCTestCase {
//
// var array: [Int] = []
// var people: [(name: String, id: String)] = []
//
// override func setUp() {
// super.setUp()
// array = [1, 2, 3, 4, 5]
//
// let bob = (name: "bob", id: "P1")
// let frank = (name: "frank", id: "P2")
// let ian = (name: "ian", id: "P3")
//
// people = [bob, frank, ian]
// }
//
// func testSortBy () {
// var sourceArray = [2, 3, 6, 5]
// var sortedArray = sourceArray.sortBy {$0 < $1}
//
// // check that the source array as not been mutated
// XCTAssertEqual(sourceArray, [2, 3, 6, 5])
// // check that the destination has been sorted
// XCTAssertEqual(sortedArray, [2, 3, 5, 6])
// }
//
// func testReject () {
// var odd = array.reject({
// return $0 % 2 == 0
// })
//
// XCTAssertEqual(odd, [1, 3, 5])
// }
//
// func testToDictionary () {
// var dictionary = people.toDictionary { $0.id }
//
// XCTAssertTrue(Array(dictionary.keys).difference(["P3", "P1", "P2"]).isEmpty)
//
// XCTAssertEqual(dictionary["P1"]!.name, "bob")
// XCTAssertEqual(dictionary["P2"]!.name, "frank")
// XCTAssertEqual(dictionary["P3"]!.name, "ian")
// }
//
// func testEach() {
// var result = Array<Int>()
//
// array.each({
// result.append($0)
// })
//
// XCTAssertEqual(result, array)
//
// result.removeAll(keepCapacity: true)
//
// array.each({
// (index: Int, item: Int) in
// result.append(index)
// })
//
// XCTAssertEqual(result, array.map({ return $0 - 1 }) as Array<Int>)
// }
//
// func testEachRight() {
// var result = [Int]()
//
// array.eachRight { (index, value) -> () in
// result += [value]
// }
//
// XCTAssertEqual(result.first!, array.last!)
// XCTAssertEqual(result.last!, array.first!)
// }
//
// func testRange() {
// var range = Array<Int>.range(0..<2)
// XCTAssertEqual(range, [0, 1])
//
// range = Array<Int>.range(0...2)
// XCTAssertEqual(range, [0, 1, 2])
// }
//
// func testContains() {
// XCTAssertFalse(array.contains("A"))
// XCTAssertFalse(array.contains(6))
// XCTAssertTrue(array.contains(5))
// XCTAssertTrue(array.contains(3, 4) )
// }
//
// func testDifference() {
// var diff = array.difference([3, 4])
// XCTAssertEqual(diff, [1, 2, 5])
//
// diff = array - [3, 4]
// XCTAssertEqual(diff, [1, 2, 5])
//
// diff = array.difference([3], [5])
// XCTAssertEqual(diff, [1, 2, 4])
// }
//
// func testIndexOf() {
// // Equatable parameter
// XCTAssertEqual(0, array.indexOf(1)!)
// XCTAssertEqual(3, array.indexOf(4)!)
// XCTAssertNil(array.indexOf(6))
//
// // Matching block
// XCTAssertEqual(1, array.indexOf { item in
// return item % 2 == 0
// }!)
// XCTAssertNil(array.indexOf { item in
// return item > 10
// })
// }
//
// func testIntersection() {
// var intersection = array.intersection([Int]())
// XCTAssertEqual(intersection, [Int]())
//
// intersection = array.intersection([1])
// XCTAssertEqual(intersection, [1])
//
// intersection = array.intersection([1, 2], [1, 2], [1, 3])
// XCTAssertEqual(intersection, [1])
// }
//
// func testUnion() {
// var union = array.union([1])
// XCTAssertEqual(union, array)
//
// union = array.union(Array<Int>())
// XCTAssertEqual(union, array)
//
// union = array.union([6])
// XCTAssertEqual(union, [1, 2, 3, 4, 5, 6])
// }
//
// func testZip() {
// var zip1 = [1, 2].zip(["A", "B"])
//
// var a = zip1[0][0] as Int
// var b = zip1[0][1] as String
//
// XCTAssertEqual(1, a)
// XCTAssertEqual("A", b)
//
// a = zip1[1][0] as Int
// b = zip1[1][1] as String
//
// XCTAssertEqual(2, a)
// XCTAssertEqual("B", b)
// }
//
// func testPartition() {
// XCTAssertEqual(array.partition(2), [[1, 2], [3, 4]])
// XCTAssertEqual(array.partition(2, step: 1), [[1, 2], [2, 3], [3, 4], [4, 5]])
// XCTAssertEqual(array.partition(2, step: 1, pad: nil), [[1, 2], [2, 3], [3, 4], [4, 5], [5]])
// XCTAssertEqual(array.partition(4, step: 1, pad: nil), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5]])
// XCTAssertEqual(array.partition(2, step: 1, pad: [6,7,8]), [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
// XCTAssertEqual(array.partition(4, step: 3, pad: [6]), [[1, 2, 3, 4], [4, 5, 6]])
// XCTAssertEqual(array.partition(2, pad: [6]), [[1, 2], [3, 4], [5, 6]])
// XCTAssertEqual([1, 2, 3, 4, 5, 6].partition(2, step: 4), [[1, 2], [5, 6]])
// XCTAssertEqual(array.partition(10), [[]])
// }
//
// func testPartitionAll() {
// XCTAssertEqual(array.partitionAll(2, step: 1), [[1, 2], [2, 3], [3, 4], [4, 5], [5]])
// XCTAssertEqual(array.partitionAll(2), [[1, 2], [3, 4], [5]])
// XCTAssertEqual(array.partitionAll(4, step: 1), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]])
// }
//
// func testPartitionBy() {
// XCTAssertEqual(array.partitionBy { $0 > 10 }, [[1, 2, 3, 4, 5]])
// XCTAssertEqual([1, 2, 4, 3, 5, 6].partitionBy { $0 % 2 == 0 }, [[1], [2, 4], [3, 5], [6]])
// XCTAssertEqual([1, 7, 3, 6, 10, 12].partitionBy { $0 % 3 }, [[1, 7], [3, 6], [10], [12]])
// }
//
// func testSample() {
// XCTAssertEqual(1, array.sample().count)
// XCTAssertEqual(2, array.sample(size: 2).count)
// XCTAssertEqual(array.sample(size: array.count), array)
// }
//
// func testSubscript() {
// XCTAssertEqual(array[0..<0], [])
// XCTAssertEqual(array[0..<1], [1])
// XCTAssertEqual(array[0..<2], [1, 2])
// XCTAssertEqual(array[0...2], [1, 2, 3])
// XCTAssertEqual(array[0, 1, 2], [1, 2, 3])
// }
//
// func testShuffled() {
// let shuffled = array.shuffled()
// XCTAssertEqual(shuffled.difference(array), [])
// XCTAssertNotEqual(shuffled, array)
// }
//
// func testShuffle() {
// var toShuffle = array
// toShuffle.shuffle()
// XCTAssertEqual(toShuffle.difference(array), [])
// }
//
// func testMax() {
// XCTAssertEqual(5, array.max() as Int)
// }
//
// func testMin() {
// XCTAssertEqual(1, array.min() as Int)
// }
//
// func testTake() {
// XCTAssertEqual(array.take(3), [1, 2, 3])
// XCTAssertEqual(array.take(0), [])
// }
//
// func testTakeWhile() {
// XCTAssertEqual(array.takeWhile { $0 < 3 }, [1 , 2])
// XCTAssertEqual([1, 2, 3, 2, 1].takeWhile { $0 < 3 }, [1, 2])
// XCTAssertEqual(array.takeWhile { $0.isEven() }, [])
// }
//
// func testSkip() {
// XCTAssertEqual(array.skip(3), [4, 5])
// XCTAssertEqual(array.skip(0), array)
// }
//
// func testSkipWhile() {
// XCTAssertEqual(array.skipWhile { $0 < 3 }, [3, 4, 5])
// XCTAssertEqual([1, 2, 3, 2, 1].skipWhile { $0 < 3 }, [3, 2, 1])
// XCTAssertEqual(array.skipWhile { $0.isEven() }, array)
// }
//
// func testTail () {
// XCTAssertEqual(array.tail(3), [3, 4, 5])
// XCTAssertEqual(array.tail(0), [])
// }
//
// func testPop() {
// XCTAssertEqual(5, array.pop())
// XCTAssertEqual(array, [1, 2, 3, 4])
// }
//
// func testPush() {
// array.push(6)
// XCTAssertEqual(6, array.last!)
// }
//
// func testShift() {
// XCTAssertEqual(1, array.shift())
// XCTAssertEqual(array, [2, 3, 4, 5])
// }
//
// func testUnshift() {
// array.unshift(0)
// XCTAssertEqual(0, array.first!)
// }
//
// func testRemove() {
// array.append(array.last!)
// array.remove(array.last!)
//
// XCTAssertEqual((array - 1), [2, 3, 4])
// XCTAssertEqual(array, [1, 2, 3, 4])
// }
//
// func testUnique() {
// let arr = [1, 1, 1, 2, 3]
// XCTAssertEqual(arr.unique() as Array<Int>, [1, 2, 3])
// }
//
// func testGroupBy() {
// let group = array.groupBy(groupingFunction: {
// (value: Int) -> Bool in
// return value > 3
// })
//
// XCTAssertEqual(Array(group.keys), [false, true])
// XCTAssertEqual(Array(group[true]!), [4, 5])
// XCTAssertEqual(Array(group[false]!), [1, 2, 3])
// }
//
// func testCountBy() {
// let group = array.countBy(groupingFunction: {
// (value: Int) -> String in
// return value % 2 == 0 ? "even" : "odd"
// })
//
// XCTAssertEqual(group, ["even": 2, "odd": 3])
// }
//
// func testReduceRight () {
// let list = [[1, 1], [2, 3], [4, 5]]
//
// let flat = list.reduceRight([Int](), { return $0 + $1 })
//
// XCTAssertEqual(flat, [4, 5, 2, 3, 1, 1])
//
// XCTAssertEqual(16, flat.reduce(+)!)
//
// let strings: [String] = ["A", "B", "C"]
//
// if let reduced = strings.reduceRight(+) {
// XCTAssertEqual(reduced, "CBA")
// } else {
// XCTFail("Error right-reducing an array of String")
// }
// }
//
// func testImplode () {
// let array = ["A", "B", "C"]
//
// var imploded = array.implode("A")
// XCTAssertEqual(imploded!, "AABAC")
//
// imploded = array * ","
// XCTAssertEqual(imploded!, "A,B,C")
// }
//
// func testAt () {
// XCTAssertEqual(array.at(0, 2), [1, 3])
// XCTAssertEqual(array[0, 2, 1], [1, 3, 2])
// }
//
// func testFlatten () {
// let array = [5, [6, [7]], 8]
// XCTAssertEqual(array.flatten() as [Int], [5, 6, 7, 8])
// XCTAssertEqual(array.flattenAny() as [Int], [5, 6, 7, 8])
// }
//
// func testGet () {
// XCTAssertEqual(1, array.get(0)!)
// XCTAssertEqual(array.get(-1)!, array.last!)
// XCTAssertEqual(array.get(array.count)!, array.first!)
// }
//
// func testDuplicationOperator () {
// XCTAssertEqual([1] * 3, [1, 1, 1])
// }
//
// func testLastIndexOf () {
// let array = [5, 1, 2, 3, 2, 1]
//
// XCTAssertEqual(array.count - 2, array.lastIndexOf(2)!)
// XCTAssertEqual(array.count - 1, array.lastIndexOf(1)!)
// XCTAssertEqual(0, array.lastIndexOf(5)!)
//
// XCTAssertNil(array.lastIndexOf(20))
// }
//
// func testInsert () {
// array.insert([0, 9], atIndex: 2)
// XCTAssertEqual(array, [1, 2, 0, 9, 3, 4, 5])
//
// // Out of bounds indexes
// array.insert([10], atIndex: 10)
// XCTAssertEqual(array, [1, 2, 0, 9, 3, 4, 5, 10])
//
// array.insert([-2], atIndex: -1)
// XCTAssertEqual(array, [-2, 1, 2, 0, 9, 3, 4, 5, 10])
// }
//
// func testTakeFirst() {
// XCTAssertEqual(2, array.takeFirst { $0 % 2 == 0 }!)
// XCTAssertNil(array.takeFirst { $0 > 10 })
// }
//
// func testCountWhere() {
// XCTAssertEqual(2, array.countWhere { $0 % 2 == 0 })
// }
//
// func testMapFilter() {
// let m = array.mapFilter { value -> Int? in
// if value > 3 {
// return nil
// }
//
// return value + 1
// }
//
// XCTAssertEqual(m, [2, 3, 4])
// }
//
// func testSubscriptConflicts() {
// let array1 = ["zero", "one", "two", "three"][rangeAsArray: 1...3]
// let array2 = ["zero", "one", "two", "three"][rangeAsArray: 1..<3]
// }
//
// func testMinBy() {
// var minValue: Int?
// minValue = array.minBy({ -$0 })
// XCTAssertEqual(minValue!, 5)
// minValue = array.minBy({ $0 % 4 })
// XCTAssertEqual(minValue!, 4)
// minValue = array.minBy({ $0 })
// XCTAssertEqual(minValue!, 1)
// minValue = array.minBy({ $0 % 2 })
// XCTAssertTrue(minValue! == 2 || minValue! == 4) // it's a tie
// }
//
// func testMaxBy() {
// var maxValue: Int?
// maxValue = array.maxBy({ -$0 })
// XCTAssertEqual(maxValue!, 1)
// maxValue = array.maxBy({ $0 % 4 })
// XCTAssertEqual(maxValue!, 3)
// maxValue = array.maxBy({ $0 })
// XCTAssertEqual(maxValue!, 5)
// maxValue = array.maxBy({ $0 % 3 })
// XCTAssertTrue(maxValue! == 2 || maxValue! == 5) // it's a tie
// }
//
// func testUniqueBy() {
// XCTAssertEqual(array.uniqueBy({$0}), array)
// XCTAssertEqual(array.uniqueBy({$0 % 2}), [1, 2])
// XCTAssertEqual(array.uniqueBy({$0 % 3}), [1, 2, 3])
// XCTAssertEqual(array.uniqueBy({$0 < 3}), [1, 3])
// }
//}
| mit | 9f1d4767cf31cfc300d5685b74111866 | 29.939394 | 110 | 0.480901 | 3.115728 | false | true | false | false |
TheNounProject/CollectionView | Example/Example/UI/GridCell.swift | 1 | 3162 | //
// GridCell.swift
// Example
//
// Created by Wes Byrne on 1/28/17.
// Copyright © 2017 Noun Project. All rights reserved.
//
import Foundation
import CollectionView
class GridCell: CollectionViewPreviewCell {
@IBOutlet weak var badgeLabel: NSTextField!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var detailLabel: NSTextField!
override func awakeFromNib() {
super.awakeFromNib()
self.useMask = false
// self.badgeLabel.isHidden = true
// self.titleLabel.isHidden = true
// self.detailLabel.isHidden = true
}
override var wantsUpdateLayer: Bool { return true }
override func prepareForReuse() {
super.prepareForReuse()
self.badgeLabel.unbind(NSBindingName(rawValue: "value"))
self.titleLabel.unbind(NSBindingName(rawValue: "value"))
}
var child: Child?
func setup(with child: Child) {
self.child = child
if !self.reused {
self.layer?.cornerRadius = 3
}
self.badgeLabel.stringValue = "\(child.displayOrder)"
self.titleLabel.stringValue = child.name
self.detailLabel.stringValue = ""
self.badgeLabel.bind(NSBindingName(rawValue: "value"), to: child, withKeyPath: "displayOrder", options: nil)
self.titleLabel.bind(NSBindingName(rawValue: "value"), to: child, withKeyPath: "name", options: nil)
}
override class var defaultReuseIdentifier: String {
return "GridCell"
}
override class func register(in collectionView: CollectionView) {
collectionView.register(nib: NSNib(nibNamed: "GridCell", bundle: nil)!,
forCellWithReuseIdentifier: self.defaultReuseIdentifier)
}
override var description: String {
return "GridCell: \(child?.description ?? "nil")"
}
static let rBG = NSColor(white: 0.98, alpha: 1)
static let hBG = NSColor(white: 0.95, alpha: 1)
var bgColor = GridCell.rBG
override func viewWillMove(toSuperview newSuperview: NSView?) {
super.viewWillMove(toSuperview: newSuperview)
self.layer?.borderColor = NSColor(white: 0.9, alpha: 1).cgColor
}
// MARK: - Selection & Highlighting
/*-------------------------------------------------------------------------------*/
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.backgroundColor = GridCell.hBG
self.layer?.borderWidth = 5
}
else {
self.layer?.borderWidth = 0
self.backgroundColor = self.highlighted
? GridCell.hBG
: bgColor
}
self.needsDisplay = true
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
guard !self.selected else { return }
self.backgroundColor = highlighted
? GridCell.hBG
: bgColor
self.needsDisplay = true
}
}
| mit | 04ce1b5323370ba220634a5dbdba39b1 | 31.255102 | 116 | 0.601708 | 4.855607 | false | false | false | false |
floschliep/FLOPageViewController | Sample App/ViewController.swift | 1 | 2134 | //
// ViewController.swift
// FLOPageViewController
//
// Created by Florian Schliep on 19.01.16.
// Copyright © 2016 Florian Schliep. All rights reserved.
//
import Cocoa
import FLOPageViewController
class ViewController: NSViewController {
fileprivate weak var pageViewController: PageViewController?
// MARK: - NSViewController
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let pageViewController = segue.destinationController as? PageViewController else { return }
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
pageViewController.loadViewControllers(["1", "2", "3"], from: storyboard)
self.pageViewController = pageViewController
}
// MARK: - Page View Controller Settings
@IBAction func didChangePageControlState(_ sender: NSButton) {
self.pageViewController?.showPageControl = (sender.state == .on)
}
@IBAction func didChangeArrowControlState(_ sender: NSButton) {
self.pageViewController?.showArrowControls = (sender.state == .on)
}
@IBAction func didChangePageControlMouseOverState(_ sender: NSButton) {
self.pageViewController?.pageControlRequiresMouseOver = (sender.state == .on)
}
@IBAction func didChangeArrowControlsMouseOverState(_ sender: NSButton) {
self.pageViewController?.arrowControlsRequireMouseOver = (sender.state == .on)
}
@IBAction func didChangeOverlayState(_ sender: NSButton) {
self.pageViewController?.overlayControls = (sender.state == .on)
}
@IBAction func didSelectTintColor(_ sender: NSColorWell) {
self.pageViewController?.tintColor = sender.color
}
@IBAction func didChangeCircleIndicatorState(_ sender: NSButton) {
self.pageViewController?.pageIndicatorStyle = (sender.state == .on) ? .circle : .dot
}
@IBAction func didSelectBackgroundColor(_ sender: NSColorWell) {
self.pageViewController?.backgroundColor = sender.color
}
}
| mit | 1658b51fb6fb09585ad8922e227c887f | 33.967213 | 105 | 0.692452 | 4.903448 | false | false | false | false |
con-beo-vang/Spendy | Spendy/Helpers/BalanceComputing.swift | 1 | 1342 | //
// BalanceComputing.swift
// Spendy
//
// Created by Harley Trung on 10/18/15.
// Copyright © 2015 Cheetah. All rights reserved.
//
import Foundation
import RealmSwift
struct BalanceComputing {
// recompute balance for an account
// update balance snapshot in each transaction
// upate total balance in account
static func recompute(account: Account) {
print("BalanceCompute.recompute(_) for \(account.id)")
var bal = account.startingBalance
// TODO: check if this actually works
let transactions = account.transactions.sorted("date", ascending: true)
let realm = try! Realm()
try! realm.write {
for t in transactions {
switch t.kind! {
case CategoryType.Income.rawValue:
bal += t.amount
t.balanceSnapshot = bal
case CategoryType.Expense.rawValue:
bal -= t.amount
t.balanceSnapshot = bal
case CategoryType.Transfer.rawValue:
if t.toAccount == account {
bal += t.amount
t.toBalanceSnapshot = bal
} else {
bal -= t.amount
t.balanceSnapshot = bal
}
default:
print("Unexpected transaction kind \(t.kind) for transaction id \(t.id)")
}
}
account.balance = bal
}
}
}
| mit | 6869799fd210fcd125c621fe8406d1d6 | 25.294118 | 83 | 0.592095 | 4.515152 | false | false | false | false |
onevcat/Kingfisher | Sources/General/KFOptionsSetter.swift | 3 | 34156 | //
// KFOptionsSetter.swift
// Kingfisher
//
// Created by onevcat on 2020/12/22.
//
// Copyright (c) 2020 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
public protocol KFOptionSetter {
var options: KingfisherParsedOptionsInfo { get nonmutating set }
var onFailureDelegate: Delegate<KingfisherError, Void> { get }
var onSuccessDelegate: Delegate<RetrieveImageResult, Void> { get }
var onProgressDelegate: Delegate<(Int64, Int64), Void> { get }
var delegateObserver: AnyObject { get }
}
extension KF.Builder: KFOptionSetter {
public var delegateObserver: AnyObject { self }
}
// MARK: - Life cycles
extension KFOptionSetter {
/// Sets the progress block to current builder.
/// - Parameter block: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called. If `block` is `nil`, the callback
/// will be reset.
/// - Returns: A `Self` value with changes applied.
public func onProgress(_ block: DownloadProgressBlock?) -> Self {
onProgressDelegate.delegate(on: delegateObserver) { (observer, result) in
block?(result.0, result.1)
}
return self
}
/// Sets the the done block to current builder.
/// - Parameter block: Called when the image task successfully completes and the the image set is done. If `block`
/// is `nil`, the callback will be reset.
/// - Returns: A `KF.Builder` with changes applied.
public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self {
onSuccessDelegate.delegate(on: delegateObserver) { (observer, result) in
block?(result)
}
return self
}
/// Sets the catch block to current builder.
/// - Parameter block: Called when an error happens during the image task. If `block`
/// is `nil`, the callback will be reset.
/// - Returns: A `KF.Builder` with changes applied.
public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self {
onFailureDelegate.delegate(on: delegateObserver) { (observer, error) in
block?(error)
}
return self
}
}
// MARK: - Basic options settings.
extension KFOptionSetter {
/// Sets the target image cache for this task.
/// - Parameter cache: The target cache is about to be used for the task.
/// - Returns: A `Self` value with changes applied.
///
/// Kingfisher will use the associated `ImageCache` object when handling related operations,
/// including trying to retrieve the cached images and store the downloaded image to it.
///
public func targetCache(_ cache: ImageCache) -> Self {
options.targetCache = cache
return self
}
/// Sets the target image cache to store the original downloaded image for this task.
/// - Parameter cache: The target cache is about to be used for storing the original downloaded image from the task.
/// - Returns: A `Self` value with changes applied.
///
/// The `ImageCache` for storing and retrieving original images. If `originalCache` is
/// contained in the options, it will be preferred for storing and retrieving original images.
/// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
///
/// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
/// applied in the option, the original image will be stored to this `originalCache`. At the
/// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
/// Kingfisher will try to search the original image to check whether it is already there. If found,
/// it will be used and applied with the given processor. It is an optimization for not downloading
/// the same image for multiple times.
///
public func originalCache(_ cache: ImageCache) -> Self {
options.originalCache = cache
return self
}
/// Sets the downloader used to perform the image download task.
/// - Parameter downloader: The downloader which is about to be used for downloading.
/// - Returns: A `Self` value with changes applied.
///
/// Kingfisher will use the set `ImageDownloader` object to download the requested images.
public func downloader(_ downloader: ImageDownloader) -> Self {
options.downloader = downloader
return self
}
/// Sets the download priority for the image task.
/// - Parameter priority: The download priority of image download task.
/// - Returns: A `Self` value with changes applied.
///
/// The `priority` value will be set as the priority of the image download task. The value for it should be
/// between 0.0~1.0. You can choose a value between `URLSessionTask.defaultPriority`, `URLSessionTask.lowPriority`
/// or `URLSessionTask.highPriority`. If this option not set, the default value (`URLSessionTask.defaultPriority`)
/// will be used.
public func downloadPriority(_ priority: Float) -> Self {
options.downloadPriority = priority
return self
}
/// Sets whether Kingfisher should ignore the cache and try to start a download task for the image source.
/// - Parameter enabled: Enable the force refresh or not.
/// - Returns: A `Self` value with changes applied.
public func forceRefresh(_ enabled: Bool = true) -> Self {
options.forceRefresh = enabled
return self
}
/// Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the
/// disk cache and starts a download task for the image source.
/// - Parameter enabled: Enable the memory-only cache searching or not.
/// - Returns: A `Self` value with changes applied.
///
/// This is useful when you want to display a changeable image behind the same url at the same app session, while
/// avoiding download it for multiple times.
public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self {
options.fromMemoryCacheOrRefresh = enabled
return self
}
/// Sets whether the image should only be cached in memory but not in disk.
/// - Parameter enabled: Whether the image should be only cache in memory or not.
/// - Returns: A `Self` value with changes applied.
public func cacheMemoryOnly(_ enabled: Bool = true) -> Self {
options.cacheMemoryOnly = enabled
return self
}
/// Sets whether Kingfisher should wait for caching operation to be completed before calling the
/// `onSuccess` or `onFailure` block.
/// - Parameter enabled: Whether Kingfisher should wait for caching operation.
/// - Returns: A `Self` value with changes applied.
public func waitForCache(_ enabled: Bool = true) -> Self {
options.waitForCache = enabled
return self
}
/// Sets whether Kingfisher should only try to retrieve the image from cache, but not from network.
/// - Parameter enabled: Whether Kingfisher should only try to retrieve the image from cache.
/// - Returns: A `Self` value with changes applied.
///
/// If the image is not in cache, the image retrieving will fail with the
/// `KingfisherError.cacheError` with `.imageNotExisting` as its reason.
public func onlyFromCache(_ enabled: Bool = true) -> Self {
options.onlyFromCache = enabled
return self
}
/// Sets whether the image should be decoded in a background thread before using.
/// - Parameter enabled: Whether the image should be decoded in a background thread before using.
/// - Returns: A `Self` value with changes applied.
///
/// Setting to `true` will decode the downloaded image data and do a off-screen rendering to extract pixel
/// information in background. This can speed up display, but will cost more time and memory to prepare the image
/// for using.
public func backgroundDecode(_ enabled: Bool = true) -> Self {
options.backgroundDecode = enabled
return self
}
/// Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from
/// cache. If not set, Kingfisher will use main queue for callbacks.
/// - Parameter queue: The target queue which the cache retrieving callback will be invoked on.
/// - Returns: A `Self` value with changes applied.
///
/// - Note:
/// This option does not affect the callbacks for UI related extension methods or `KFImage` result handlers.
/// You will always get the callbacks called from main queue.
public func callbackQueue(_ queue: CallbackQueue) -> Self {
options.callbackQueue = queue
return self
}
/// Sets the scale factor value when converting retrieved data to an image.
/// - Parameter factor: The scale factor value.
/// - Returns: A `Self` value with changes applied.
///
/// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
/// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
///
public func scaleFactor(_ factor: CGFloat) -> Self {
options.scaleFactor = factor
return self
}
/// Sets whether the original image should be cached even when the original image has been processed by any other
/// `ImageProcessor`s.
/// - Parameter enabled: Whether the original image should be cached.
/// - Returns: A `Self` value with changes applied.
///
/// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
/// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
/// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
/// images if necessary.
///
/// The original image will be only cached to disk storage.
///
public func cacheOriginalImage(_ enabled: Bool = true) -> Self {
options.cacheOriginalImage = enabled
return self
}
/// Sets writing options for an original image on a first write
/// - Parameter writingOptions: Options to control the writing of data to a disk storage.
/// - Returns: A `Self` value with changes applied.
/// If set, options will be passed the store operation for a new files.
///
/// This is useful if you want to implement file enctyption on first write - eg [.completeFileProtection]
///
public func diskStoreWriteOptions(_ writingOptions: Data.WritingOptions) -> Self {
options.diskStoreWriteOptions = writingOptions
return self
}
/// Sets whether the disk storage loading should happen in the same calling queue.
/// - Parameter enabled: Whether the disk storage loading should happen in the same calling queue.
/// - Returns: A `Self` value with changes applied.
///
/// By default, disk storage file loading
/// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
/// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
/// has an image set.
///
/// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
/// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
///
public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self {
options.loadDiskFileSynchronously = enabled
return self
}
/// Sets a queue on which the image processing should happen.
/// - Parameter queue: The queue on which the image processing should happen.
/// - Returns: A `Self` value with changes applied.
///
/// By default, Kingfisher uses a pre-defined serial
/// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
/// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
/// blocking the UI, especially if the processor needs a lot of time to run).
public func processingQueue(_ queue: CallbackQueue?) -> Self {
options.processingQueue = queue
return self
}
/// Sets the alternative sources that will be used when loading of the original input `Source` fails.
/// - Parameter sources: The alternative sources will be used.
/// - Returns: A `Self` value with changes applied.
///
/// Values of the `sources` array will be used to start a new image loading task if the previous task
/// fails due to an error. The image source loading process will stop as soon as a source is loaded successfully.
/// If all `sources` are used but the loading is still failing, an `imageSettingError` with
/// `alternativeSourcesExhausted` as its reason will be given out in the `catch` block.
///
/// This is useful if you want to implement a fallback solution for setting image.
///
/// User cancellation will not trigger the alternative source loading.
public func alternativeSources(_ sources: [Source]?) -> Self {
options.alternativeSources = sources
return self
}
/// Sets a retry strategy that will be used when something gets wrong during the image retrieving.
/// - Parameter strategy: The provided strategy to define how the retrying should happen.
/// - Returns: A `Self` value with changes applied.
public func retry(_ strategy: RetryStrategy?) -> Self {
options.retryStrategy = strategy
return self
}
/// Sets a retry strategy with a max retry count and retrying interval.
/// - Parameters:
/// - maxCount: The maximum count before the retry stops.
/// - interval: The time interval between each retry attempt.
/// - Returns: A `Self` value with changes applied.
///
/// This defines the simplest retry strategy, which retry a failing request for several times, with some certain
/// interval between each time. For example, `.retry(maxCount: 3, interval: .second(3))` means attempt for at most
/// three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt.
public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self {
let strategy = DelayRetryStrategy(maxRetryCount: maxCount, retryInterval: interval)
options.retryStrategy = strategy
return self
}
/// Sets the `Source` should be loaded when user enables Low Data Mode and the original source fails with an
/// `NSURLErrorNetworkUnavailableReason.constrained` error.
/// - Parameter source: The `Source` will be loaded under low data mode.
/// - Returns: A `Self` value with changes applied.
///
/// When this option is set, the
/// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the
/// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a
/// low-resolution version of your image or a local image provider to display a placeholder.
///
/// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will
/// be loaded following the system default behavior, in a normal way.
public func lowDataModeSource(_ source: Source?) -> Self {
options.lowDataModeSource = source
return self
}
/// Sets whether the image setting for an image view should happen with transition even when retrieved from cache.
/// - Parameter enabled: Enable the force transition or not.
/// - Returns: A `Self` with changes applied.
public func forceTransition(_ enabled: Bool = true) -> Self {
options.forceTransition = enabled
return self
}
/// Sets the image that will be used if an image retrieving task fails.
/// - Parameter image: The image that will be used when something goes wrong.
/// - Returns: A `Self` with changes applied.
///
/// If set and an image retrieving error occurred Kingfisher will set provided image (or empty)
/// in place of requested one. It's useful when you don't want to show placeholder
/// during loading time but wants to use some default image when requests will be failed.
///
public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self {
options.onFailureImage = .some(image)
return self
}
}
// MARK: - Request Modifier
extension KFOptionSetter {
/// Sets an `ImageDownloadRequestModifier` to change the image download request before it being sent.
/// - Parameter modifier: The modifier will be used to change the request before it being sent.
/// - Returns: A `Self` value with changes applied.
///
/// This is the last chance you can modify the image download request. You can modify the request for some
/// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
///
public func requestModifier(_ modifier: AsyncImageDownloadRequestModifier) -> Self {
options.requestModifier = modifier
return self
}
/// Sets a block to change the image download request before it being sent.
/// - Parameter modifyBlock: The modifying block will be called to change the request before it being sent.
/// - Returns: A `Self` value with changes applied.
///
/// This is the last chance you can modify the image download request. You can modify the request for some
/// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
///
public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self {
options.requestModifier = AnyModifier { r -> URLRequest? in
var request = r
modifyBlock(&request)
return request
}
return self
}
}
// MARK: - Redirect Handler
extension KFOptionSetter {
/// The `ImageDownloadRedirectHandler` argument will be used to change the request before redirection.
/// This is the possibility you can modify the image download request during redirect. You can modify the request for
/// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
/// mapping.
/// The original redirection request will be sent without any modification by default.
/// - Parameter handler: The handler will be used for redirection.
/// - Returns: A `Self` value with changes applied.
public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self {
options.redirectHandler = handler
return self
}
/// The `block` will be used to change the request before redirection.
/// This is the possibility you can modify the image download request during redirect. You can modify the request for
/// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
/// mapping.
/// The original redirection request will be sent without any modification by default.
/// - Parameter block: The block will be used for redirection.
/// - Returns: A `Self` value with changes applied.
public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self {
let redirectHandler = AnyRedirectHandler { (task, response, request, handler) in
let payload = KF.RedirectPayload(
task: task, response: response, newRequest: request, completionHandler: handler
)
block(payload)
}
options.redirectHandler = redirectHandler
return self
}
}
// MARK: - Processor
extension KFOptionSetter {
/// Sets an image processor for the image task. It replaces the current image processor settings.
///
/// - Parameter processor: The processor you want to use to process the image after it is downloaded.
/// - Returns: A `Self` value with changes applied.
///
/// - Note:
/// To append a processor to current ones instead of replacing them all, use `appendProcessor(_:)`.
public func setProcessor(_ processor: ImageProcessor) -> Self {
options.processor = processor
return self
}
/// Sets an array of image processors for the image task. It replaces the current image processor settings.
/// - Parameter processors: An array of processors. The processors inside this array will be concatenated one by one
/// to form a processor pipeline.
/// - Returns: A `Self` value with changes applied.
///
/// - Note:
/// To append processors to current ones instead of replacing them all, concatenate them by `|>`, then use
/// `appendProcessor(_:)`.
public func setProcessors(_ processors: [ImageProcessor]) -> Self {
switch processors.count {
case 0:
options.processor = DefaultImageProcessor.default
case 1...:
options.processor = processors.dropFirst().reduce(processors[0]) { $0 |> $1 }
default:
assertionFailure("Never happen")
}
return self
}
/// Appends a processor to the current set processors.
/// - Parameter processor: The processor which will be appended to current processor settings.
/// - Returns: A `Self` value with changes applied.
public func appendProcessor(_ processor: ImageProcessor) -> Self {
options.processor = options.processor |> processor
return self
}
/// Appends a `RoundCornerImageProcessor` to current processors.
/// - Parameters:
/// - radius: The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction
/// of the target image with `.widthFraction`. or `.heightFraction`. For example, given a square image
/// with width and height equals, `.widthFraction(0.5)` means use half of the length of size and makes
/// the final image a round one.
/// - targetSize: Target size of output image should be. If `nil`, the image will keep its original size after processing.
/// - corners: The target corners which will be applied rounding.
/// - backgroundColor: Background color of the output image. If `nil`, it will use a transparent background.
/// - Returns: A `Self` value with changes applied.
public func roundCorner(
radius: Radius,
targetSize: CGSize? = nil,
roundingCorners corners: RectCorner = .all,
backgroundColor: KFCrossPlatformColor? = nil
) -> Self
{
let processor = RoundCornerImageProcessor(
radius: radius,
targetSize: targetSize,
roundingCorners: corners,
backgroundColor: backgroundColor
)
return appendProcessor(processor)
}
/// Appends a `BlurImageProcessor` to current processors.
/// - Parameter radius: Blur radius for the simulated Gaussian blur.
/// - Returns: A `Self` value with changes applied.
public func blur(radius: CGFloat) -> Self {
appendProcessor(
BlurImageProcessor(blurRadius: radius)
)
}
/// Appends a `OverlayImageProcessor` to current processors.
/// - Parameters:
/// - color: Overlay color will be used to overlay the input image.
/// - fraction: Fraction will be used when overlay the color to image.
/// - Returns: A `Self` value with changes applied.
public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self {
appendProcessor(
OverlayImageProcessor(overlay: color, fraction: fraction)
)
}
/// Appends a `TintImageProcessor` to current processors.
/// - Parameter color: Tint color will be used to tint the input image.
/// - Returns: A `Self` value with changes applied.
public func tint(color: KFCrossPlatformColor) -> Self {
appendProcessor(
TintImageProcessor(tint: color)
)
}
/// Appends a `BlackWhiteProcessor` to current processors.
/// - Returns: A `Self` value with changes applied.
public func blackWhite() -> Self {
appendProcessor(
BlackWhiteProcessor()
)
}
/// Appends a `CroppingImageProcessor` to current processors.
/// - Parameters:
/// - size: Target size of output image should be.
/// - anchor: Anchor point from which the output size should be calculate. The anchor point is consisted by two
/// values between 0.0 and 1.0. It indicates a related point in current image.
/// See `CroppingImageProcessor.init(size:anchor:)` for more.
/// - Returns: A `Self` value with changes applied.
public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self {
appendProcessor(
CroppingImageProcessor(size: size, anchor: anchor)
)
}
/// Appends a `DownsamplingImageProcessor` to current processors.
///
/// Compared to `ResizingImageProcessor`, the `DownsamplingImageProcessor` does not render the original images and
/// then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient
/// than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
/// as you can than the `ResizingImageProcessor`.
///
/// Only CG-based images are supported. Animated images (like GIF) is not supported.
///
/// - Parameter size: Target size of output image should be. It should be smaller than the size of input image.
/// If it is larger, the result image will be the same size of input data without downsampling.
/// - Returns: A `Self` value with changes applied.
public func downsampling(size: CGSize) -> Self {
let processor = DownsamplingImageProcessor(size: size)
if options.processor == DefaultImageProcessor.default {
return setProcessor(processor)
} else {
return appendProcessor(processor)
}
}
/// Appends a `ResizingImageProcessor` to current processors.
///
/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
/// instead, which is more efficient and uses less memory.
///
/// - Parameters:
/// - referenceSize: The reference size for resizing operation in point.
/// - mode: Target content mode of output image should be. Default is `.none`.
/// - Returns: A `Self` value with changes applied.
public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self {
appendProcessor(
ResizingImageProcessor(referenceSize: referenceSize, mode: mode)
)
}
}
// MARK: - Cache Serializer
extension KFOptionSetter {
/// Uses a given `CacheSerializer` to convert some data to an image object for retrieving from disk cache or vice
/// versa for storing to disk cache.
/// - Parameter cacheSerializer: The `CacheSerializer` which will be used.
/// - Returns: A `Self` value with changes applied.
public func serialize(by cacheSerializer: CacheSerializer) -> Self {
options.cacheSerializer = cacheSerializer
return self
}
/// Uses a given format to serializer the image data to disk. It converts the image object to the give data format.
/// - Parameters:
/// - format: The desired data encoding format when store the image on disk.
/// - jpegCompressionQuality: If the format is `.JPEG`, it specify the compression quality when converting the
/// image to a JPEG data. Otherwise, it is ignored.
/// - Returns: A `Self` value with changes applied.
public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self {
let cacheSerializer: FormatIndicatedCacheSerializer
switch format {
case .JPEG:
cacheSerializer = .jpeg(compressionQuality: jpegCompressionQuality ?? 1.0)
case .PNG:
cacheSerializer = .png
case .GIF:
cacheSerializer = .gif
case .unknown:
cacheSerializer = .png
}
options.cacheSerializer = cacheSerializer
return self
}
}
// MARK: - Image Modifier
extension KFOptionSetter {
/// Sets an `ImageModifier` to the image task. Use this to modify the fetched image object properties if needed.
///
/// If the image was fetched directly from the downloader, the modifier will run directly after the
/// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
/// - Parameter modifier: The `ImageModifier` which will be used to modify the image object.
/// - Returns: A `Self` value with changes applied.
public func imageModifier(_ modifier: ImageModifier?) -> Self {
options.imageModifier = modifier
return self
}
/// Sets a block to modify the image object. Use this to modify the fetched image object properties if needed.
///
/// If the image was fetched directly from the downloader, the modifier block will run directly after the
/// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
///
/// - Parameter block: The block which is used to modify the image object.
/// - Returns: A `Self` value with changes applied.
public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self {
let modifier = AnyImageModifier { image -> KFCrossPlatformImage in
var image = image
try block(&image)
return image
}
options.imageModifier = modifier
return self
}
}
// MARK: - Cache Expiration
extension KFOptionSetter {
/// Sets the expiration setting for memory cache of this image task.
///
/// By default, the underlying `MemoryStorage.Backend` uses the
/// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this value to overwrite
/// the config setting for this caching item.
///
/// - Parameter expiration: The expiration setting used in cache storage.
/// - Returns: A `Self` value with changes applied.
public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self {
options.memoryCacheExpiration = expiration
return self
}
/// Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this
/// value after access.
///
/// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending
/// value: .cacheTime.
///
/// To disable extending option at all, sets `.none` to it.
///
/// - Parameter extending: The expiration extending setting used in cache storage.
/// - Returns: A `Self` value with changes applied.
public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
options.memoryCacheAccessExtendingExpiration = extending
return self
}
/// Sets the expiration setting for disk cache of this image task.
///
/// By default, the underlying `DiskStorage.Backend` uses the expiration in its config for all items. If set,
/// the `DiskStorage.Backend` will use this value to overwrite the config setting for this caching item.
///
/// - Parameter expiration: The expiration setting used in cache storage.
/// - Returns: A `Self` value with changes applied.
public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self {
options.diskCacheExpiration = expiration
return self
}
/// Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this
/// value after access.
///
/// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending
/// value: .cacheTime.
///
/// To disable extending option at all, sets `.none` to it.
///
/// - Parameter extending: The expiration extending setting used in cache storage.
/// - Returns: A `Self` value with changes applied.
public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
options.diskCacheAccessExtendingExpiration = extending
return self
}
}
| mit | 2327192ff3981dcd21751a939d06ff0e | 47.311174 | 128 | 0.676894 | 4.928716 | false | false | false | false |
mikengyn/SideMenuController | Example/Example/CachingSideViewController.swift | 3 | 2058 | //
// CachingSideViewController.swift
// Example
//
// Created by Teodor Patras on 15/07/16.
// Copyright © 2016 teodorpatras. All rights reserved.
//
import UIKit
import SideMenuController
class CachingSideViewController: UITableViewController, SideMenuControllerDelegate {
let dataSource = [FCViewController.self, SCViewController.self, TCViewController.self] as [Any]
let cellIdentifier = "cachingSideCell"
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sideMenuController?.delegate = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
cell?.textLabel?.text = "Switch to: " + (dataSource[indexPath.row] as! CacheableViewController.Type).cacheIdentifier
return cell!
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let controllerType = dataSource[indexPath.row] as! CacheableViewController.Type
if let controller = sideMenuController?.viewController(forCacheIdentifier: controllerType.cacheIdentifier) {
sideMenuController?.embed(centerViewController: controller)
} else {
sideMenuController?.embed(centerViewController: UINavigationController(rootViewController: controllerType.init()), cacheIdentifier: controllerType.cacheIdentifier)
}
}
func sideMenuControllerDidHide(_ sideMenuController: SideMenuController) {
print(#function)
}
func sideMenuControllerDidReveal(_ sideMenuController: SideMenuController) {
print(#function)
}
}
| mit | 37b6256fcd42ae89e283f668ad3708cf | 35.732143 | 175 | 0.697132 | 5.729805 | false | false | false | false |
muukii/JAYSON | Tests/BasicTests/Tests.swift | 1 | 6532 | import Foundation
import XCTest
@testable import JAYSON
class Tests: XCTestCase {
let inData = Data(referencing: NSData(contentsOfFile: Bundle(for: Tests.self).path(forResource: "test", ofType: "json")!)!)
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
enum Enum {
case a
case b
case c
var json: JSON {
switch self {
case .a:
return JSON("a")
case .b:
return JSON("b")
case .c:
return JSON("c")
}
}
}
func testEqualable() {
let source: [String : JSON] = [
"aaa":"AAA",
"bbb":["BBB":"AAA"],
"a":[1,2,3],
"enum":Enum.a.json,
]
let json = JSON(source)
let json2 = JSON(source)
XCTAssert(json == json2)
}
func testDictionaryInit() {
let dictionary: [AnyHashable : Any] = [
"title" : "foo",
"name" : "hiroshi",
"age" : 25,
"height" : 173,
]
do {
let json = try JSON(any: dictionary)
let data = try json.data()
_ = try JSON(data: data)
} catch {
XCTFail("\(error)")
}
}
func testURLInit() {
let dictionary = [
"url" : "https://antoine.marandon.fr",
]
do {
let json = try JSON(any: dictionary)
let data = try json.data()
let parsedJson = try JSON(data: data)
XCTAssertEqual(dictionary["url"], try parsedJson.next("url").getURL().absoluteString)
} catch {
XCTFail("\(error)")
}
}
func testIsArray() {
let json = JSON([
128,129,130,
])
XCTAssert(json.isArray)
}
func testIsDictionary() {
let json = JSON(
[
"aaa":"AAA",
"bbb":["BBB":"AAA"],
"a":[1,2,3],
"enum":Enum.a.json,
]
)
XCTAssert(json.isDictionary)
}
func testExists() {
let j = try! JSON(data: inData)
XCTAssert(j.presentsValue(13) == false)
XCTAssert(j.presentsValue("a") == false)
XCTAssert(j.presentsValue("b") == false)
XCTAssert(j.presentsValue("a.b.c") == false)
XCTAssert(j.presentsValue("tree1.tree2") == true)
XCTAssert(j.presentsValue("tree1", "tree2") == true)
XCTAssert(j.presentsValue("tree1") == true)
}
func testNext() {
do {
let j = try JSON(data: inData)
let v = j["a"]?["b"]?[1]
XCTAssert(v == nil)
} catch {
XCTFail("\(error)")
}
do {
let j = try JSON(data: inData)
do {
_ = try j.next("a").next("b").next("c")
XCTFail()
} catch {
print("Success \(error)")
}
} catch {
XCTFail("\(error)")
}
do {
let j = try JSON(data: inData)
let v = try j.next("tree1.tree2.tree3").next(0).next("index")
XCTAssertEqual(v, "myvalue")
} catch {
XCTFail("\(error)")
}
}
func testRemove() {
let j = try! JSON(data: inData)
let removed = j.removed("tree1")
XCTAssert(j["tree1"] != nil)
XCTAssert(removed["tree1"] == nil)
}
func testImportExport() {
do {
let j = try JSON(data: inData)
_ = try j.data()
} catch {
XCTFail("\(error)")
}
}
func testBack() {
do {
let j = try JSON(data: inData)
let value = try j
.next("tree1")
.next("tree2")
.back()
.next("tree2")
.back()
.back()
.next("tree1")
.next("tree2")
.next("tree3")
.next(0)
.next("index")
.getString()
XCTAssertEqual(value, "myvalue")
} catch {
XCTFail("\(error)")
}
}
func testBuild() {
var j = JSON()
j["number"] = 124
j["text"] = "hooo"
j["bool"] = true
j["null"] = JSON.null
j["tree1"] = JSON(
[
"tree2" : JSON(
[
"tree3" : JSON(
[
JSON(["index" : "myvalue"])
]
)
]
)
]
)
do {
let data = try j.data(options: .prettyPrinted)
let text = String(data: data, encoding: .utf8)!
print(text)
} catch {
print(j.source)
XCTFail("\(error)")
}
}
func testNull() {
// Key is existing, but value is null.
// Ignoring NSNull
let j = try! JSON(data: inData)
XCTAssertNil(j["null"])
}
func testMutation() {
var j = try! JSON(data: inData)
XCTAssertNotNil(j["number"])
j["number"] = nil
XCTAssertNil(j["number"])
}
/*
func testJSONWritable() {
var json = JSON()
json["String"] = "String"
json["NSString"] = JSON("NSString" as NSString)
json["Int"] = 64
json["Int8"] = JSON(8 as Int8)
json["Int16"] = JSON(16 as Int16)
json["Int32"] = JSON(32 as Int32)
json["Int64"] = JSON(64 as Int64)
json["UInt"] = JSON(64 as UInt)
json["UInt8"] = JSON(8 as UInt8)
json["UInt16"] = JSON(16 as UInt16)
json["UInt32"] = JSON(32 as UInt32)
json["UInt64"] = JSON(64 as UInt64)
json["Bool_true"] = true
json["Bool_false"] = false
json["Float"] = JSON(1.0 / 3.0 as Float)
json["Double"] = JSON(1.0 / 3.0 as Double)
#if !os(Linux)
json["CGFloat"] = JSON(1.0 / 3.0 as CGFloat)
let answer = "{\"UInt8\":8,\"Int32\":32,\"UInt\":64,\"UInt16\":16,\"UInt32\":32,\"Int16\":16,\"Int\":64,\"String\":\"String\",\"CGFloat\":0.3333333333333333,\"Int8\":8,\"UInt64\":64,\"Float\":0.3333333,\"Double\":0.3333333333333333,\"Bool_true\":true,\"Int64\":64,\"Bool_false\":false,\"NSString\":\"NSString\"}"
print(String(data: try! json.data(), encoding: .utf8))
let value = String(data: try! json.data(), encoding: .utf8)!
XCTAssert(answer == value)
#else
let answer = "{\"UInt8\":8,\"Int32\":32,\"UInt\":64,\"UInt16\":16,\"UInt32\":32,\"Int16\":16,\"Int\":64,\"String\":\"String\",\"Int8\":8,\"UInt64\":64,\"Float\":0.3333333,\"Double\":0.3333333333333333,\"Bool_true\":true,\"Int64\":64,\"Bool_false\":false,\"NSString\":\"NSString\"}"
print(String(data: try! json.data(), encoding: .utf8))
let value = String(data: try! json.data(), encoding: .utf8)!
XCTAssert(answer == value)
#endif
}
*/
}
private func jsonFromString(_ string: () -> String) -> JSON {
try! JSON(data: string().data(using: .utf8)!)
}
| mit | ddfbdf5ddc5c75c37424b0f5a1a42946 | 21.759582 | 318 | 0.523117 | 3.487453 | false | true | false | false |
peteratseneca/dps923winter2015 | Week_09/Scroll/Classes/Launch.swift | 1 | 9251 | //
// Launch.swift
// Toronto 2015
//
// Created by Peter McIntyre on 2015-03-03.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import UIKit
import CoreData
class Launch: UIViewController {
// MARK: - Properties
var model: Model!
// These will be filled by the results of the web service requests
var sports = [AnyObject]()
var venues = [AnyObject]()
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let frc = model.frc_sport
// This controller will be the frc delegate
frc.delegate = nil
// No predicate (which means the results will NOT be filtered)
frc.fetchRequest.predicate = nil
// Create an error object
var error: NSError? = nil
// Perform fetch, and if there's an error, log it
if !frc.performFetch(&error) { println(error?.description) }
// Finally, check for data on the device, and if not, load the data
checkForDataOnDevice()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toSportList" {
let vc = segue.destinationViewController as SportList
vc.model = model
}
if segue.identifier == "toVenueList" {
let vc = segue.destinationViewController as VenueList
vc.model = model
}
}
// MARK: - On first launch, fetch initial data from the web service
func checkForDataOnDevice() {
if model.frc_sport.fetchedObjects?.count == 0 {
print("Device does not have data.\nWill fetch data from the network.\n")
// First, listen for the notification (from the WebServiceRequest instance)
// that indicates that the download is complete
NSNotificationCenter.defaultCenter().addObserver(self, selector: "fetchCompletedSports", name: "Scroll.Launch_sports_fetch_completed", object: nil)
// Next, cause the request to run
// Create, configure, and execute a web service request
// When complete, the runtime will save the results in the 'sports' array variable,
// and call the 'fetchCompletedSports' method
let request = WebServiceRequest()
request.sendRequestToUrlPath("/sports", forDataKeyName: "Collection", from: self, propertyNamed: "sports")
print("Request for sports has been sent.\nWaiting for results.\n\n")
}
}
func fetchCompletedSports() {
// This method is called when there's new/updated data from the network
// It's the 'listener' method
print("Results have returned.\n")
print("\(sports.count) sport objects were fetched.\n")
print("Next, the venues will be fetched.\n")
// First, listen for the notification (from the WebServiceRequest instance)
// that indicates that the download is complete
NSNotificationCenter.defaultCenter().addObserver(self, selector: "fetchCompletedVenues", name: "Scroll.Launch_venues_fetch_completed", object: nil)
// Next, cause the request to run
// Create, configure, and execute a web service request
// When complete, the runtime will save the results in the 'venues' array variable,
// and call the 'fetchCompletedVenues' method
let request = WebServiceRequest()
request.sendRequestToUrlPath("/venues/withsports", forDataKeyName: "Collection", from: self, propertyNamed: "venues")
print("Request for venues has been sent.\nWaiting for results.\n\n")
}
func fetchCompletedVenues() {
// This method is called when there's new/updated data from the network
// It's the 'listener' method
print("Results have returned.\n")
print("\(venues.count) venue objects were fetched.\n")
print("Data will be saved on this device.\n")
// At this point in time, we have all the sports and venues
// Process the sports first...
// For each web service sport, create and configure a local sport object
for s in sports {
// Here, we use 'd' for the name of the new device-stored object
let d = model.addNewSport()
// The data type of the web service 'sport' is AnyObject
// When reading a value from this AnyObject,
// we will use its key-value accessor, 'valueForKey'
// The data type of the local 'sport' is Sport
// When writing (setting) a value to this Sport,
// we will use its property name
d.sportName = s.valueForKey("Name") as String
print("Adding \(d.sportName)...\n")
d.sportDescription = s.valueForKey("Description") as String
d.history = s.valueForKey("History") as String
d.howItWorks = s.valueForKey("HowItWorks") as String
d.hostId = s.valueForKey("Id") as Int
// Get logo and photo
// let urlLogo = s.valueForKey("LogoUrl") as String
// if let logo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlLogo)!)!) {
// d.logo = UIImagePNGRepresentation(logo)
// }
//
// let urlPhoto = s.valueForKey("PhotoUrl") as String
// if let photo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlPhoto)!)!) {
// d.photo = UIImagePNGRepresentation(photo)
// }
//
// print("- logo and photo fetched.\n")
}
print("All sports have been added.\n\n")
model.saveChanges()
// Create and configure a fetch request object
// We will need this to set the sport-venue relation
let f = NSFetchRequest(entityName: "Sport")
// Process the venues next...
// For each web service venue, create and configure a local venue object
// While doing this, use the fetch request object to get a local sport object,
// so that it can be set in the 'sports' relation collection
// This task uses an Venue 'extension', which you can find in the
// 'Extensions.swift' source code file
// Use this 'best practice' technique to configure a many-to-many relationship
for v in venues {
// Here, we use 'd' for the name of the new device-stored object
let d = model.addNewVenue()
d.venueName = v.valueForKey("Name") as String
print("Adding \(d.venueName)...\n")
d.venueDescription = v.valueForKey("Description") as String
d.location = v.valueForKey("Location") as String
// // Get photo and map
//
// let urlPhoto = v.valueForKey("PhotoUrl") as String
// if let photo = UIImage(data: NSData(contentsOfURL: NSURL(string: urlPhoto)!)!) {
// d.photo = UIImagePNGRepresentation(photo)
// }
//
// let urlMap = v.valueForKey("MapUrl") as String
// if let map = NSData(contentsOfURL: NSURL(string: urlMap)!) {
// d.map = map
// }
//
// print("- photo and map fetched.\n")
model.saveChanges()
// This code block will check if the web service 'venue'
// has anything in its "Sports" collection
// If yes, the code will fetch the 'sport' object from the device data store,
// and use it to set the sport-venue relationship
if let sportsInVenue = (v.valueForKey("Sports") as? [AnyObject]) {
for s in sportsInVenue {
// We need a unique identifier, and the web service 'Id' value is unique
let sportId = s.valueForKey("Id") as Int
// We will use that value in the (lookup/search) predicate
f.predicate = NSPredicate(format: "hostId == %@", argumentArray: [sportId])
// Attempt to fetch the matching sport object from the device store
// The results from the 'executeFetchRequest' call is an array of AnyObject
// However, the array will contain exactly one object (if successful)
// That's why we get and use the first object found in the array
if let relatedSport = (model.executeFetchRequest(fetchRequest: f))[0] as? Sport {
d.addSport(relatedSport)
print("- \(relatedSport.sportName) added to this venue\n")
}
}
}
model.saveChanges()
}
print("All venues have been added.\n\n")
}
}
| mit | fde66e5387c9febb023a24f6a5b61bb5 | 38.703863 | 159 | 0.568803 | 4.923363 | false | false | false | false |
qiuncheng/posted-articles-in-blog | Demos/QRCodeDemo/QRCodeDemo/DetectQRCode.swift | 1 | 1016 | //
// DetectQRCode.swift
// YLQRCode
//
// Created by yolo on 2017/1/20.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
import UIKit
import CoreImage
typealias CompletionHandler<T> = (T) -> Void
struct YLDetectQRCode {
static func scanQRCodeFromPhotoLibrary(image: UIImage, completion: CompletionHandler<String?>) {
guard let cgImage = image.cgImage else {
completion(nil)
return
}
if let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) {
let features = detector.features(in: CIImage(cgImage: cgImage))
for feature in features { // 这里实际上可以识别两张二维码,在这里只取第一张(左边或者上边)
if let qrFeature = feature as? CIQRCodeFeature {
completion(qrFeature.messageString)
return
}
}
}
completion(nil)
}
}
| apache-2.0 | 8e9f1f5a26598db188a98be345a624ac | 29.677419 | 137 | 0.619348 | 4.382488 | false | false | false | false |
hakeemsyd/twitter | twitter/HomeViewController.swift | 1 | 5523 | //
// HomeViewController.swift
// twitter
//
// Created by Syed Hakeem Abbas on 9/26/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
import NSDateMinimalTimeAgo
enum Mode {
case PROFILE, HOME, MENTIONS, SOMEONES_PROFILE
}
enum Update {
case RESET, APPEND
}
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let MAX_TWEETS = 5
@IBOutlet weak var tweetButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
var mode: Mode = Mode.PROFILE
var isMoreDataLoading = false
var refreshControl: UIRefreshControl = UIRefreshControl()
@IBOutlet weak var tableView: UITableView!
var userTweets: [Tweet] = [Tweet]()
var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
var user: User = User.currentUser!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
if( mode == Mode.PROFILE || mode == Mode.SOMEONES_PROFILE) {
setupHeader()
}
// pull to refresh
refreshControl.addTarget(self, action: #selector(onUserInitiatedRefresh(_:)), for: UIControlEvents.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
//update()
//infinite scroll
// infinite scroll
let tableFooterView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
loadingView.center = tableFooterView.center
tableFooterView.addSubview(loadingView)
self.tableView.tableFooterView = tableFooterView
}
override func viewWillAppear(_ animated: Bool) {
update(mode: Update.RESET)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onLogoutClicked(_ sender: UIBarButtonItem) {
if mode == Mode.SOMEONES_PROFILE {
//close this view
dismiss(animated: true, completion: nil)
return
}
TwitterClient.sharedInstance.logout()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userTweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(userTweets.count - indexPath.row <= MAX_TWEETS && !self.isMoreDataLoading){
self.isMoreDataLoading = true;
loadingView.startAnimating()
update(mode: Update.APPEND)
}
let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell") as? TweetCell
let t = userTweets[indexPath.row]
cell?.tweet = t
cell?.update()
cell?.onOpenProfile = { (user: User) in
print("\(user.name ?? "")")
self.handleProfPicTap(user: user)
}
return cell!
}
func onUserInitiatedRefresh(_ refreshControl: UIRefreshControl) {
update(mode: Update.RESET)
}
private func update(mode: Update) {
var lasttweeId = -1
if userTweets.count > 0 && mode == Update.APPEND {
lasttweeId = (userTweets.last?.id)!
}
TwitterClient.sharedInstance.timeline(userId: (user.id)!, mode: self.mode, lastTweetId: lasttweeId, maxCount: MAX_TWEETS, success: { (tweets: [Tweet]) in
if mode == Update.RESET {
self.userTweets = tweets
} else if mode == Update.APPEND {
self.userTweets += tweets
}
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.isMoreDataLoading = false
self.loadingView.stopAnimating()
}) { (error: Error) in
self.refreshControl.endRefreshing()
self.loadingView.stopAnimating()
self.isMoreDataLoading = false
print(error.localizedDescription)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "viewTweetSegue") {
let destinationViewController = segue.destination as! TweetDetailViewController
let s = sender as! TweetCell
destinationViewController.tweetId = (s.tweet?.id)!
} else if (segue.identifier == "tweetSegue"){
}
}
private func setupHeader() {
let header = tableView.dequeueReusableCell(withIdentifier: "profileHeader") as! ProfileHeader
header.user = user
tableView.tableHeaderView = header
if mode == Mode.SOMEONES_PROFILE {
logoutButton.title = "close"
tweetButton.isEnabled = false
} else {
logoutButton.title = "Log Out"
tweetButton.isEnabled = true
}
}
private func handleProfPicTap(user: User) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let profileVC = storyboard.instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
profileVC.user = user;
profileVC.mode = Mode.SOMEONES_PROFILE
self.present(profileVC, animated: true, completion: nil)
}
}
| apache-2.0 | 6c83053f563da898fcf10f5063646327 | 32.466667 | 161 | 0.622963 | 4.912811 | false | false | false | false |
fewspider/FFNavigationBar | Example/FFNavigationBar/ViewController.swift | 1 | 1542 | //
// ViewController.swift
// FFNavigationBar
//
// Created by fewspider on 01/23/2016.
// Copyright (c) 2016 fewspider. All rights reserved.
//
import UIKit
import FFNavigationBar
class ViewController: FFNavigationBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func awakeFromNib() {
super.awakeFromNib()
// custom it demo code
// var config = FFNavaigationBarConfig()
// config.screenNavMaxNumber = 3
// config.cursorViewHeight = 5
// config.navTitles = ["Custom0",
// "Custom1",
// "Custom2",
// "Custom3",
// "Custom4",
// "Custom5",
// "Custom6",
// "Custom7",
// "Custom8",
// "Custom9",
// "Custom10"]
// config.navigationScrollViewHeight = 55
// config.navButtonHightlightFontColor = UIColor.redColor()
// config.navButtonNormalFontColor = UIColor.purpleColor()
// config.cursorViewColor = UIColor.redColor()
//
// config.animateDuration = 0.6
//
// self.config = config
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 6b6d1bf3b50a857fd45e5e2f10a78cb6 | 28.653846 | 80 | 0.525292 | 4.65861 | false | true | false | false |
noppoMan/swifty-libuv | Sources/QueueWorkWrap.swift | 1 | 1748 | //
// QueueWorkWrap.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
import CLibUv
private func work_cb(req: UnsafeMutablePointer<uv_work_t>?) {
guard let req = req else {
return
}
let ctx: QueueWorkContext = releaseVoidPointer(req.pointee.data)
ctx.workCallback(ctx)
req.pointee.data = retainedVoidPointer(ctx)
}
private func after_work_cb(req: UnsafeMutablePointer<uv_work_t>?, status: Int32){
guard let req = req else {
return
}
defer {
dealloc(req)
}
let ctx: QueueWorkContext = releaseVoidPointer(req.pointee.data)
ctx.afterWorkCallback(ctx)
}
public class QueueWorkContext {
public let workCallback: (QueueWorkContext) -> Void
public let afterWorkCallback: (QueueWorkContext) -> Void
public var storage: [String: Any] = [:]
public init(workCallback: @escaping (QueueWorkContext) -> Void, afterWorkCallback: @escaping (QueueWorkContext) -> Void) {
self.workCallback = workCallback
self.afterWorkCallback = afterWorkCallback
}
}
public class QueueWorkWrap {
let req: UnsafeMutablePointer<uv_work_t>
let loop: Loop
private let context: QueueWorkContext
public init(loop: Loop = Loop.defaultLoop, context: QueueWorkContext) {
self.loop = loop
self.req = UnsafeMutablePointer<uv_work_t>.allocate(capacity: MemoryLayout<uv_work_t>.size)
self.context = context
}
public func execute(){
req.pointee.data = retainedVoidPointer(context)
uv_queue_work(loop.loopPtr, req, work_cb, after_work_cb)
}
public func cancel(){
uv_cancel(req.cast(to: UnsafeMutablePointer<uv_req_t>.self))
}
}
| mit | a5ce5f2e7bdec58da6cc4ce7a677ef39 | 24.705882 | 126 | 0.655606 | 3.841758 | false | false | false | false |
Return-1/bottomSheetMap | BottomSheetMap/BottomSheetIconAndTextCell.swift | 1 | 1644 | //
// File.swift
// Novoville
//
// Created by George Avgoustis on 04/09/2017.
// Copyright © 2017 George Avgoustis. All rights reserved.
//
import UIKit
class BottomSheetIconAndTextCell : UITableViewCell{
@IBOutlet weak var titleLabel : UILabel?
@IBOutlet weak var iconImgView : UIImageView?
var type = "none"; //enum this
func setData(title: String, type : String){
titleLabel?.text = title;
self.type = type;
switch (type){
case "email":
iconImgView?.image = UIImage(named: "mailOutline", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
case "phone":
iconImgView?.image = UIImage(named: "phoneIcon", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
case "openHours":
iconImgView?.image = UIImage(named: "accessTime", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
case "address":
iconImgView?.image = UIImage(named: "locationPinBottomSheet", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
case "on_duty":
iconImgView?.image = UIImage(named: "onduty", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
default:
iconImgView?.image = UIImage(named: "mailOutline", in: Bundle.init(identifier: "com.malforked.BottomSheetMap"), compatibleWith: nil)
}
}
override func awakeFromNib() {
selectionStyle = .none
}
}
| mit | 668ad8c6b48ac3a7b4ffc4c26640fa6a | 40.075 | 159 | 0.634814 | 4.180662 | false | false | false | false |
jbruce2112/health-tracker | HealthTracker/Model/HealthDataProvider.swift | 1 | 1827 | //
// HealthDataProvider.swift
// HealthTracker
//
// Created by John on 7/25/17.
// Copyright © 2017 Bruce32. All rights reserved.
//
import Foundation
import HealthKit
enum CompareInterval {
case day
case week
case month
case year
}
protocol HealthDataProviderProtocol {
func data(for date: Date, interval: CompareInterval, completion: @escaping ([String: Nutrient]) -> Void)
}
class HealthDataProvider: HealthDataProviderProtocol {
private var healthStore: HKHealthStore
init(withSupportFor types: Set<HKQuantityType>) {
healthStore = HKHealthStore()
// Gather our supported types and request authorization from the health store
healthStore.requestAuthorization(toShare: nil, read: types) { (_, _) in }
}
func data(for date: Date, interval: CompareInterval, completion: @escaping ([String: Nutrient]) -> Void) {
DispatchQueue.global().async {
let serviceGroup = DispatchGroup()
let cal = NSCalendar.current
let start = cal.startOfDay(for: date)
let end = cal.date(byAdding: .day, value: 1, to: start)
let predicate = HKQuery.predicateForSamples(withStart: start, end: end)
var results = [String: Nutrient]()
for sampleType in Nutrient.supportedTypes {
serviceGroup.enter()
let query = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
defer {
serviceGroup.leave()
}
guard let statistic = result, let sum = statistic.sumQuantity() else {
return
}
let nutrient = Nutrient(type: statistic.quantityType, quantity: sum)
results[nutrient.name] = nutrient
}
self.healthStore.execute(query)
}
serviceGroup.wait()
DispatchQueue.main.async {
completion(results)
}
}
}
}
| mit | d1637901d0b49f33499453d0ce8f55ad | 23.026316 | 138 | 0.687842 | 3.918455 | false | false | false | false |
BenziAhamed/Nevergrid | NeverGrid/Source/Level.WarpZone.swift | 1 | 2600 | //
// Level.zoneZone.swift
// MrGreen
//
// Created by Benzi on 23/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
/// extensions to support level zoneing
extension Level {
/// returns an array of accumulated zone zones per zone level
/// configured for this level
func calculateZoneBounds() -> [ZoneBounds] {
// first we calculate the individual zone level bounds
// then this will be acculumated in order to get the
// effective zone zone bounds for a given zone level
// the zone zone bounds is used to calculate the screen
// rect that covers all cells on screen for a given zone
// level.
// as we collect zone keys that start showing up newer sections
// of the grid, we will centre the camera onto the rect of
// the effective zone zone rect bounds. This is taken care
// by the camera system
var zoneBounds = [UInt:ZoneBounds]()
for c in 0..<columns {
for r in 0..<rows {
let cell = cells[c,r]!
if cell.type == CellType.Block {
continue
}
//println(cell)
let currentZone = cell.zone
if zoneBounds[currentZone] == nil {
zoneBounds[currentZone] = ZoneBounds(zone: currentZone)
}
let b = zoneBounds[currentZone]!
//print("<c,r>=(\(c),\(r)) \(b) --> ")
if c < b.start.column {
b.start.column = c
}
else if c > b.end.column {
b.end.column = c
}
if r < b.start.row {
b.start.row = r
}
else if r > b.end.row {
b.end.row = r
}
//println("\(b)")
}
}
var combinedZoneBounds = [ZoneBounds]()
for (zone, bounds) in zoneBounds {
bounds.fixSingleBlock()
combinedZoneBounds.append(bounds)
//println(bounds)
}
// ensure that bounds are ordered based on zone index
return combinedZoneBounds.sort(sortBounds)
}
}
func sortBounds(a:ZoneBounds, b:ZoneBounds) -> Bool {
return a.zone < b.zone
} | isc | b6287395f5f16695a4934a2a4e43ea96 | 28.896552 | 75 | 0.470769 | 4.990403 | false | false | false | false |
noprom/Cocktail-Pro | smartmixer/smartmixer/Home/HomeDirectionSync.swift | 1 | 6493 | //
// HomeDirectionsSync.swift
// smartmixer
//
// Created by 姚俊光 on 14/10/8.
// Copyright (c) 2014年 smarthito. All rights reserved.
//
import UIKit
/**
* 该类是用于处理获取主页更新信息的网络处理部分,
* 该部分的工作首先获取一个当前服务器的版本号与本地匹配,
* 若本地版本与服务器不一致都进行下载更新
*/
//自定义一个搜索设置完毕开始搜索的消息
protocol HomeDirectionSyncDelegate:NSObjectProtocol{
func homeDirectionSync(sender:HomeDirectionSync,NeedRefresh refresh:Bool)
}
class HomeDirectionSync {
init(){
}
//代理
var delegate:HomeDirectionSyncDelegate!
//主页数据存储的基地址
let baseUrl:String="http://???????/cocktailpro/homedirections/"
//是否是强制更新
var byForce:Bool = false
//子线程的数量
var subthread:Int=0
//更新数据的调用
func UpdateHomeSync(){
//第一种 新建线程
NSThread.detachNewThreadSelector("getServerVersionSync:", toTarget:self,withObject:self)
}
@objc func getServerVersionSync(sender:AnyObject){
var owner = sender as! HomeDirectionSync
var request = HTTPTask()
request.GET(owner.baseUrl+"version.txt", parameters: nil, success: {(response: HTTPResponse) in
if response.responseObject != nil {
var localVersion:String?=NSUserDefaults.standardUserDefaults().stringForKey("HomeDirection")
if(localVersion==nil){
localVersion=""
}
let data = response.responseObject as! NSData
let remoteVersion = NSString(data: data, encoding: NSUTF8StringEncoding)
if(localVersion != remoteVersion || owner.byForce){//两地的版本字符串不匹配或是强制更新,开始下载新的
let fileManager = NSFileManager.defaultManager()
var isDir:ObjCBool=false
if !fileManager.fileExistsAtPath(applicationDocumentsPath + "/homedirections/",isDirectory: &isDir) {
fileManager.createDirectoryAtPath(applicationDocumentsPath + "/homedirections/", withIntermediateDirectories: true, attributes: nil, error: nil)
}
NSUserDefaults.standardUserDefaults().setObject(remoteVersion, forKey: "HomeDirection")
self.getLatestSync(owner)
}else{
if(owner.delegate != nil){
owner.delegate.homeDirectionSync(owner, NeedRefresh: false)
}
}
}
},failure: {(error: NSError, response: HTTPResponse?) in
if(owner.delegate != nil){
owner.delegate.homeDirectionSync(owner, NeedRefresh: false)
}
})
}
//获取最新的文件
func getLatestSync(sender:HomeDirectionSync){
var request = HTTPTask()
request.download(sender.baseUrl+"latest.zip", parameters: nil, progress: {(complete: Double) in
}, success: {(response: HTTPResponse) in
if response.responseObject != nil {
//数据下载成功,将数据解压到用户牡蛎中
var zip = ZipArchive()
zip.UnzipOpenFile((response.responseObject! as! NSURL).path)
needRefresh=zip.UnzipFileTo(applicationDocumentsPath+"/homedirections/", overWrite: true)
if(needRefresh && sender.delegate != nil){//唯一的操作成功的返回
sender.delegate.homeDirectionSync(sender, NeedRefresh: true)
return
}
}
if(sender.delegate != nil){
sender.delegate.homeDirectionSync(sender, NeedRefresh: false)
}
} ,failure: {(error: NSError, response: HTTPResponse?) in
if(sender.delegate != nil){
sender.delegate.homeDirectionSync(sender, NeedRefresh: false)
}
})
}
/*
//分析文件,开始下载数据信息
func analysisDescription(tmpUrl:NSURL,MainThread sender:HomeDirectionSync){
let jsonData = NSData(contentsOfURL: tmpUrl)
let rootDescription = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
let version:NSString = rootDescription["version"] as NSString
NSUserDefaults.standardUserDefaults().setObject(version, forKey: "HomeDirection")
let databody:NSArray = rootDescription["data"] as NSArray
sender.subthread = databody.count
for item in databody {
var str=item["image"] as String
if(str != ""){
getImageSync(str,MainThread:sender)
}else{
sender.subthread--
}
}
}
//异步下载图片信息
func getImageSync(image:String,MainThread sender:HomeDirectionSync){
var request = HTTPTask()
request.download(sender.baseUrl+image, parameters: nil, progress: {(complete: Double) in
}, success: {(response: HTTPResponse) in
if response.responseObject != nil {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let newPath = NSURL(fileURLWithPath:applicationDocumentsPath+"/homedirections/"+image)
NSLog("\(newPath)")
let fileManager = NSFileManager.defaultManager()
fileManager.removeItemAtURL(newPath!, error: nil)
var error:NSError?=nil
if !fileManager.moveItemAtURL(response.responseObject! as NSURL, toURL: newPath!, error: &error) {
NSLog(error!.localizedDescription)
}
sender.subthread--
if(sender.subthread==0 && sender.delegate != nil){
sender.delegate.homeDirectionSync(sender, NeedRefresh: true)
}
}
} ,failure: {(error: NSError) in
if(sender.delegate != nil){
sender.delegate.homeDirectionSync(sender, NeedRefresh: false)
}
})
}
*/
}
| apache-2.0 | d78834242834f8904f521ba58796c225 | 40.033784 | 168 | 0.582085 | 4.91343 | false | false | false | false |
brave/browser-ios | Client/Frontend/Settings/SearchEnginePicker.swift | 1 | 2706 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
protocol SearchEnginePickerDelegate {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker, didSelectSearchEngine engine: OpenSearchEngine?, forType: DefaultEngineType?) -> Void
}
class SearchEnginePicker: UITableViewController {
var delegate: SearchEnginePickerDelegate?
var engines: [OpenSearchEngine]!
var selectedSearchEngineName: String?
var type: DefaultEngineType?
convenience init(type: DefaultEngineType) {
self.init(style: .plain)
self.type = type
}
override init(style: UITableViewStyle) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = Strings.DefaultSearchEngine
navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.Cancel, style: .plain, target: self, action: #selector(SearchEnginePicker.SELcancel))
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return engines.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let engine = engines[indexPath.item]
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize))
if engine.shortName == selectedSearchEngineName {
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let engine = engines[indexPath.item]
delegate?.searchEnginePicker(self, didSelectSearchEngine: engine, forType: type)
guard let cell = tableView.cellForRow(at: indexPath) else { return }
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
@objc func SELcancel() {
delegate?.searchEnginePicker(self, didSelectSearchEngine: nil, forType: nil)
}
}
| mpl-2.0 | 92d900b86f7a67edfa1ad2851063c947 | 38.794118 | 159 | 0.717664 | 5.274854 | false | false | false | false |
tredds/pixelthoughts | PixelThoughts/UIImage+Circle.swift | 1 | 1011 | //
// UIImage+Circle.swift
// PixelThoughts
//
// Created by Victor Tatarasanu on 22/12/15.
// Copyright © 2015 Victor Tatarasanu. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
public class func circle(size: CGSize, color: UIColor) -> UIImage? {
var circle = UIImage()
var onceToken : dispatch_once_t = 0
dispatch_once(&onceToken, {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let ctx = UIGraphicsGetCurrentContext();
let rect = CGRectMake(0, 0, size.width, size.height);
CGContextSaveGState(ctx);
CGContextSetFillColorWithColor(ctx, color.CGColor);
CGContextFillEllipseInRect(ctx, rect);
CGContextRestoreGState(ctx);
circle = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
})
return circle
}
} | mit | 0608f6e5ad39f254821c5d3faa89554a | 26.324324 | 72 | 0.589109 | 5.549451 | false | false | false | false |
danielpi/NSOutlineViewInSwift | NSOutlineViewInSwift/NSOutlineViewInSwift/ViewController.swift | 1 | 3134 | //
// ViewController.swift
// NSOutlineViewInSwift
//
// Created by Daniel Pink on 2/12/2014.
// Copyright (c) 2014 Electronic Innovations. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
outlineView.headerView = nil
}
}
// MARK:- Outline View Data Source
extension ViewController: NSOutlineViewDataSource {
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
// return (item == nil) ? [FileSystemItem rootItem] : [(FileSystemItem *)item childAtIndex:index];
guard let fileSystemItem = item as? FileSystemItem else {
print("child:ofItem: return the rootItem")
return FileSystemItem.rootItem
}
print("child: \(index) ofItem: \(fileSystemItem)")
return fileSystemItem.childAtIndex(index)!
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
// return (item == nil) ? YES : ([item numberOfChildren] != -1);
guard let fileSystemItem = item as? FileSystemItem else {
// This is the root item which is always expandable
return true
}
return fileSystemItem.numberOfChildren() > 0
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
// return (item == nil) ? 1 : [item numberOfChildren];
guard let fileSystemItem = item as? FileSystemItem else {
print("numberOfChildrenOfItem: We have been passed the root object so we return 1")
return 1
}
print("numberOfChildrenOfItem: \(fileSystemItem.numberOfChildren())")
return fileSystemItem.numberOfChildren()
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn: NSTableColumn?, byItem:AnyObject?) -> AnyObject? {
// return (item == nil) ? @"/" : [item relativePath];
guard let fileSystemItem = byItem as? FileSystemItem else {
return nil
}
print("objectValueForTableColumn:byItem: \(fileSystemItem)")
return fileSystemItem.relativePath
}
}
/*
@implementation DataSource
// Data Source methods
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
return (item == nil) ? 1 : [item numberOfChildren];
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
return (item == nil) ? YES : ([item numberOfChildren] != -1);
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
return (item == nil) ? [FileSystemItem rootItem] : [(FileSystemItem *)item childAtIndex:index];
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
return (item == nil) ? @"/" : [item relativePath];
}
@end
*/ | mit | af5befcd313418c47822b7033496dc22 | 29.735294 | 126 | 0.654116 | 4.927673 | false | false | false | false |
Ramesh-P/on-the-spot | On the Spot/AppDelegate.swift | 1 | 3717 | //
// AppDelegate.swift
// On the Spot
//
// Created by Ramesh Parthasarathy on 4/6/17.
// Copyright © 2017 Ramesh Parthasarathy. All rights reserved.
//
import UIKit
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let defaults = UserDefaults.standard
var searchNearby: Bool = Bool()
var distanceInMiles: Double = Double()
var searchRadius: CLLocationDistance = CLLocationDistance()
var googlePlaces: [GooglePlaces] = [GooglePlaces]()
let stack = CoreDataStack(modelName: "Model")!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Hide navigation bar border
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
// Hide tab bar border
UITabBar.appearance().clipsToBounds = true
// Enable Google Mobile Service (GMS)
GMSServices.provideAPIKey(Google.gmsKey)
//GMSServices.provideAPIKey(Google.ParameterValues.apiKey)
// Set UI object defaults
setDefaults()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
stack.saveContext()
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
stack.saveContext()
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
stack.saveContext()
}
// MARK: Application Functions
func setDefaults() {
// Initialize
if (defaults.value(forKey: "searchNearby") == nil) {
defaults.set(true, forKey: "searchNearby")
}
if (defaults.value(forKey: "distanceInMiles") == nil) {
defaults.set(5, forKey: "distanceInMiles")
}
// Set default values for search type & radius
searchNearby = defaults.bool(forKey: "searchNearby")
distanceInMiles = defaults.double(forKey: "distanceInMiles")
searchRadius = distanceInMiles * Constants.metersPerMile
}
}
| mit | 25fa53075feb1ea535ccbcfb797e0ccd | 39.835165 | 285 | 0.689182 | 5.488922 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Entertainment/View/PageContentView.swift | 2 | 7496 | //
// PageContentView.swift
// XMTV
//
// Created by Mac on 2017/1/11.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
//MARK:- 定义代理1
protocol PageContentViewDelegate :class {
func pageContentView(_ contentView : PageContentView, progress : CGFloat,sourceIndex :Int , targetIndex :Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// 默认控子制器
let defaultVcsCount = UserDefaults.standard.object(forKey: DEFAULT_CHILDVCS) as! Int
fileprivate var isForbidScrollDelegate : Bool = false
fileprivate var startOffsetX : CGFloat = 0
fileprivate var childVcs :[UIViewController]
//需要改成弱引用,否则有循环引用
fileprivate weak var parentVc : UIViewController?
//MARK:- 定义代理2
weak var delegate : PageContentViewDelegate?
// MARK:- 懒加载
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
//布局属性 大小 滚动方向 间距
layout.itemSize = (self?.bounds.size)!//使用[weak self] in 后: self.bounds.size => (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.isPagingEnabled = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
init(frame: CGRect,childVcs : [UIViewController],parentVc:UIViewController?) {
self.childVcs = childVcs
self.parentVc = parentVc //可选类型赋值给可选类型
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI(){
for childVc in childVcs {
parentVc?.addChildViewController(childVc)
}
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource数据源协议
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
//
for view in cell.contentView.subviews{
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK:- 遵守UICollectionViewDelegate代理
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//是点击传导过来的,则不处理
if isForbidScrollDelegate { return }
//滚动处理
var progress : CGFloat = 0
var sourceIndex :Int = 0
var targetIndex :Int = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX {
progress = currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW)
sourceIndex = Int(currentOffsetX/scrollViewW)
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//完全滑过去
if currentOffsetX - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
}else{
progress = 1 - (currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW))
targetIndex = Int(currentOffsetX/scrollViewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count{
sourceIndex = childVcs.count - 1
}
//完全划过去
if startOffsetX - currentOffsetX == scrollViewW {
sourceIndex = targetIndex
}
// print(">right>progress[\(progress)] sourceIndex[\(sourceIndex)] targetIndex[\(targetIndex)]")
}
//MARK:- 定义代理3
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK: - homevc作为Pageview的代理,再由homevc调用到这里
extension PageContentView {
func setCurrentIndex(currentIndex : Int){
isForbidScrollDelegate = true
let offsetX = CGFloat( currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false)
}
}
//MARK: - 公共方法,当添加或移除分类后,需要同步刷新PageContentView
extension PageContentView {
//MARK: - 刷新子控制器
public func reloadChildVcs(newChildVcs: [UIViewController]) {
print("newChildVcs-", newChildVcs)
if self.childVcs.count < (defaultVcsCount + newChildVcs.count) {
for childVc in newChildVcs {
self.childVcs.append(childVc)
parentVc?.addChildViewController(childVc)
}
} else {
let count = self.childVcs.count - (defaultVcsCount + newChildVcs.count)
updateChildVcs(count: count)
}
UserDefaults.standard.set(self.childVcs.count, forKey: HOME_CHILDVCS)
collectionView.reloadData()
}
//MARK: - 没有添加频道或者移除了所有的频道,回到默认状态
public func setDefaultChildVcs() {
// 移除 "精彩推荐"和"全部直播"两个频道之外的所有频道控制器
// 当前子控制器个数 - 默认子控制个数 = 需要移除控制器的个数
let counts = self.childVcs.count - defaultVcsCount
updateChildVcs(count: counts)
UserDefaults.standard.set(self.childVcs.count, forKey: HOME_CHILDVCS)
collectionView.reloadData()
}
//MARK: - 更新控制器
func updateChildVcs(count: Int) {
var i = 0
let lastChildVcsCount = UserDefaults.standard.object(forKey: HOME_CHILDVCS) as! Int
print("removecount-",count)
for _ in 0..<count {
self.childVcs.removeLast()
}
for childvc in (self.parentVc?.childViewControllers)! {
print("unremoveChildVC-",childvc)
print("i=", i)
if i > (lastChildVcsCount - count - 1) {
print("removechildVC",childvc)
childvc.removeFromParentViewController()
}
i += 1
}
for childs in self.childVcs {
parentVc?.addChildViewController(childs)
}
}
}
| apache-2.0 | d36781124bb1abfcb3736184091ab67d | 34.822335 | 121 | 0.642483 | 5.022776 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/Pods/Kingfisher/Sources/ImageCache.swift | 62 | 28527 | //
// ImageCache.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[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(macOS)
import AppKit
#else
import UIKit
#endif
public extension Notification.Name {
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it.
*/
public static var KingfisherDidCleanDiskCache = Notification.Name.init("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
}
/**
Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
*/
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
/// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
public typealias RetrieveImageDiskTask = DispatchWorkItem
/**
Cache type of a cached image.
- None: The image is not cached yet when retrieving it.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case none, memory, disk
}
/// `ImageCache` represents both the memory and disk cache system of Kingfisher.
/// While a default image cache object will be used if you prefer the extension methods of Kingfisher,
/// you can create your own cache object and configure it as your need. You could use an `ImageCache`
/// object to manipulate memory and disk cache for Kingfisher.
open class ImageCache {
//Memory
fileprivate let memoryCache = NSCache<NSString, AnyObject>()
/// The largest cache cost of memory cache. The total cost is pixel count of
/// all cached images in memory.
/// Default is unlimited. Memory cache will be purged automatically when a
/// memory warning notification is received.
open var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
fileprivate let ioQueue: DispatchQueue
fileprivate var fileManager: FileManager!
///The disk cache location.
open let diskCachePath: String
/// The default file extension appended to cached files.
open var pathExtension: String?
/// The longest time duration in second of the cache being stored in disk.
/// Default is 1 week (60 * 60 * 24 * 7 seconds).
open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
/// The largest disk size can be taken for the cache. It is the total
/// allocated size of cached files in bytes.
/// Default is no limit.
open var maxDiskCacheSize: UInt = 0
fileprivate let processQueue: DispatchQueue
/// The default cache.
public static let `default` = ImageCache(name: "default")
/// Closure that defines the disk cache path from a given path and cacheName.
public typealias DiskCachePathClosure = (String?, String) -> String
/// The default DiskCachePathClosure
public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String {
let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return (dstPath as NSString).appendingPathComponent(cacheName)
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
- parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name
appending to the cache path. This value should not be an empty string.
- parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value),
the `.cachesDirectory` in of your app will be used.
- parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates
the final disk cache path. You could use it to fully customize your cache path.
- returns: The cache object.
*/
public init(name: String,
path: String? = nil,
diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure)
{
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)"
memoryCache.name = cacheName
diskCachePath = diskCachePathClosure(path, cacheName)
let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)"
ioQueue = DispatchQueue(label: ioQueueName)
let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)"
processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent)
ioQueue.sync { fileManager = FileManager() }
#if !os(macOS) && !os(watchOS)
NotificationCenter.default.addObserver(
self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
NotificationCenter.default.addObserver(
self, selector: #selector(cleanExpiredDiskCache), name: .UIApplicationWillTerminate, object: nil)
NotificationCenter.default.addObserver(
self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Store & Remove
/**
Store an image to cache. It will be saved to both memory and disk. It is an async operation.
- parameter image: The image to be stored.
- parameter original: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- parameter key: Key for the image.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of
processor to it.
This identifier will be used to generate a corresponding key for the combination of `key` and processor.
- parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
- parameter completionHandler: Called when store operation completes.
*/
open func store(_ image: Image,
original: Data? = nil,
forKey key: String,
processorIdentifier identifier: String = "",
cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
toDisk: Bool = true,
completionHandler: (() -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf.imageCost)
func callHandlerInMainQueue() {
if let handler = completionHandler {
DispatchQueue.main.async {
handler()
}
}
}
if toDisk {
ioQueue.async {
if let data = serializer.data(with: image, original: original) {
if !self.fileManager.fileExists(atPath: self.diskCachePath) {
do {
try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil)
}
callHandlerInMainQueue()
}
} else {
callHandlerInMainQueue()
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation.
- parameter key: Key for the image.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
This identifier will be used to generate a corresponding key for the combination of `key` and processor.
- parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
- parameter completionHandler: Called when removal operation completes.
*/
open func removeImage(forKey key: String,
processorIdentifier identifier: String = "",
fromDisk: Bool = true,
completionHandler: (() -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
memoryCache.removeObject(forKey: computedKey as NSString)
func callHandlerInMainQueue() {
if let handler = completionHandler {
DispatchQueue.main.async {
handler()
}
}
}
if fromDisk {
ioQueue.async{
do {
try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey))
} catch _ {}
callHandlerInMainQueue()
}
} else {
callHandlerInMainQueue()
}
}
// MARK: - Get data from cache
/**
Get an image for a key from memory or disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- parameter completionHandler: Called when getting operation completes with image result and cached type of
this image. If there is no such key cached, the image will be `nil`.
- returns: The retrieving task.
*/
@discardableResult
open func retrieveImage(forKey key: String,
options: KingfisherOptionsInfo?,
completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask?
{
// No completion handler. Not start working and early return.
guard let completionHandler = completionHandler else {
return nil
}
var block: RetrieveImageDiskTask?
let options = options ?? KingfisherEmptyOptionsInfo
if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) {
options.callbackDispatchQueue.safeAsync {
completionHandler(image, .memory)
}
} else {
var sSelf: ImageCache! = self
block = DispatchWorkItem(block: {
// Begin to load image from disk
if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) {
if options.backgroundDecode {
sSelf.processQueue.async {
let result = image.kf.decoded(scale: options.scaleFactor)
sSelf.store(result,
forKey: key,
processorIdentifier: options.processor.identifier,
cacheSerializer: options.cacheSerializer,
toDisk: false,
completionHandler: nil)
options.callbackDispatchQueue.safeAsync {
completionHandler(result, .memory)
sSelf = nil
}
}
} else {
sSelf.store(image,
forKey: key,
processorIdentifier: options.processor.identifier,
cacheSerializer: options.cacheSerializer,
toDisk: false,
completionHandler: nil
)
options.callbackDispatchQueue.safeAsync {
completionHandler(image, .disk)
sSelf = nil
}
}
} else {
// No image found from either memory or disk
options.callbackDispatchQueue.safeAsync {
completionHandler(nil, .none)
sSelf = nil
}
}
})
sSelf.ioQueue.async(execute: block!)
}
return block
}
/**
Get an image for a key from memory.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
open func retrieveImageInMemoryCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
let options = options ?? KingfisherEmptyOptionsInfo
let computedKey = key.computedKey(with: options.processor.identifier)
return memoryCache.object(forKey: computedKey as NSString) as? Image
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
let options = options ?? KingfisherEmptyOptionsInfo
let computedKey = key.computedKey(with: options.processor.identifier)
return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options)
}
// MARK: - Clear & Clean
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is an async operation.
- parameter completionHander: Called after the operation completes.
*/
open func clearDiskCache(completion handler: (()->())? = nil) {
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.diskCachePath)
try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ { }
if let handler = handler {
DispatchQueue.main.async {
handler()
}
}
}
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc fileprivate func cleanExpiredDiskCache() {
cleanExpiredDiskCache(completion: nil)
}
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
open func cleanExpiredDiskCache(completion handler: (()->())? = nil) {
// Do things in cocurrent io queue
ioQueue.async {
var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItem(at: fileURL)
} catch _ { }
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
// Not valid date information. This should not happen. Just in case.
return true
}
for fileURL in sortedFiles {
do {
try self.fileManager.removeItem(at: fileURL)
} catch { }
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
diskCacheSize -= UInt(fileSize)
}
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async {
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map { $0.lastPathComponent }
NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
handler?()
}
}
}
fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
let diskCacheURL = URL(fileURLWithPath: diskCachePath)
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
let expiredDate = Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
var cachedFiles = [URL: URLResourceValues]()
var urlsToDelete = [URL]()
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumerator(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles, errorHandler: nil),
let urls = fileEnumerator.allObjects as? [URL]
{
for fileUrl in urls {
do {
let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys)
// If it is a Directory. Continue to next file URL.
if resourceValues.isDirectory == true {
continue
}
if !onlyForCacheSize {
// If this file is expired, add it to URLsToDelete
if let lastAccessData = resourceValues.contentAccessDate {
if (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate {
urlsToDelete.append(fileUrl)
continue
}
}
}
if let fileSize = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(fileSize)
if !onlyForCacheSize {
cachedFiles[fileUrl] = resourceValues
}
}
} catch _ { }
}
}
return (urlsToDelete, diskCacheSize, cachedFiles)
}
#if !os(macOS) && !os(watchOS)
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
// if 'sharedApplication()' is unavailable, then return
guard let sharedApplication = Kingfisher<UIApplication>.shared else { return }
func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
sharedApplication.endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = sharedApplication.beginBackgroundTask {
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCache {
endBackgroundTask(&backgroundTask!)
}
}
#endif
// MARK: - Check cache status
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
- parameter key: Key for the image.
- returns: The check result.
*/
open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult {
let computedKey = key.computedKey(with: identifier)
if memoryCache.object(forKey: computedKey as NSString) != nil {
return CacheCheckResult(cached: true, cacheType: .memory)
}
let filePath = cachePath(forComputedKey: computedKey)
var diskCached = false
ioQueue.sync {
diskCached = fileManager.fileExists(atPath: filePath)
}
if diskCached {
return CacheCheckResult(cached: true, cacheType: .disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
- parameter key: The key which is used for caching.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
- returns: Corresponding hash.
*/
open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String {
let computedKey = key.computedKey(with: identifier)
return cacheFileName(forComputedKey: computedKey)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
- parameter completionHandler: Called with the calculated size when finishes.
*/
open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) {
ioQueue.async {
let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
DispatchQueue.main.async {
handler(diskCacheSize)
}
}
}
/**
Get the cache path for the key.
It is useful for projects with UIWebView or anyone that needs access to the local file path.
i.e. Replace the `<img src='path_for_key'>` tag in your HTML.
- Note: This method does not guarantee there is an image already cached in the path. It just returns the path
that the image should be.
You could use `isImageCached(forKey:)` method to check whether the image is cached under that key.
*/
open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String {
let computedKey = key.computedKey(with: identifier)
return cachePath(forComputedKey: computedKey)
}
open func cachePath(forComputedKey key: String) -> String {
let fileName = cacheFileName(forComputedKey: key)
return (diskCachePath as NSString).appendingPathComponent(fileName)
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? {
if let data = diskImageData(forComputedKey: key) {
return serializer.image(with: data, options: options)
} else {
return nil
}
}
func diskImageData(forComputedKey key: String) -> Data? {
let filePath = cachePath(forComputedKey: key)
return (try? Data(contentsOf: URL(fileURLWithPath: filePath)))
}
func cacheFileName(forComputedKey key: String) -> String {
if let ext = self.pathExtension {
return (key.kf.md5 as NSString).appendingPathExtension(ext)!
}
return key.kf.md5
}
}
extension Kingfisher where Base: Image {
var imageCost: Int {
return images == nil ?
Int(size.height * size.width * scale * scale) :
Int(size.height * size.width * scale * scale) * images!.count
}
}
extension Dictionary {
func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
}
}
#if !os(macOS) && !os(watchOS)
// MARK: - For App Extensions
extension UIApplication: KingfisherCompatible { }
extension Kingfisher where Base: UIApplication {
public static var shared: UIApplication? {
let selector = NSSelectorFromString("sharedApplication")
guard Base.responds(to: selector) else { return nil }
return Base.perform(selector).takeUnretainedValue() as? UIApplication
}
}
#endif
extension String {
func computedKey(with identifier: String) -> String {
if identifier.isEmpty {
return self
} else {
return appending("@\(identifier)")
}
}
}
| apache-2.0 | 80f796f5532f8c5b594abb83ac1d9fe1 | 40.223988 | 276 | 0.59512 | 5.638861 | false | false | false | false |
coderwjq/swiftweibo | SwiftWeibo/SwiftWeibo/Classes/Home/PhotoBrowser/ProgressView.swift | 1 | 1083 | //
// ProgressView.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/11.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
class ProgressView: UIView {
// MARK:- 定义属性
var progress: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
// MARK:- 重写drawRect方法
override func draw(_ rect: CGRect) {
super.draw(rect)
// 获取参数
let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
let radius = rect.width * 0.5 - 3
let startAngle = CGFloat(-M_PI_2)
let endAngle = CGFloat(2 * M_PI) * progress + startAngle
// 创建贝塞尔曲线
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
// 绘制一条中心点的线
path.addLine(to: center)
path.close()
// 设置绘制的颜色
UIColor(white: 1.0, alpha: 0.4).setFill()
// 开始绘制
path.fill()
}
}
| apache-2.0 | 810173d4dfe76a6bada7d7399edd4409 | 22.302326 | 127 | 0.537924 | 3.809886 | false | false | false | false |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/AppDelegate.swift | 1 | 1317 | //
// AppDelegate.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/7.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 1.设置tabBar样式
setupTabbarStyle()
// 2.设置根控制器
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = MainController()
self.window?.makeKeyAndVisible()
return true
}
}
extension AppDelegate {
// 设置tabBar样式
func setupTabbarStyle() {
let tabBarItemAppearance = UITabBarItem.appearance()
let selectedTextAttrs = [ NSForegroundColorAttributeName : UIColor.orange, NSFontAttributeName : UIFont.systemFont(ofSize: 11) ]
let normalTextAttrs = [ NSForegroundColorAttributeName : UIColor.gray, NSFontAttributeName : UIFont.systemFont(ofSize: 11) ]
tabBarItemAppearance.setTitleTextAttributes(selectedTextAttrs, for: .selected)
tabBarItemAppearance.setTitleTextAttributes(normalTextAttrs, for: .normal)
}
}
| mit | 00aaf3234cd542b5f0361dd7bf5d9c74 | 26.826087 | 144 | 0.685938 | 5.099602 | false | false | false | false |
srn214/Floral | Floral/Pods/NVActivityIndicatorView/Source/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallZigZagDeflect.swift | 3 | 3688 | //
// NVActivityIndicatorAnimationBallZigZagDeflect.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallZigZagDeflect: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.75
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
#if swift(>=4.2)
animation.timingFunction = CAMediaTimingFunction(name: .linear)
#else
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
#endif
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))
]
animation.duration = duration
animation.repeatCount = HUGE
animation.autoreverses = true
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))
]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) {
let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | ea48b4a428a61fdc44b6b2332c5de80b | 43.97561 | 160 | 0.701735 | 4.680203 | false | false | false | false |
tekezo/Karabiner-Elements | src/apps/NotificationWindow/src/NotificationWindowManager.swift | 1 | 3273 | import SwiftUI
private func callback(_ filePath: UnsafePointer<Int8>?,
_ context: UnsafeMutableRawPointer?)
{
let path = String(cString: filePath!)
let obj: NotificationWindowManager! = unsafeBitCast(context, to: NotificationWindowManager.self)
let json = KarabinerKitJsonUtility.loadFile(path)
if let dictionary = json as? [String: Any] {
if let body = dictionary["body"] as? String {
DispatchQueue.main.async { [weak obj] in
guard let obj = obj else { return }
NotificationMessage.shared.text = body.trimmingCharacters(in: .whitespacesAndNewlines)
obj.updateWindowsVisibility()
}
}
}
}
public class NotificationWindowManager {
private var windows: [NSWindow] = []
private var observers = KarabinerKitSmartObserverContainer()
init() {
let center = NotificationCenter.default
let o = center.addObserver(forName: NSApplication.didChangeScreenParametersNotification,
object: nil,
queue: .main) { [weak self] _ in
guard let self = self else { return }
self.updateWindows()
}
observers.addObserver(o, notificationCenter: center)
updateWindows()
let obj = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
libkrbn_enable_notification_message_json_file_monitor(callback, obj)
}
deinit {
libkrbn_disable_notification_message_json_file_monitor()
}
func updateWindows() {
// The old window sometimes does not deallocated properly when screen count is decreased.
// Thus, we hide the window before clear windows.
windows.forEach {
w in w.orderOut(self)
}
windows.removeAll()
NSScreen.screens.forEach { screen in
let window = NSWindow(
contentRect: .zero,
styleMask: [
.fullSizeContentView,
],
backing: .buffered,
defer: false
)
window.contentView = NSHostingView(rootView: NotificationView(window: window))
window.backgroundColor = NSColor.clear
window.isOpaque = false
window.level = .statusBar
// window.ignoresMouseEvents = true
window.collectionBehavior.insert(.canJoinAllSpaces)
window.collectionBehavior.insert(.ignoresCycle)
window.collectionBehavior.insert(.stationary)
let screenFrame = screen.visibleFrame
let windowFrame = window.frame
let margin = CGFloat(10.0)
window.setFrameOrigin(NSMakePoint(
screenFrame.origin.x + screenFrame.size.width - windowFrame.width - margin,
screenFrame.origin.y + margin
))
windows.append(window)
}
updateWindowsVisibility()
}
func updateWindowsVisibility() {
let hide = NotificationMessage.shared.text.isEmpty
windows.forEach { w in
if hide {
w.orderOut(self)
} else {
w.orderFront(self)
}
}
}
}
| unlicense | 63f7cff3b2b2af86c6e454d508ba1090 | 31.73 | 102 | 0.586312 | 5.2368 | false | false | false | false |
lkzhao/Elastic | Examples/ElasticExamples/ViewController.swift | 1 | 2031 | //
// ViewController.swift
// ElasticExamples
//
// Created by Luke Zhao on 2017-01-20.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
import Elastic
import Hero
extension CGFloat {
static var random:CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static var random: UIColor {
return UIColor(red: .random/2 + 0.5,
green: .random/2 + 0.5,
blue: .random/2 + 0.5,
alpha: 1.0)
}
}
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var leftGR:UIScreenEdgePanGestureRecognizer!
var rightGR:UIScreenEdgePanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
ElasticHeroPlugin.enable()
view.backgroundColor = .random
rightGR = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(pan(gr:)))
rightGR.edges = UIRectEdge.right
view.addGestureRecognizer(rightGR)
leftGR = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(pan(gr:)))
leftGR.edges = UIRectEdge.left
view.addGestureRecognizer(leftGR)
label.heroModifiers = [.fade, .scale(0.5)]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let count = navigationController!.childViewControllers.count
label.text = "\(count)"
title = "\(count)"
}
func pan(gr:UIScreenEdgePanGestureRecognizer){
if gr.edges == .right && gr.state == .began {
performSegue(withIdentifier: "next", sender: nil)
}
if gr.edges == .left && gr.state == .began && navigationController!.viewControllers.count > 1 {
view.heroModifiers = [.elastic(edge: .left, gestureRecognizer: leftGR)]
let _ = navigationController?.popViewController(animated: true)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination
vc.view.heroModifiers = [.elastic(edge: .right, gestureRecognizer: rightGR)]
}
}
| mit | 0ad2ef2f8d80092e4e3194f4aecebf3b | 27.194444 | 99 | 0.673892 | 4.255765 | false | false | false | false |
odin2505/Bransoletka | Bransoletka/Models/MinuteMeasurements.swift | 1 | 1708 | //
// MinuteMeasurements.swift
// Bransoletka
//
// Created by Sauron Black on 5/4/15.
// Copyright (c) 2015 Totenkopf. All rights reserved.
//
import Foundation
class MinuteMeasurements: DayMeasurements
{
var sleepMode = false
init(minuteData: NSData) {
super.init()
date = self.dateWithData(minuteData)
var sleepMode = 0
minuteData.getBytes(&sleepMode, range: NSMakeRange(6, 1))
minuteData.getBytes(&steps, range: NSMakeRange(7, 2))
minuteData.getBytes(&distance, range: NSMakeRange(9, 2))
minuteData.getBytes(&calories, range: NSMakeRange(11, 1))
distance = Int(Double(distance) * Constants.MeterCoefficient)
calories = Int(Double(calories) * Constants.CaloriesCoefficient)
self.sleepMode = Bool(sleepMode)
}
override func dateWithData(data: NSData) -> NSDate? {
var minute = 0, hour = 0, day = 0, month = 0, year = 0
data.getBytes(&minute, range: NSMakeRange(1, 1))
data.getBytes(&hour, range: NSMakeRange(2, 1))
data.getBytes(&day, range: NSMakeRange(3, 1))
data.getBytes(&month, range: NSMakeRange(4, 1))
data.getBytes(&year, range: NSMakeRange(5, 1))
let dateComponents = NSDateComponents()
dateComponents.minute = minute
dateComponents.hour = hour
dateComponents.day = day + 1
dateComponents.month = month + 1
dateComponents.year = year + Constants.YearOffset
return NSCalendar.currentCalendar().dateFromComponents(dateComponents)
}
override var description: String {
return super.description + "Sleep Mode = \(sleepMode)"
}
} | mit | d3e18e430ad646fa3047a4c1c8682b5d | 31.865385 | 78 | 0.637002 | 4.217284 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/best-time-to-buy-and-sell-stock-iii.swift | 2 | 1899 | /**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
*
*
*/
// Date: Mon Jun 1 11:57:15 PDT 2020
class Solution {
/// dp[k, i] = max(dp[k, i-1], prices[i] - prices[j] + dp[k-1, j-1]), j=[0..i-1]
/// - Complexity:
/// - Time: O(k*n*n), k is the number of trasactions, and n is the number of elements in prices array.
/// - Space: O(k*n)
///
func maxProfit(_ prices: [Int]) -> Int {
let n = prices.count
let k = 2
guard n > 1 else { return 0 }
var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: k + 1)
for kk in 1 ... k {
for sell in 2 ... n {
dp[kk][sell] = dp[kk][sell - 1]
for buy in 1 ..< sell {
dp[kk][sell] = max(dp[kk][sell], prices[sell - 1] - prices[buy - 1] + dp[kk - 1][buy - 1])
}
}
}
// print("\(dp)")
return max(dp[k][n], dp[k - 1][n])
}
}
class Solution {
/// dp[k, i] = max(dp[k, i-1], prices[i] - prices[j] + dp[k-1, j-1]), j=[0..i-1]
///
/// tmpMin has been repeatedly calculated.
/// - Complexity:
/// - Time: O(k*n), k is the number of trasactions, and n is the number of elements in prices array.
/// - Space: O(k*n)
///
func maxProfit(_ prices: [Int]) -> Int {
let n = prices.count
let k = 2
guard n > 1 else { return 0 }
var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: k + 1)
for kk in 1 ... k {
var tmpMin = prices[0] - dp[kk - 1][0]
for sell in 2 ... n {
tmpMin = min(tmpMin, prices[sell - 1] - dp[kk - 1][sell - 1])
dp[kk][sell] = max(dp[kk][sell - 1], prices[sell - 1] - tmpMin)
}
}
// print("\(dp)")
return max(dp[k][n], dp[k - 1][n])
}
}
| mit | 97385939ae4620bc05e91c4565d7fe25 | 34.166667 | 110 | 0.458136 | 3.043269 | false | false | false | false |
sgr-ksmt/SUSwiftSugar | SUSwiftSugar/Extensions/UIKit/UIViewExtensions.swift | 1 | 5622 | //
// UIViewExtensions.swift
import Foundation
import UIKit
public extension UIView {
public convenience init(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) {
self.init(frame: CGRect(x, y, width, height))
}
public var x: CGFloat {
get {
return frame.origin.x
}
set {
frame = CGRect(CGPoint(newValue, y), size)
}
}
public var y: CGFloat {
get {
return frame.origin.y
}
set {
frame = CGRect(CGPoint(x, newValue), size)
}
}
public var width: CGFloat {
get {
return frame.size.width
}
set {
frame = CGRect(origin, CGSize(newValue, height))
}
}
public var height: CGFloat {
get {
return frame.size.height
}
set {
frame = CGRect(origin, CGSize(width, newValue))
}
}
public var origin: CGPoint {
get {
return frame.origin
}
set {
frame = CGRect(newValue, size)
}
}
public var size: CGSize {
get {
return frame.size
}
set {
frame = CGRect(origin, newValue)
}
}
public var top: CGFloat {
get {
return y
}
set {
y = newValue
}
}
public var bottom: CGFloat {
get {
return y + height
}
set {
y = newValue - height
}
}
public var left: CGFloat {
get {
return x
}
set {
x = newValue
}
}
public var right: CGFloat {
get {
return x + width
}
set {
x = newValue - width
}
}
@nonobjc public var center: CGPoint {
get {
return CGPoint(frame.midX, frame.midY)
}
set {
self.frame = CGRect(
CGPoint(
newValue.x - width / 2,
newValue.y - height / 2
),
size
)
}
}
public var centerX: CGFloat {
get {
return frame.midX
}
set {
self.center = CGPoint(newValue, centerY)
}
}
public var centerY: CGFloat {
get {
return frame.midY
}
set {
self.center = CGPoint(centerX, newValue)
}
}
}
public extension UIView {
public func setCornerRadius(radius radius: CGFloat) {
layer.cornerRadius = radius
layer.masksToBounds = true
}
public func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(radius, radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
layer.mask = mask
}
public func setShadow(offset offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.shadowColor = color.CGColor
guard let cornerRadius = cornerRadius else { return }
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
}
}
public extension UIView {
public func to_image() -> UIImage {
return to_image(bounds)
}
public func to_image(scale: CGFloat) -> UIImage {
return to_image(bounds, scale: scale)
}
public func to_image(rect: CGRect, scale: CGFloat = UIScreen.mainScreen().scale) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
let context = UIGraphicsGetCurrentContext()!
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y)
layer.renderInContext(context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// //TODO: change if needed?
// drawViewHierarchyInRect(rect, afterScreenUpdates: false)
// let img = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
return img
}
}
public enum FadeAnimationType: NSTimeInterval {
case Fast = 0.15
case Normal = 0.35
case Slow = 1.0
}
public extension UIView {
public func fadeIn(type type: FadeAnimationType = .Normal, completion: (() -> Void)? = nil) {
fadeIn(duration: type.rawValue, completion: completion)
}
public func fadeIn(duration duration: NSTimeInterval, completion: (() -> Void)? = nil) {
alpha = 0.0
hidden = false
UIView.animateWithDuration(duration, animations: { [weak self] in
self?.alpha = 1.0
}) { _ in
completion?()
}
}
public func fadeOut(completion: (() -> Void)) {
fadeOut(type: .Normal, completion: completion)
}
public func fadeOut(type type: FadeAnimationType = .Normal, completion: (() -> Void)? = nil) {
fadeOut(duration: type.rawValue, completion: completion)
}
public func fadeOut(duration duration: NSTimeInterval, completion: (() -> Void)? = nil) {
UIView.animateWithDuration(duration, animations: { [weak self] in
self?.alpha = 0
}) { [weak self] finished in
self?.hidden = true
self?.alpha = 1
completion?()
}
}
} | mit | 41883bacfaaed541dba5cf3440ee856b | 24.443439 | 129 | 0.533796 | 4.83405 | false | false | false | false |
alexcomu/swift3-tutorial | 12-webRequest/12-webRequest/MainVC.swift | 1 | 3821 | //
// MainVC.swift
// 12-webRequest
//
// Created by Alex Comunian on 19/01/17.
// Copyright © 2017 Alex Comunian. All rights reserved.
//
import UIKit
import Alamofire
import CoreLocation
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var weatherImage: UIImageView!
@IBOutlet weak var weatherLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let locationManager = CLLocationManager()
var currentLocation: CLLocation!
var currentWeather: CurrentWeather!
var forecasts = [Forecast]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
func locationAuthStatus(){
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
currentLocation = locationManager.location
Location.sharedInstance.latitude = currentLocation.coordinate.latitude
Location.sharedInstance.longitude = currentLocation.coordinate.longitude
currentWeather = CurrentWeather()
currentWeather.downloadWeatherDetails {
self.downloadForecastData() {
self.updateMainUI()
}
}
}else{
locationManager.requestWhenInUseAuthorization()
locationAuthStatus()
}
}
func downloadForecastData(completed: @escaping DownloadComplete){
let forecastURL = URL(string: FOREACAST_WEATHER_URL)!
Alamofire.request(forecastURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject>{
if let list = dict["list"] as? [Dictionary<String, AnyObject>]{
for obj in list{
let forecast = Forecast(weatherDict: obj)
self.forecasts.append(forecast)
}
self.forecasts.remove(at: 0) // removing Today
self.tableView.reloadData()
}
}
completed()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecasts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "weatherCell", for: indexPath) as? WeatherCell{
let forecast = forecasts[indexPath.row]
cell.configureCell(forecast: forecast)
return cell
}
return WeatherCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func updateMainUI(){
dateLabel.text = currentWeather.date
temperatureLabel.text = "\(currentWeather.currentTemp)°"
cityLabel.text = currentWeather.cityName
weatherLabel.text = currentWeather.weatherType
weatherImage.image = UIImage(named: currentWeather.weatherType)
}
}
| mit | 125215237e61f8c0baccd36b6c706f3c | 29.798387 | 115 | 0.626866 | 5.957878 | false | false | false | false |
Paladinfeng/Weibo-Swift | Weibo/Weibo/Classes/Tools/Extension/UIView+IBExtension.swift | 1 | 1653 | //
// UIView+IBExtension.swift
// Weibo
//
// Created by Paladinfeng on 15/12/6.
// Copyright © 2015年 Paladinfeng. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get{
return layer.cornerRadius
}
set{
layer.cornerRadius = newValue
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get{
return layer.borderWidth
}
set{
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get{
guard let c = layer.borderColor else{
return nil
}
return UIColor(CGColor: c)
}
set{
layer.borderColor = newValue?.CGColor
}
}
// @IBInspectable var cornerRadius: CGFloat {
// get{
// return layer.cornerRadius
// }
// set{
// layer.cornerRadius = newValue
// layer.masksToBounds = cornerRadius > 0
// }
// }
//
// @IBInspectable var borderColor: UIColor? {
// get{
// guard let c = layer.borderColor else {
// return nil
// }
// return UIColor(CGColor: c)
// }
// set{
// layer.borderColor = newValue?.CGColor
// }
// }
//
//borderWidth
// @IBInspectable var borderWidth: CGFloat {
// get{
// return layer.borderWidth
// }
// set{
// layer.borderWidth = newValue
// }
// }
}
| mit | 248c040c5a1374006861c6cb701cc664 | 21 | 55 | 0.487879 | 4.520548 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/keyboardTest/AddressBookModel.swift | 1 | 3053 | //
// AddressBookModel.swift
// keyboardTest
//
// Created by Sean McGee on 10/20/15.
// Copyright © 2015 Kannuu. All rights reserved.
//
import UIKit
import RealmSwift
import AddressBook
import AddressBookUI
class AddressBookModel: NSObject {
var adbk: ABAddressBook!
lazy var queue = NSOperationQueue()
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "determineStatus", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "synchronize", name: "AddressBookDidChangeExternallyNotification", object: nil)
}
private func createAddressBook() -> Bool {
if self.adbk != nil {
return true
}
var err : Unmanaged<CFError>? = nil
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
if adbk == nil {
print(err)
self.adbk = nil
return false
}
self.adbk = adbk
return true
}
func determineStatus() -> Bool {
let status = ABAddressBookGetAuthorizationStatus()
switch status {
case .Authorized:
return self.createAddressBook()
case .NotDetermined:
var ok = false
ABAddressBookRequestAccessWithCompletion(nil) {[unowned self]
(granted:Bool, err:CFError!) in
dispatch_async(dispatch_get_main_queue()) {
if granted {
ok = self.createAddressBook()
// Register external change callback
registerExternalChangeCallbackForAddressBook(self.adbk)
self.synchronize()
}
}
}
if ok == true {
return true
}
self.adbk = nil
return false
case .Restricted:
self.adbk = nil
return false
case .Denied:
let alert = UIAlertController(title: "Need Authorization", message: "Wouldn't you like to authorize this app to use your Contacts?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {
_ in
let url = NSURL(string:UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
}))
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated:true, completion:nil)
self.adbk = nil
return false
}
}
func synchronize() {
if !self.determineStatus() {
print("not authorized")
return
}
let op = SyncAddressBookContactsOperation()
queue.addOperation(op)
}
}
| mit | 2e37d62aafc2abb96fa12e74c787feac | 32.538462 | 168 | 0.576999 | 5.382716 | false | false | false | false |
deekshibellare/AwesomeCharts | AwesomeCharts.playground/Sources/Partition.swift | 1 | 1137 | import Foundation
import UIKit
public struct PieChartPartition {
var name:String
var percentage:Float
var color: UIColor
var totalAngle:Float {
get{
return 360 * percentage / 100;
}
}
public init(name:String,percentage:Float,color:UIColor)
{
self.name = name;
self.percentage = percentage;
self.color = color;
}
}
extension PieChartPartition: CustomPlaygroundQuickLookable {
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
let containerView = UIView(frame: CGRectMake(0, 0, 400, 400))
let pichart = AwesomeChart(frame: containerView.bounds)
containerView.addSubview(pichart)
let label = UILabel(frame: CGRectMake(0,0,100,100))
label.text = self.name
label.font = UIFont.systemFontOfSize(25)
label.textColor = self.color
containerView.addSubview(label)
pichart.partitions = [self]
pichart.chartType = .Donut2DPercentageIndicator
pichart.render()
return PlaygroundQuickLook(reflecting: containerView)
}
} | mit | 9db27228e6c32a569d0eed3ed6382df1 | 28.179487 | 69 | 0.646438 | 4.640816 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.