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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/android-auto-companion-ios | Sources/AndroidAutoLogger/LogRecord.swift | 1 | 4533 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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
/// `LogRecord` is a snapshot for a log message.
///
/// All properties are values captured when the snapshot was recorded.
@available(macOS 10.15, *)
@dynamicMemberLookup
public struct LogRecord {
/// The logger which recorded this record.
let logger: Logger
/// The time when the snapshot was recorded.
let timestamp: Date
/// The timezone when the snapshot was recorded.
let timezone: TimeZone
/// The process identifier.
let processId: Int32 // Type matches ProcessInfo.processIdentifier.
/// The name of the process.
let processName: String
/// The thread on which the logger was called to record the message.
let threadId: Int
/// The source file where the logger was called to record the message.
let file: String
/// The line in the source file where the logger was called to record the message.
let line: Int
/// The function in which the logger was called to record the message.
let function: String
/// Optional stack trace symbols provided for fault logs.
let backTrace: [String]?
/// The message that was specified to be logged.
let message: String
/// Optional message to be redacted and appended after the primary message in output.
let redactableMessage: String?
/// Optional, custom metadata.
let metadata: [String: LogMetaData]?
/// Surface the logger properties to this record.
public subscript<T>(dynamicMember keyPath: KeyPath<Logger, T>) -> T {
logger[keyPath: keyPath]
}
}
// MARK - Implement `Encodable` conformance.
@available(macOS 10.15, *)
extension LogRecord: Encodable {
/// Coding keys for the record's properties.
enum CodingKeys: String, CodingKey {
case timestamp
case processId
case processName
case threadId
case file
case line
case function
case backTrace
case message
case subsystem
case category
case level
case metadata
}
/// Encode the record to the specified encoder.
///
/// Note that to respect privacy, `redactableMessage` will not be encoded.
/// - Parameter encoder: The encoder to which to encode the record.
/// - Throws: An error if a property fails to be encoded.
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(timestamp.encodeForLog(timezone: timezone), forKey: .timestamp)
try container.encode(processId, forKey: .processId)
try container.encode(processName, forKey: .processName)
try container.encode(threadId, forKey: .threadId)
try container.encode(file, forKey: .file)
try container.encode(line, forKey: .line)
try container.encode(function, forKey: .function)
try container.encode(backTrace, forKey: .backTrace)
try container.encode(message, forKey: .message)
try container.encode(self.subsystem, forKey: .subsystem)
try container.encode(self.category, forKey: .category)
try container.encode(self.level, forKey: .level)
if let metadata = metadata {
var metadataContainer = container.nestedContainer(
keyedBy: MetadataCodingKey.self, forKey: .metadata)
try encodeMetadata(metadata, to: &metadataContainer)
}
}
}
// MARK - Encode timestamp.
extension Date {
/// Encode a timestamp to a string which includes the date, time with milliseconds and the
/// timezone offset from UTC.
///
/// Generates an econding formatted such as: "2020-06-26T10:06:41.363-0700".
///
/// - Parameter timezone: The timezone to output in the encoding.
/// - Returns: The encoded timestamp.
func encodeForLog(timezone: TimeZone) -> String {
// See: https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.timeZone = timezone
return formatter.string(from: self)
}
}
| apache-2.0 | 9d4038883b92d512bf59a3b02e427d53 | 32.828358 | 92 | 0.717185 | 4.268362 | false | false | false | false |
pasmall/WeTeam | WeTools/WeTools/ViewController/Mine/MineViewController.swift | 1 | 5663 | //
// MineViewController.swift
// WeTools
//
// Created by lhtb on 16/11/8.
// Copyright © 2016年 lhtb. All rights reserved.
//
import UIKit
class MineViewController: BaseViewController , UICollectionViewDelegate , UICollectionViewDataSource{
let header = "headcell"
let footer = "footercell"
let user_icon = UIImageView(frame: CGRect.init(x: 20, y: 64, width: 64, height: 64))
var imgArr = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
view.backgroundColor = backColor
getData()
setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getData () {
imgArr = [ ["mine_download" , "mine_history" , "mine_favourite" , "home_region_icon_153" , "mine_pocketcenter","home_region_icon_153" ,"mine_theme"] , ["mine_systemNotification" , "mine_shakeMe","mine_systemNotification" , "mine_shakeMe","mine_systemNotification" ]]
}
func setUI() {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 164))
view.addSubview(headerView)
//头像设置
user_icon.layer.cornerRadius = 32
user_icon.layer.masksToBounds = true
user_icon.image = UIImage(named: "icon")
user_icon.contentMode = .scaleAspectFit
headerView.addSubview(user_icon)
let layout = UICollectionViewFlowLayout()
layout.headerReferenceSize = CGSize.init(width: SCREEN_WIDTH, height: 44)
layout.footerReferenceSize = CGSize.init(width: SCREEN_WIDTH, height: 21)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize.init(width: SCREEN_WIDTH / 4.0, height: 110)
let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 164, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 164 - 49), collectionViewLayout:layout )
let cellNib = UINib(nibName: "MineCollectionViewCell", bundle: nil)
collectionView.register(cellNib, forCellWithReuseIdentifier: "myCell")
collectionView.register(TitleView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: header)
collectionView.register(TitleView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footer)
collectionView.backgroundColor = backColor
collectionView.delegate = self
collectionView.dataSource = self
self.view.addSubview(collectionView)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let arr = [ 8 , 8 ]
return arr[section]
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MineCollectionViewCell
cell.layer.borderWidth = 0.5
cell.layer.borderColor = backColor.cgColor
if indexPath.section == 0 {
if indexPath.row < 7 {
cell.img.image = UIImage(named: imgArr[indexPath.section][indexPath.row])
} else {
cell.img.isHidden = true
cell.titlelab.isHidden = true
}
} else {
if indexPath.row < 5 {
cell.img.image = UIImage(named: imgArr[indexPath.section][indexPath.row])
}else{
cell.img.isHidden = true
cell.titlelab.isHidden = true
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var kindView : UICollectionReusableView!
if(kind == UICollectionElementKindSectionHeader){
kindView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: header, for: indexPath)
let view0 = kindView.viewWithTag(0)
view0?.backgroundColor = UIColor.white
let lab1 = kindView.viewWithTag(1) as! UILabel
lab1.font = UIFont.systemFont(ofSize: 15)
lab1.frame = CGRect.init(x: 20, y: 0, width: SCREEN_WIDTH, height: 44)
if indexPath.section == 0 {
lab1.text = "个人中心"
} else {
lab1.text = "我的消息"
}
}else if(kind == UICollectionElementKindSectionFooter){
kindView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footer, for: indexPath)
}
return kindView
}
}
class TitleView: UICollectionReusableView {
var nameLab :UILabel! = nil
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
nameLab = UILabel()
nameLab.tag = 1
self.addSubview(nameLab)
}
}
| apache-2.0 | b8c1e3822994eef9fc73fe333a7b86d3 | 32.748503 | 274 | 0.60912 | 5.223355 | false | false | false | false |
asp2insp/CodePathFinalProject | Pretto/Event.swift | 1 | 7801 | //
// Event.swift
// Pretto
//
// Created by Josiah Gaskin on 6/6/15.
// Copyright (c) 2015 Pretto. All rights reserved.
//
import Foundation
import CoreLocation
private let kClassName = "Event"
private let kEventTitleKey = "title"
internal let kEventStartDateKey = "startDate"
internal let kEventEndDateKey = "endDate"
internal let kOrderedByNewestFirst = "newestFirst"
private let kEventCoverPhotoKey = "coverPhoto"
private let kEventOwnerKey = "owner"
private let kEventPincodeKey = "pincode"
private let kEventLatitudeKey = "latitude"
private let kEventLongitudeKey = "longitude"
private let kEventLocationNameKey = "locationName"
private let kEventAdminsKey = "admins"
private let kEventGuestsKey = "guests"
private let kEventChannelKey = "channel"
internal let kEventIsPublicKey = "isPublic"
class Event : PFObject, PFSubclassing {
static let sDateFormatter = NSDateFormatter()
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
static func parseClassName() -> String {
return kClassName
}
@NSManaged var title : String
@NSManaged var coverPhoto : PFFile?
@NSManaged var startDate : NSDate
@NSManaged var endDate : NSDate
@NSManaged var owner : PFUser?
@NSManaged var pincode : String?
@NSManaged var geoPoint : PFGeoPoint
@NSManaged var latitude : Double
@NSManaged var longitude : Double
@NSManaged var locationName : String?
@NSManaged var admins : [PFUser]?
@NSManaged var guests : [PFUser]?
@NSManaged var channel : String?
@NSManaged var visibility : String?
// TODO - support more than one album per event, right now we're going
// to have a 1:1 mapping
@NSManaged var albums : [Album]
var isLive : Bool {
let now = NSDate()
let afterStart = startDate.compare(now) == NSComparisonResult.OrderedAscending
let beforeEnd = now.compare(endDate) == NSComparisonResult.OrderedAscending
return afterStart && beforeEnd
}
override init() {
super.init()
}
init?(dictionary: NSDictionary) {
super.init()
if let title = dictionary[kEventTitleKey] as? String {
self.title = title
} else {
return nil
}
if let startDate = dictionary[kEventStartDateKey] as? NSDate {
self.startDate = startDate
} else {
return nil
}
if let endDate = dictionary[kEventEndDateKey] as? NSDate {
self.endDate = endDate
} else {
return nil
}
if let owner = dictionary[kEventOwnerKey] as? PFUser {
self.owner = owner
} else {
return nil
}
self.coverPhoto = dictionary[kEventCoverPhotoKey] as? PFFile
self.pincode = dictionary[kEventPincodeKey] as? String
self.latitude = dictionary[kEventLatitudeKey] as! Double
self.longitude = dictionary[kEventLongitudeKey] as! Double
self.geoPoint = PFGeoPoint(latitude: self.latitude, longitude: self.longitude)
self.admins = dictionary[kEventAdminsKey] as? [PFUser]
self.guests = dictionary[kEventGuestsKey] as? [PFUser]
self.channel = dictionary[kEventChannelKey] as? String
self.visibility = dictionary[kEventIsPublicKey] as? String ?? "private"
}
func getAllPhotosInEvent(orderedBy: String?, block: ([Photo] -> Void)) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var photos : Array<Photo> = []
for album in self.albums {
// album.fetchIfNeeded()
album.fetch()
for p in album.photos ?? [] {
SwiftTryCatch.try({ p.fetchIfNeeded() }, catch: nil, finally: nil)
photos.append(p)
}
}
let order = orderedBy ?? ""
switch order {
case kOrderedByNewestFirst:
photos.sort {(a: Photo, b: Photo) -> Bool in
let aCreated = a.createdAt ?? NSDate.distantPast() as! NSDate
let bCreated = b.createdAt ?? NSDate.distantPast() as! NSDate
return aCreated.compare(bCreated) == NSComparisonResult.OrderedDescending
}
default:
break
}
dispatch_async(dispatch_get_main_queue()) {
block(photos)
}
}
}
func addImageToEvent(image: Photo) {
let album = self.albums[0]
album.addPhoto(image)
}
func getInvitation() -> Invitation {
let query = PFQuery(className:"Invitation", predicate: nil)
query.whereKey("event", equalTo: self)
query.whereKey("to", equalTo: PFUser.currentUser()!)
let objects = query.findObjects()
return objects![0] as! Invitation
}
func makeInvitationForUser(user: PFUser) -> Invitation {
let invitation = Invitation()
invitation.from = self.owner!
invitation.to = user
invitation.paused = false
invitation.event = self
invitation.accepted = false
invitation.lastUpdated = NSDate()
sendInvitationNotification(invitation)
return invitation
}
func acceptFromMapView() -> Invitation {
let invitation = Invitation()
invitation.from = self.owner!
invitation.to = PFUser.currentUser()!
invitation.paused = false
invitation.event = self
invitation.accepted = true
invitation.lastUpdated = NSDate()
return invitation
}
func sendInvitationNotification(invite: Invitation) {
println("Sending Push")
if invite.from != invite.to {
var pushQuery: PFQuery = PFInstallation.query()!
pushQuery.whereKey("deviceType", equalTo: "ios")
pushQuery.whereKey("user", equalTo: invite.to)
let myString = User.currentUser!.name! + " invited you to an event"
let data = ["alert" : myString, "badge" : "Increment"]
let push = PFPush()
push.setData(data)
push.setQuery(pushQuery)
push.sendPushInBackground()
}
}
class func getNearbyEvents(location: CLLocationCoordinate2D, callback:([Event]->Void)) {
let userGeoPoint = PFGeoPoint(latitude: location.latitude, longitude: location.longitude)
var query = PFQuery(className: kClassName)
query.whereKey("geoPoint", nearGeoPoint: userGeoPoint, withinMiles:1.0)
query.whereKey("visibility", equalTo: "public")
query.whereKey(kEventEndDateKey, greaterThan: NSDate())
query.whereKey(kEventStartDateKey, lessThan: NSDate())
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if let events = objects as? [Event] {
callback(events)
return
}
}
callback([])
}
}
// class func createEventPushChannel() -> String {
// dateFormatter.dateFormat = "MMyMhmMdyMyymhy" // just to mix things up a little ;)
// let channelId = "\(PFUser.currentUser()!.objectId!)" + "\(dateFormatter.stringFromDate(NSDate()))"
//
// let currentInstallation = PFInstallation.currentInstallation()
// currentInstallation.addUniqueObject(channelId, forKey: "channels")
// currentInstallation.saveInBackground()
//
// return channelId
// }
} | mit | 4efe12989439455bc2fbb2503f29baac | 33.986547 | 108 | 0.606973 | 4.688101 | false | false | false | false |
IBM-MIL/WatsonWeatherBot | Config/Configuration-Sample.swift | 1 | 1543 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Configuration settings for integration services
*/
public struct Configuration {
/// Latitude and longitude. ex. "30.401633699999998,-97.7143924"
static let staticGeocode = ""
/// Token assigned automatically from the 'Slash Commands' integration
static let slackToken = ""
/// Natural language classifier ID. You get this after training your classifier
static let classifierID = ""
/**
* You can obtain the below information after your app has been deployed by
* running `cf env`
*/
/// Username for Weather Insights service
static let weatherUsername = ""
/// Username for Weather Insights service
static let weatherPassword = ""
/// Username for Watson Natural Language Classifier service
static let naturalLanguageClassifierUsername = ""
/// Username for Watson Natural Language Classifier service
static let naturalLanguageClassifierPassword = ""
}
| apache-2.0 | 65b2e30c4c6792bf20e135b56156fbd7 | 29.86 | 83 | 0.719378 | 4.791925 | false | false | false | false |
lucasmpaim/EasyRest | Sources/EasyRest/Classes/Interceptors/LoggerInterceptor.swift | 1 | 3134 | //
// LoggerInterceptor.swift
// RestClient
//
// Created by Guizion Labs on 11/03/16.
// Copyright © 2016 Guizion Labs. All rights reserved.
//
import Foundation
import Alamofire
class LoggerInterceptor : Interceptor {
weak var bodyParams: AnyObject?
required init() {}
func requestInterceptor<T: Codable>(_ api: API<T>) {
self.bodyParams = api.bodyParams as AnyObject?
}
func responseInterceptor<T: Codable, U>(_ api: API<T>, response: DataResponse<U>) {
if let _ = response.result.value {
if (response.response?.statusCode)! >= 200 && (response.response?.statusCode)! <= 399 {
self.logSucess(api, response: response)
}else{
self.logError(api, response: response)
}
}else{
self.logError(api, response: response)
}
}
func logSucess<T: Codable, U>(_ api: API<T>, response: DataResponse<U>){
api.logger?.info("==============================================================================")
api.logger?.info("request URI: \(response.request!.httpMethod!) \(String(describing: response.request!.url))")
api.logger?.info("request headers:\n\(response.request!.allHTTPHeaderFields!)")
if let bodyParams = self.bodyParams {
api.logger?.info("request body:\n\(bodyParams)")
}
api.logger?.info("==============================================================================")
api.logger?.info("response status code: \(response.response!.statusCode)")
api.logger?.info("response headers:\n\(response.response!.allHeaderFields)")
if let value = response.result.value {
api.logger?.info("response body:\n\(value)")
}
api.logger?.info("==============================================================================")
}
func logError<T: Codable, U>(_ api: API<T>, response: DataResponse<U>) {
api.logger?.error("==============================================================================")
api.logger?.error("request URI: \(response.request!.httpMethod!) \(String(describing: response.request!.url))")
api.logger?.error("request headers:\n\(response.request!.allHTTPHeaderFields!)")
if let bodyParams = self.bodyParams {
api.logger?.info("request body:\n\(bodyParams)")
}
api.logger?.error("==============================================================================")
if response.response != nil {
api.logger?.error("response status code: \(response.response!.statusCode)")
api.logger?.error("response headers:\n\(response.response!.allHeaderFields)")
}else{
api.logger?.error(response.result.error?.localizedDescription)
}
if let value = response.result.value {
api.logger?.error("response body:\n\(value)")
}
api.logger?.error("==============================================================================")
}
}
| mit | fe2123adea59e1ef6c13edffcad3d3d0 | 40.223684 | 119 | 0.496968 | 5.061389 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Data Model/NSManagedObjectContext+LastNotificationID.swift | 1 | 1917 | //
// 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 WireDataModel
private let lastUpdateEventIDKey = "LastUpdateEventID"
@objc public protocol ZMLastNotificationIDStore {
var zm_lastNotificationID: UUID? { get set }
var zm_hasLastNotificationID: Bool { get }
}
extension NSManagedObjectContext: ZMLastNotificationIDStore {
public var zm_lastNotificationID: UUID? {
get {
guard let uuidString = self.persistentStoreMetadata(forKey: lastUpdateEventIDKey) as? String,
let uuid = UUID(uuidString: uuidString)
else { return nil }
return uuid
}
set (newValue) {
if let value = newValue, let previousValue = zm_lastNotificationID,
value.isType1UUID && previousValue.isType1UUID &&
previousValue.compare(withType1: value) != .orderedAscending {
return
}
Logging.eventProcessing.debug("Setting zm_lastNotificationID = \( newValue?.transportString() ?? "nil" )")
self.setPersistentStoreMetadata(newValue?.uuidString, key: lastUpdateEventIDKey)
}
}
public var zm_hasLastNotificationID: Bool {
return zm_lastNotificationID != nil
}
}
| gpl-3.0 | 989a837b2f009dc666c21798155b6d7e | 36.588235 | 118 | 0.683359 | 4.575179 | false | false | false | false |
icylydia/PlayWithLeetCode | 215. Kth Largest Element in an Array/solution.swift | 1 | 1981 | class Solution {
func findKthLargest(nums: [Int], _ k: Int) -> Int {
var heap = MaxIntHeap()
for e in nums {
heap.insert(e)
}
for _ in 0..<k - 1{
heap.pop()
}
return heap.pop()
}
}
class MaxIntHeap {
var elements = [0]
func insert(element: Int) {
elements.append(element)
var index = elements.count - 1
while index / 2 > 0 && elements[index] > elements[index / 2]{
let temp = elements[index / 2]
elements[index / 2] = elements[index]
elements[index] = temp
index /= 2
}
}
func pop() -> Int {
let ans = elements[1]
let last = elements.removeLast()
if elements.count == 1 {
return ans
}
elements[1] = last
var index = 1
while index * 2 + 1 <= elements.count - 1 {
if elements[index * 2 + 1] > elements[index * 2] {
// right > left
if elements[index * 2 + 1] > elements[index] {
let temp = elements[index * 2 + 1]
elements[index * 2 + 1] = elements[index]
elements[index] = temp
index = index * 2 + 1
} else {
break
}
} else {
// left >= right
if elements[index * 2] > elements[index] {
let temp = elements[index * 2]
elements[index * 2] = elements[index]
elements[index] = temp
index = index * 2
} else {
break
}
}
}
if index * 2 <= elements.count - 1 && elements[index * 2] > elements[index] {
let temp = elements[index * 2]
elements[index * 2] = elements[index]
elements[index] = temp
}
return ans
}
} | mit | 04398525bc0ee2a656baee080d7bfde9 | 30.460317 | 85 | 0.425038 | 4.431767 | false | false | false | false |
ByteriX/BxInputController | BxInputController/Sources/Rows/Text/View/BxInputTextMemoRowBinder.swift | 1 | 4059 | /**
* @file BxInputTextMemoRowBinder.swift
* @namespace BxInputController
*
* @details Binder for BxInputTextMemoRow
* @date 01.08.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
import BxObjC
/// Binder for BxInputTextMemoRow
open class BxInputTextMemoRowBinder<Row: BxInputTextMemoRow, Cell: BxInputTextMemoCell> : BxInputBaseRowBinder<Row, Cell>, BxInputTextMemoCellDelegate, UITextViewDelegate, BxInputTextMemoProtocol
{
/// This field stored position of cursore of textView, how need update on cell
internal var textPosition : UITextRange? = nil
var memoCell: BxInputTextMemoCellProtocol?{ cell }
var memoRow: BxInputTextMemoRowProtocol?{ row }
/// call when user selected this cell
override open func didSelected()
{
super.didSelected()
cell?.textView.becomeFirstResponder()
}
/// update cell from model data
override open func update()
{
super.update()
guard let cell = cell else {
return
}
cell.delegate = self
cell.textView.font = owner?.settings.valueFont
cell.textView.textColor = owner?.settings.valueColor
cell.textView.text = row.value
cell.textView.placeholderColor = owner?.settings.placeholderColor
cell.textView.placeholder = row.placeholder
cell.textView.update(from: row.textSettings)
updateTextView()
}
/// event of change isEnabled
override open func didSetEnabled(_ value: Bool)
{
super.didSetEnabled(value)
guard let cell = cell else {
return
}
if !value {
cell.textView.resignFirstResponder()
}
cell.textView.isUserInteractionEnabled = value
// UI part
if needChangeDisabledCell {
if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler {
changeViewEnableHandler(cell.textView, isEnabled)
} else {
cell.textView.alpha = value ? 1 : alphaForDisabledView
}
} else {
cell.textView.alpha = 1
}
}
/// check state of putting value
@objc open func check()
{
if checkSize() {
checkScroll()
}
}
// MARK - UITextViewDelegate
/// start editing
open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool
{
if !isEnabled {
return false
}
if let owner = owner, owner.settings.isAutodissmissSelector {
owner.dissmissSelectors()
}
owner?.activeRow = row
owner?.activeControl = textView
return true
}
/// editing is started
open func textViewDidBeginEditing(_ textView: UITextView)
{
self.perform(#selector(check), with: nil, afterDelay: 0.1)
}
/// end editing
open func textViewShouldEndEditing(_ textView: UITextView) -> Bool
{
if owner?.activeControl === textView {
owner?.activeControl = nil
}
if owner?.activeRow === row {
owner?.activeRow = nil
}
return true
}
/// change value
open func textViewDidChange(_ textView: UITextView)
{
row.value = textView.text
didChangeValue()
//owner?.updateRow(row) - it is redundant (2.7.9)
check()
}
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
if let maxCount = row.maxCount {
if var textView = textView as? BxTextView {
if textView.cutText(maxCount: maxCount, shouldChangeCharactersIn: range, replacementString: text) {
return false
}
}
}
return true
}
}
| mit | dee3aa54c747223697868acd3acb94b0 | 28.413043 | 195 | 0.607785 | 4.809242 | false | false | false | false |
uberbruns/UBRTest | UBRDeltaUI/Items/StaticValueTableViewCell.swift | 1 | 1887 | //
// StaticValueCell.swift
// DeltaCamera
//
// Created by Karsten Bruns on 25/11/15.
// Copyright © 2015 bruns.me. All rights reserved.
//
import UIKit
public class StaticValueTableViewCell: UITableViewCell, UpdateableTableViewCell {
private let titleView = UILabel()
private let valueView = UILabel()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
addSubviews()
addViewConstraints()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addSubviews() {
// Title View
titleView.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleView)
// Value View
valueView.textAlignment = .Right
valueView.translatesAutoresizingMaskIntoConstraints = false
addSubview(valueView)
}
private func addViewConstraints() {
let views = ["titleView": titleView, "valueView": valueView]
let h = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[titleView]-[valueView]-|", options: [], metrics: nil, views: views)
let vColorView = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[titleView]-|", options: [], metrics: nil, views: views)
let vCounterView = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[valueView]-|", options: [], metrics: nil, views: views)
addConstraints(h + vColorView + vCounterView)
}
public func updateCellWithItem(item: ComparableItem, animated: Bool) {
guard let staticValueItem = item as? StaticValueItem else { return }
titleView.text = staticValueItem.title
valueView.text = staticValueItem.value
}
} | mit | 7baf5dc5823c39a8c3a7d79f8f45e530 | 31.534483 | 136 | 0.668611 | 5.357955 | false | false | false | false |
LongPF/FaceTube | FaceTube/Tool/FTDevice.swift | 1 | 1279 |
//
// FTDevice.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/11.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import Foundation
public func transformForDeviceOrientation(orientation: UIDeviceOrientation) -> CGAffineTransform {
var result: CGAffineTransform = CGAffineTransform.identity
switch orientation {
case .landscapeRight:
result = CGAffineTransform.init(rotationAngle: .pi)
break
case .portraitUpsideDown:
result = CGAffineTransform.init(rotationAngle: .pi * 1.5)
break
case .faceDown,.faceUp,.portrait:
result = CGAffineTransform.init(rotationAngle: .pi * 0.5)
break
default:
break
}
return result
}
/// 根据前后摄像头返回transform
public func transformWithDevice(devicePosition: AVCaptureDevicePosition) -> CGAffineTransform {
var transform = CGAffineTransform.identity
switch devicePosition {
case .back:
transform = CGAffineTransform.init(rotationAngle: .pi/2.0)
break
case .front:
transform = CGAffineTransform.init(rotationAngle: .pi*1.5).scaledBy(x: -1.0, y: 1.0)
break
default:
break
}
return transform
}
| mit | f181269a3d1dffaac6b2d5608cac0c1e | 22.185185 | 98 | 0.659744 | 4.503597 | false | false | false | false |
Guicai-Li/iOS_Tutorial | CoreImageDemo/CoreImageDemo/ViewController.swift | 1 | 3990 | //
// ViewController.swift
// CoreImageDemo
//
// Created by 力贵才 on 15/12/1.
// Copyright © 2015年 Guicai.Li. All rights reserved.
//
import UIKit
import AssetsLibrary
import Photos
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
/*
CIFilter 滤镜
*/
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var amountSlider: UISlider!
var context : CIContext!
var filter : CIFilter!
var beginImage : CIImage!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fileURL = NSBundle.mainBundle().URLForResource("image", withExtension: "png")
beginImage = CIImage(contentsOfURL: fileURL!)
filter = CIFilter(name: "CISepiaTone")!
filter.setValue(beginImage, forKey: kCIInputImageKey)
filter.setValue(0.5, forKey: kCIInputIntensityKey)
// let newImage = UIImage(CIImage: filter.outputImage!)
//
// self.imageView.image = newImage
context = CIContext(options: nil)
let cgimg = context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent)
let newImage = UIImage(CGImage: cgimg)
self.imageView.image = newImage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func amountSliderValueChanged(sender: AnyObject) {
var slider = sender as! UISlider
let sliderValue = slider.value
filter.setValue(sliderValue, forKey: kCIInputIntensityKey)
let outputImg = filter.outputImage
let cgImg = context.createCGImage(outputImg!, fromRect: outputImg!.extent)
let newImg = UIImage(CGImage: cgImg)
self.imageView.image = newImg
}
@IBAction func loadPhoto(sender: AnyObject) {
let pickerC = UIImagePickerController()
pickerC.delegate = self
self.presentViewController(pickerC, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
print("[line=83]image=\(image), info=\(editingInfo)")
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("[line=87]info=\(info)")
self.dismissViewControllerAnimated(true, completion: nil)
let gotImg = info[UIImagePickerControllerOriginalImage] as! UIImage
beginImage = CIImage(image: gotImg)
filter.setValue(beginImage, forKey: kCIInputImageKey)
self.amountSliderValueChanged(self.amountSlider) //好机智...
}
@IBAction func savePhoto(sender: AnyObject) {
let imageToSave = filter.outputImage
let softwareContext = CIContext(options: [kCIContextUseSoftwareRenderer : true])
let cgimg = softwareContext.createCGImage(imageToSave!, fromRect: imageToSave!.extent)
let library = ALAssetsLibrary()
// // 恭喜你,iOS9.0弃用
// library.writeImageToSavedPhotosAlbum(cgimg, metadata: imageToSave!.properties, completionBlock: nil)
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
PHAssetChangeRequest.creationRequestForAssetFromImage(UIImage(CGImage: cgimg))
}) { (success, error) -> Void in
if success {
print("保存成功")
}
}
}
}
| apache-2.0 | f8c983f7dbe5636de9004ad2d0289264 | 28.931818 | 139 | 0.623386 | 5.397541 | false | false | false | false |
EZ-NET/ESCSVParser | Tool/ConverterMethodsGenerator.swift | 1 | 1458 | #!/usr/bin/swift
import Darwin.C
let startCode = UnicodeScalar("A").value
let endCode = UnicodeScalar("Z").value
var results = [String]()
results += ["extension RawLine {"]
for j in startCode ... endCode {
var parameters = [String]()
var parameterConditions = [String]()
var arguments = [String]()
var tuples = [String]()
var values = [String]()
parameters.append("Result")
for (i, char) in (startCode ... j).enumerate() {
let typeName = String(UnicodeScalar(char))
let valueName = typeName.lowercaseString
let argumentPrefix = (i == 0 ? "from " : "_ ")
parameters.append("\(typeName):RawColumnConvertible")
parameterConditions.append("\(typeName) == \(typeName).ConvertedType")
arguments.append("\(argumentPrefix)\(valueName):Int")
tuples.append("\(typeName)")
values.append("self.column(\(valueName)) as \(typeName)")
}
let params = parameters.joinWithSeparator(", ")
let paramConditions = parameterConditions.joinWithSeparator(", ")
let args = arguments.joinWithSeparator(", ")
let tups = tuples.joinWithSeparator(", ")
let vals = values.joinWithSeparator(", ")
results += [""]
results += ["\tpublic func make<\(params) where \(paramConditions)>(creation:(\(tups))->Result)(\(args)) throws -> Result {"]
results += [""]
results += ["\t\treturn try Converter((\(vals))).into(creation)"]
results += ["\t}"]
}
results += ["}"]
let code = results.joinWithSeparator("\n")
print(code)
| mit | 1f6fee69557dad7a793b748db5639085 | 26.509434 | 126 | 0.659122 | 3.826772 | false | false | false | false |
steve-whitney/spt-ios-sdk-issue409 | Issue409/SpotifyTracks.swift | 1 | 998 | import Foundation
class SpotifyTracks {
class func newInstanceAsyncFromURIs(uris: [String], callback: (SpotifyTracks) -> ()) -> Void {
var tracks = [SPTTrack]()
let count = uris.count
for uri in uris {
SPTTrack.trackWithURI(NSURL(string:uri), session: nil, callback: {
(error: NSError!, untypedSptTrack: AnyObject!) -> Void in
assert((nil == error),"oops: \(error)")
let track = untypedSptTrack as! SPTTrack
tracks.append(track)
if (tracks.count == count) {
callback(SpotifyTracks(uris:tracks))
NSLog("HAVE SPTTrack's.")
}
})
}
}
init(uris: [SPTTrack]) {
assert((uris.count >= 1),"oops -- no uri's")
self.uris = uris
}
private var ix = -1
private let uris: [SPTTrack]
func nextTrack() -> SPTTrack {
ix = (++ix % uris.count)
return uris[ix]
}
}
| apache-2.0 | 760f00f50691ee08d4e9b499786ec54c | 27.514286 | 98 | 0.518036 | 4.056911 | false | false | false | false |
jad6/DataStore | DataStore/DataStore-Common/DataStoreOperations.swift | 1 | 6145 | //
// DataStoreOperations.swift
// DataStore
//
// Created by Jad Osseiran on 12/11/2014.
// Copyright (c) 2015 Jad Osseiran. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import CoreData
public extension DataStore {
// MARK: Class Methods
/**
* Helper method to create an object model from a resource.
*
* - parameter resource: The name of the managed object model file.
* - parameter bundle: The bundle in which to look for.
* - returns: The initialised object model if found, nil otherwise.
*/
public class func modelForResource(resource: String, bundle: NSBundle) -> NSManagedObjectModel? {
// Try finding the model with both known model file extensions.
var modelURL = bundle.URLForResource(resource, withExtension: "momd")
if modelURL == nil {
modelURL = bundle.URLForResource(resource, withExtension: "mom")
}
// Return nil upon failure.
guard modelURL != nil else {
return nil
}
return NSManagedObjectModel(contentsOfURL: modelURL!)
}
// MARK: Main Queue
/**
* Method which performs operations asynchronously on the main queue.
*
* - parameter closure: The closure to perform on the main queue.
*/
public func performClosure(closure: ContextClosure) {
mainManagedObjectContext.performBlock() {
closure(context: self.mainManagedObjectContext)
}
}
/**
* Method which performs operations and saves asynchronously on the main queue.
*
* - parameter closure: The closure to perform on the main queue.
* - parameter completion: Closure containing an error pointer which is called when the operations and save are completed.
*/
public func performClosureAndSave(closure: ContextClosure, completion: ContextSaveClosure?) {
performClosure() { context in
closure(context: context)
self.save() { error in
completion?(context: context, error: error)
}
}
}
/**
* Method which performs operations synchronously on the main queue.
*
* - parameter closure: The closure to perform on the main queue.
*/
public func performClosureAndWait(closure: ContextClosure) {
mainManagedObjectContext.performBlockAndWait() {
closure(context: self.mainManagedObjectContext)
}
}
/**
* Method which performs operations and saves synchronously on the main queue.
* - throws: An error if issues are encountered at save time.
*
* - parameter closure: The closure to perform on the main queue.
*/
public func performClosureWaitAndSave(closure: ContextClosure) throws {
performClosureAndWait() { context in
closure(context: context)
}
try self.saveAndWait()
}
// MARK: Background Queue
/**
* Method which performs operations asynchronously on the background queue.
*
* - parameter closure: The closure to perform on the background queue.
*/
public func performBackgroundClosure(closure: ContextClosure) {
backgroundManagedObjectContext.performBlock() {
closure(context: self.backgroundManagedObjectContext)
}
}
/**
* Method which performs operations and saves asynchronously on the background queue.
*
* - parameter closure: The closure to perform on the background queue.
* - parameter completion: Closure containing an error pointer which is called when the operations and save are completed.
*/
public func performBackgroundClosureAndSave(closure: ContextClosure, completion: ContextSaveClosure?) {
performBackgroundClosure() { context in
closure(context: context)
self.save() { error in
completion?(context: context, error: error)
}
}
}
/**
* Method which performs operations synchronously on the background queue.
*
* - parameter closure: The closure to perform on the background queue.
*/
public func performBackgroundClosureAndWait(closure: ContextClosure) {
backgroundManagedObjectContext.performBlockAndWait() {
closure(context: self.backgroundManagedObjectContext)
}
}
/**
* Method which performs operations and saves synchronously on the background queue.
* - throws: An error if issues are encountered at save time.
*
* - parameter closure: The closure to perform on the background queue.
*/
public func performBackgroundClosureWaitAndSave(closure: ContextClosure) throws {
performBackgroundClosureAndWait() { context in
closure(context: context)
}
try saveAndWait()
}
} | bsd-2-clause | dc2ab627d537c2a5671c89528701632e | 37.4125 | 126 | 0.676159 | 5.15953 | false | false | false | false |
AS7C2/AVSTaggedAttributedString | AVSTaggedAttributedString/AVSTaggedAttributedString.swift | 1 | 2639 | //
// AVSTaggedAttributedString.swift
// AVSTaggedAttributedString
//
// Created by Andrei Sherstniuk on 8/8/16.
//
//
import Foundation
private extension NSRange {
private var avs_isFound: Bool {
get {
return self.location != NSNotFound
}
}
private func avs_isBefore(range range: NSRange) -> Bool {
return self.location + self.length <= range.location
}
private static func avs_between(range1 range1: NSRange, range2: NSRange) -> NSRange {
let location = range1.location + range1.length
let length = range2.location - location
return NSRange(location: location, length: length)
}
}
public extension NSMutableAttributedString {
public func avs_addAttributes(attributes: [String: AnyObject], toTag tag: String) {
let openTag = "<\(tag)>"
let closeTag = "</\(tag)>"
var string = self.mutableString
var openRange = string.rangeOfString(openTag)
var closeRange = string.rangeOfString(closeTag)
while openRange.avs_isFound && closeRange.avs_isFound && openRange.avs_isBefore(range: closeRange) {
let rangeBetween = NSRange.avs_between(range1: openRange, range2: closeRange)
self.replaceCharactersInRange(closeRange, withString: "")
self.replaceCharactersInRange(openRange, withString: "")
let rangeBetweenWithRemovedTags = NSRange(location: openRange.location, length: rangeBetween.length)
self.addAttributes(attributes, range: rangeBetweenWithRemovedTags)
string = self.mutableString
openRange = string.rangeOfString(openTag)
closeRange = string.rangeOfString(closeTag)
}
}
}
public extension NSAttributedString {
public func avs_attributedStringByAddingAttributes(attributes: [String: AnyObject], toTag tag: String) -> NSAttributedString {
let mutableSelf = self.mutableCopy() as! NSMutableAttributedString
mutableSelf.avs_addAttributes(attributes, toTag: tag)
return mutableSelf.copy() as! NSAttributedString
}
}
public extension String {
public func avs_attributedStringByAddingAttributes(attributes: [String: AnyObject], toTag tag: String) -> NSAttributedString {
return NSAttributedString(string: self).avs_attributedStringByAddingAttributes(attributes, toTag: tag)
}
}
public extension NSString {
public func avs_attributedStringByAddingAttributes(attributes: [String: AnyObject], toTag tag: String) -> NSAttributedString {
return (self as String).avs_attributedStringByAddingAttributes(attributes, toTag: tag)
}
} | mit | 6d047fe9833f3ff7d2fabc2afae48ef6 | 36.183099 | 130 | 0.699128 | 4.573657 | false | false | false | false |
niekang/WeiBo | Pods/URLNavigator/Sources/URLMatcher/URLMatcher.swift | 2 | 5728 | import Foundation
/// URLMatcher provides a way to match URLs against a list of specified patterns.
///
/// URLMatcher extracts the pattern and the values from the URL if possible.
open class URLMatcher {
public typealias URLPattern = String
public typealias URLValueConverter = (_ pathComponents: [String], _ index: Int) -> Any?
static let defaultURLValueConverters: [String: URLValueConverter] = [
"string": { pathComponents, index in
return pathComponents[index]
},
"int": { pathComponents, index in
return Int(pathComponents[index])
},
"float": { pathComponents, index in
return Float(pathComponents[index])
},
"uuid": { pathComponents, index in
return UUID(uuidString: pathComponents[index])
},
"path": { pathComponents, index in
return pathComponents[index..<pathComponents.count].joined(separator: "/")
}
]
open var valueConverters: [String: URLValueConverter] = URLMatcher.defaultURLValueConverters
public init() {
// 🔄 I'm an URLMatcher!
}
/// Returns a matching URL pattern and placeholder values from the specified URL and patterns.
/// It returns `nil` if the given URL is not contained in the URL patterns.
///
/// For example:
///
/// let result = matcher.match("myapp://user/123", from: ["myapp://user/<int:id>"])
///
/// The value of the `URLPattern` from an example above is `"myapp://user/<int:id>"` and the
/// value of the `values` is `["id": 123]`.
///
/// - parameter url: The placeholder-filled URL.
/// - parameter from: The array of URL patterns.
///
/// - returns: A `URLMatchComponents` struct that holds the URL pattern string, a dictionary of
/// the URL placeholder values.
open func match(_ url: URLConvertible, from candidates: [URLPattern]) -> URLMatchResult? {
let url = self.normalizeURL(url)
let scheme = url.urlValue?.scheme
let stringPathComponents = self.stringPathComponents(from :url)
for candidate in candidates {
guard scheme == candidate.urlValue?.scheme else { continue }
if let result = self.match(stringPathComponents, with: candidate) {
return result
}
}
return nil
}
func match(_ stringPathComponents: [String], with candidate: URLPattern) -> URLMatchResult? {
let normalizedCandidate = self.normalizeURL(candidate).urlStringValue
let candidatePathComponents = self.pathComponents(from: normalizedCandidate)
guard self.ensurePathComponentsCount(stringPathComponents, candidatePathComponents) else {
return nil
}
var urlValues: [String: Any] = [:]
let pairCount = min(stringPathComponents.count, candidatePathComponents.count)
for index in 0..<pairCount {
let result = self.matchStringPathComponent(
at: index,
from: stringPathComponents,
with: candidatePathComponents
)
switch result {
case let .matches(placeholderValue):
if let (key, value) = placeholderValue {
urlValues[key] = value
}
case .notMatches:
return nil
}
}
return URLMatchResult(pattern: candidate, values: urlValues)
}
func normalizeURL(_ dirtyURL: URLConvertible) -> URLConvertible {
guard dirtyURL.urlValue != nil else { return dirtyURL }
var urlString = dirtyURL.urlStringValue
urlString = urlString.components(separatedBy: "?")[0].components(separatedBy: "#")[0]
urlString = self.replaceRegex(":/{3,}", "://", urlString)
urlString = self.replaceRegex("(?<!:)/{2,}", "/", urlString)
urlString = self.replaceRegex("(?<!:|:/)/+$", "", urlString)
return urlString
}
func replaceRegex(_ pattern: String, _ repl: String, _ string: String) -> String {
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return string }
let range = NSMakeRange(0, string.count)
return regex.stringByReplacingMatches(in: string, options: [], range: range, withTemplate: repl)
}
func ensurePathComponentsCount(
_ stringPathComponents: [String],
_ candidatePathComponents: [URLPathComponent]
) -> Bool {
let hasSameNumberOfComponents = (stringPathComponents.count == candidatePathComponents.count)
let containsPathPlaceholderComponent = candidatePathComponents.contains {
if case let .placeholder(type, _) = $0, type == "path" {
return true
} else {
return false
}
}
return hasSameNumberOfComponents || (containsPathPlaceholderComponent && stringPathComponents.count > candidatePathComponents.count)
}
func stringPathComponents(from url: URLConvertible) -> [String] {
return url.urlStringValue.components(separatedBy: "/").lazy
.filter { !$0.isEmpty }
.filter { !$0.hasSuffix(":") }
}
func pathComponents(from url: URLPattern) -> [URLPathComponent] {
return self.stringPathComponents(from: url).map(URLPathComponent.init)
}
func matchStringPathComponent(
at index: Int,
from stringPathComponents: [String],
with candidatePathComponents: [URLPathComponent]
) -> URLPathComponentMatchResult {
let stringPathComponent = stringPathComponents[index]
let urlPathComponent = candidatePathComponents[index]
switch urlPathComponent {
case let .plain(value):
guard stringPathComponent == value else { return .notMatches }
return .matches(nil)
case let .placeholder(type, key):
guard let type = type, let converter = self.valueConverters[type] else {
return .matches((key, stringPathComponent))
}
if let value = converter(stringPathComponents, index) {
return .matches((key, value))
} else {
return .notMatches
}
}
}
}
| apache-2.0 | 07701baaa200417f6c219612818f6f48 | 34.78125 | 136 | 0.67738 | 4.525692 | false | false | false | false |
pierrewehbe/MyVoice | MyVoice/AppDelegate.swift | 1 | 8846 | //
// AppDelegate.swift
// MyVoice
//
// Created by Pierre on 11/12/16.
// Copyright © 2016 Pierre. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// print("Documents Directory of app :" + appDocumentDirectory.path)
//listContentsAtDirectory(Directory: "/")
// print("\n")
// print("Temporary Directory of app :" + appTemporaryFilesDirectory)
// listContentsAtDirectory(Directory: "/")
// print("\n")
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
directoryToSave = "Files/" // So each time we open the application, the default directory is Files/
myUserDefaults.synchronize()
// var protectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
// if protectedDataAvailable == true {
// self.launchApp()
// }
// else {
// print("protected_Data_NOT_Available")
// NotificationCenter.default.addObserver(self, selector: #selector(self.protectedDataAvailableNotification), name: UIApplicationProtectedDataDidBecomeAvailable, object: nil)
// }
return true
}
// func protectedDataAvailableNotification(_ notification: Notification) {
// print("protectedDataAvailableNotification")
// NotificationCenter.default.removeObserver(self, name: UIApplicationProtectedDataDidBecomeAvailable, object: nil)
// self.launchApp()
// }
func rotated()
{
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation))
{
print("Landscape")
//FIXME: Cancel
}
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation))
{
print("Portrait")
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//
// let tbc : UITabBarController = self.window?.rootViewController as! UITabBarController
// var moreViewController : UINavigationController = tbc.moreNavigationController
// moreViewController.navigationBar.barStyle = UIBarStyle.black
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
//FIXME: Exit conditions
print("Exited")
if ( RecordButtonState == .Pause ){ // Meaning it is currently recording
print("Was Still Recording")
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "1") as! VC_Recorder
vc.updateRecordButtonAtExit()
myUserDefaults.set(true, forKey: "wasRecording")
}else{
myUserDefaults.set(false, forKey: "wasRecording")
}
myUserDefaults.synchronize()
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "PierreW.MyVoice" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "MyVoice", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 5da6d73bdbb426cd69fd1f2b33abc324 | 46.810811 | 291 | 0.688864 | 5.713824 | false | false | false | false |
fjcaetano/RxWebSocket | RxWebSocketTests/RxWebSocketTests.swift | 1 | 8050 | //
// RxWebSocketTests.swift
// RxWebSocket
//
// Created by Flávio Caetano on 2016-01-22.
// Copyright © 2016 RxWebSocket. All rights reserved.
//
import RxBlocking
import RxSwift
@testable import RxWebSocket
import Starscream
import XCTest
class RxWebSocketTests: XCTestCase {
private var socket: RxWebSocket!
override func setUp() {
super.setUp()
socket = RxWebSocket(url: URL(string: "ws://127.0.0.1:9000")!)
}
override func tearDown() {
socket.disconnect()
super.tearDown()
}
// MARK: - Reactive components
func test__Connect_Cycle() {
do {
try socket.rx.connect
.toBlocking(timeout: 3)
.first()
}
catch let e {
XCTFail(e.localizedDescription)
}
socket.disconnect()
do {
let error = try socket.rx.disconnect
.toBlocking(timeout: 3)
.first()
.flatMap { $0 } // Double optional: Error??
as? WSError
XCTAssertNotNil(error?.type)
// swiftlint:disable:next todo
// TODO
// Starscream is returning `protocolError` for normal closing operations
// https://github.com/daltoniam/Starscream/issues/488
XCTAssertEqual(error?.type, ErrorType.protocolError)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Receive_Message() {
let messageString = "messageString"
do {
_ = socket.rx.connect
.take(1)
.subscribe(onNext: { [weak socket] in
socket?.write(string: messageString)
})
let result = try socket.rx.text
.toBlocking(timeout: 3)
.first()
XCTAssertEqual(result, messageString)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Receive_Data() {
let messageData = "messageString".data(using: String.Encoding.utf8)!
do {
_ = socket.rx.connect
.take(1)
.subscribe(onNext: { [weak socket] in
socket?.write(data: messageData)
})
let result = try socket.rx.data
.toBlocking(timeout: 3)
.first()
XCTAssertEqual(result, messageData)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Receive_Pong() {
var randomNumber = Int64(arc4random())
let pongData = Data(bytes: &randomNumber, count: MemoryLayout<Int64>.size)
do {
_ = socket.rx.connect
.take(1)
.subscribe(onNext: { [weak socket] in
socket?.write(ping: pongData)
})
let result = try socket.rx.pong
.toBlocking(timeout: 3)
.first()
.flatMap { $0 } // Double optional: Data??
XCTAssertEqual(result, pongData)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Receive_Stream() {
do {
// Receives connect
_ = try socket.rx.stream
.filter { $0 == .connect }
.toBlocking(timeout: 3)
.first()
// Receives pong
var randomNumber1 = Int64(arc4random())
let pongData = Data(bytes: &randomNumber1, count: MemoryLayout<Int64>.size)
socket.write(ping: pongData)
_ = try socket.rx.stream
.filter { $0 == .pong(pongData) }
.toBlocking(timeout: 3)
.first()
// Receives data
var randomNumber2 = Int64(arc4random())
let data = Data(bytes: &randomNumber2, count: MemoryLayout<Int64>.size)
socket.write(data: data)
_ = try socket.rx.stream
.filter { $0 == .data(data) }
.toBlocking(timeout: 3)
.first()
// Receives text
let message = "foobar"
socket.write(string: message)
_ = try socket.rx.stream
.filter { $0 == .text(message) }
.toBlocking(timeout: 3)
.first()
// Receives disconnect
socket.disconnect()
_ = try socket.rx.stream
.filter { $0 == .disconnect(nil) }
.toBlocking(timeout: 3)
.first()
}
catch let e {
XCTFail(e.localizedDescription)
}
do {
// Does not receive connect
_ = try socket.rx.stream
.filter { $0 == .connect }
.toBlocking(timeout: 3)
.first()
XCTFail("Shouldn't have connected")
}
catch _ {
// Did timeout as expected
}
}
// MARK: Binding
func test__Send_Text() {
let messageString = "someMessage"
do {
_ = socket.rx.connect
.map { messageString }
.take(1)
.bind(to: socket.rx.text)
let result = try socket.rx.text
.toBlocking(timeout: 3)
.first()
XCTAssertEqual(result, messageString)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Send_Data() {
let messageData = "someMessage".data(using: String.Encoding.utf8)!
do {
_ = socket.rx.connect
.map { messageData }
.take(1)
.bind(to: socket.rx.data)
let result = try socket.rx.data
.toBlocking(timeout: 3)
.first()
XCTAssertEqual(result, messageData)
}
catch let e {
XCTFail(e.localizedDescription)
}
}
func test__Multiple_Subscriptions() {
do {
// Disconnects and reconnects
_ = try socket.rx.connect
.flatMap { [unowned self] _ -> Observable<Error?> in
defer { self.socket.disconnect() }
return self.socket.rx.disconnect
}
.delay(.milliseconds(100), scheduler: MainScheduler.instance)
.do(onNext: { [weak self] _ in
self?.socket.connect()
})
.toBlocking(timeout: 3)
.first()
}
catch let e {
XCTFail(e.localizedDescription)
}
do {
_ = socket.rx.connect
.delay(.milliseconds(100), scheduler: MainScheduler.instance)
.map { "foobar" }
.take(1)
.bind(to: socket.rx.text)
_ = try socket.rx.text.asObservable()
.timeout(.seconds(1), scheduler: MainScheduler.instance)
.catchError { _ in .empty() } // Completes the sequence
.toBlocking(timeout: 3)
.single() // Checks if there's only 1 element
}
catch let e {
XCTFail(e.localizedDescription)
}
}
// MARK: Connect state
func test__Connect_State() {
do {
_ = try socket.rx.connect
.toBlocking(timeout: 3)
.first()
// Is still connected
_ = socket.rx.connect
.take(1)
.subscribe(onNext: { [weak socket] in
socket?.disconnect()
})
_ = try socket.rx.disconnect
.flatMap { _ in self.socket.rx.connect }
.toBlocking(timeout: 3)
.first()
XCTFail("Shouldn't have connected")
}
catch _ {
// Did timeout as expected
}
}
}
| mit | 177dc0955395c4671d0b46350fd3f27c | 26.281356 | 87 | 0.474652 | 4.816278 | false | false | false | false |
gobetti/Swift | BasicAgenda/BasicAgenda/DetailViewController.swift | 1 | 1347 | //
// DetailViewcontroller.swift
// BasicAgenda
//
// Created by Carlos Butron on 12/04/15.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var surnameLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
var contact = Contact()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
nameLabel.text = contact.name
surnameLabel.text = contact.surname
phoneLabel.text = contact.phone
emailLabel.text = contact.email
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | a79a5e0d8fe9a727eb8fc525f8654c6a | 25.94 | 106 | 0.662212 | 5.044944 | false | false | false | false |
tensorflow/swift-models | Tests/MiniGoTests/Strategies/MCTS/MCTSNodeTests.swift | 1 | 4650 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
import XCTest
@testable import MiniGo
final class MCTSNodeTests: XCTestCase {
func testSelectActionWithHighestPriorForNewNode() {
let boardSize = 2
let configuration = GameConfiguration(size: boardSize, komi: 0.1)
let boardState = BoardState(gameConfiguration: configuration)
let node = MCTSNode(
boardSize: boardSize,
boardState: boardState,
distribution: MCTSPrediction.Distribution(
positions: ShapedArray<Float>(
shape: [boardSize, boardSize],
scalars: Array(1...boardSize * boardSize).map { Float($0) }),
pass: 0.0))
// The final position has the highest prior.
let action = node.actionByPUCT
XCTAssertEqual(.place(position: Position(x: boardSize-1, y: boardSize-1)), action)
}
func testSelectActionWithHighestPriorWithTieBreakForNewNode() {
let boardSize = 2
let configuration = GameConfiguration(size: boardSize, komi: 0.1)
let boardState = BoardState(gameConfiguration: configuration)
let node = MCTSNode(
boardSize: boardSize,
boardState: boardState,
distribution: MCTSPrediction.Distribution(
positions: ShapedArray<Float>(repeating: 1.0, shape: [boardSize, boardSize]),
pass: 1.0))
// All actions have equal prior values. So, with 100 runs, we should see they are randomly
// selected. To avoid flakyness, we test >1 rather than ==boardSize*boardSize+1.
var actionPool = Set<Move>()
for _ in 1..<100 {
actionPool.insert(node.actionByPUCT)
}
XCTAssertTrue(actionPool.count > 1)
}
}
// Tests for backUp.
extension MCTSNodeTests {
func testSelectActionAfterBackUpForSamePlayer() {
let boardSize = 2
let configuration = GameConfiguration(size: boardSize, komi: 0.1)
let boardState = BoardState(gameConfiguration: configuration)
XCTAssertEqual(.black, boardState.nextPlayerColor)
let node = MCTSNode(
boardSize: boardSize,
boardState: boardState,
distribution: MCTSPrediction.Distribution(
positions: ShapedArray<Float>(repeating: 1.0, shape: [boardSize, boardSize]),
pass: 1.0))
node.backUp(for: .place(position: Position(x: 1, y: 0)), withRewardForBlackPlayer: 100.0)
let action = node.actionByPUCT
XCTAssertEqual(.place(position: Position(x: 1, y: 0)), action)
}
func testSelectActionAfterBackUpForOpponent() {
let boardSize = 2
let configuration = GameConfiguration(size: boardSize, komi: 0.1)
let boardState = BoardState(gameConfiguration: configuration).passing()
XCTAssertEqual(.white, boardState.nextPlayerColor)
let node = MCTSNode(
boardSize: boardSize,
boardState: boardState,
distribution: MCTSPrediction.Distribution(
positions: ShapedArray<Float>(
shape: [boardSize, boardSize],
scalars: Array(1...boardSize * boardSize).map { Float($0) }),
pass: Float(boardSize * boardSize) - 0.5))
// x: 1, y: 1 has the highest prior. But after backing up, its action value is lower.
node.backUp(for: .place(position: Position(x: 1, y: 1)), withRewardForBlackPlayer: 100.0)
let action = node.actionByPUCT
XCTAssertEqual(.pass, action)
}
}
extension MCTSNodeTests {
static var allTests = [
("testSelectActionWithHighestPriorForNewNode", testSelectActionWithHighestPriorForNewNode),
("testSelectActionWithHighestPriorWithTieBreakForNewNode",
testSelectActionWithHighestPriorWithTieBreakForNewNode),
("testSelectActionAfterBackUpForSamePlayer", testSelectActionAfterBackUpForSamePlayer),
("testSelectActionAfterBackUpForOpponent", testSelectActionAfterBackUpForOpponent),
]
}
| apache-2.0 | 016aee428e6c059995f8bbcf45fac544 | 40.517857 | 99 | 0.663226 | 4.317549 | false | true | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Common/Transforms/HexDataTransform.swift | 1 | 560 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import ObjectMapper
class HexDataTransform: TransformType {
public typealias Object = Data
public typealias JSON = String
public init() {}
open func transformFromJSON(_ value: Any?) -> Data? {
guard let string = value as? String, let data = string.toHexData() else {
return nil
}
return data
}
open func transformToJSON(_ value: Data?) -> String? {
guard let data = value else{
return nil
}
return data.hex()
}
}
| gpl-3.0 | d02c2160a7897b085212955e0abc6240 | 20.5 | 77 | 0.652952 | 4.367188 | false | false | false | false |
manavgabhawala/CookieManager | Cookie Manager/Extensions.swift | 1 | 6691 | //
// Extensions.swift
// Cookie Manager
//
// Created by Manav Gabhawala on 22/07/15.
// Copyright © 2015 Manav Gabhawala. All rights reserved.
//
// The MIT License (MIT)
// Copyright (c) 2015 Manav Gabhawala
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension String
{
/// An initializer that allows for a native Swift `String` to be created using `NSData`
///
/// - parameter data: The data with which to create the `String`
/// - parameter encoding: The encoding with which to parse the data. This defaults to `NSUTF8StringEncoding` if no encoding is specified.
///
/// - returns: nil if the data passed was nil or if the `String` couldn't be formed using the encoding specified.
init?(data: NSData?, encoding: NSStringEncoding = NSUTF8StringEncoding)
{
guard let data = data
else
{
return nil
}
guard let str = NSString(data: data, encoding: encoding) as? String
else
{
return nil
}
self.init(str)
}
/// Initializes a String by reading data from an `NSData` instance one character at a time until it reaches a null character.
///
/// - parameter data: The data from which to read off to form the string.
/// - parameter location: The location inside the data from which to start reading the `String` one character at a time.
/// - parameter encoding: The encoding with which to parse the data. This defaults to `NSUTF8StringEncoding` if no encoding is specified.
///
/// - returns: An initialized string with the characters till a null character or `\0` was read or if the data couldn't be converted to a string using the encoding specified. This can return an empty `String` too if the first character read was null.
init(readData data: NSData, fromLocationTillNullChar location: Int, encoding: NSStringEncoding = NSUTF8StringEncoding)
{
if encoding == NSUTF8StringEncoding
{
let dataPointer = UnsafePointer<Int8>(data.bytes.advancedBy(location))
self = NSString(UTF8String: dataPointer) as! String
return
}
self = ""
var range = NSRange(location: location, length: 1)
while let str = String(data: data.subdataWithRange(range), encoding: encoding) where str != "\0"
{
self += str
++range.location
}
}
/// A function that checks if the reciever contains a string with considering case.
///
/// - parameter string: The string which should be inside the reciever.
///
/// - returns: `true` if the string is contained. Else `false`
func caseInsensitiveContainsString(string: String) -> Bool
{
return self.rangeOfString(string, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
}
}
/// This enum specifies the types of Endianness available to parse binary data.
enum Endianness
{
/// BigEndian meaning the first bits are least significant (reversed).
case BigEndian
/// LittleEndian meaning the first bits are most significant.
case LittleEndian
}
extension Int
{
/// Creates an Integer from binary data using the endian to parse the binary data.
///
/// - Warning: This function will fail if the `length` of `data != 4`. Therefore data must be of length 4.
/// - parameter data: The binary data to use to form the integer.
/// - parameter endian: The endianness with which to read the data.
///
/// - returns: An initialized Integer read from the binary data.
init(binary data: NSData, endian: Endianness)
{
assert(data.length == 4)
var bytes = [UInt8]()
bytes.reserveCapacity(data.length)
var dataBytes = data.bytes
for _ in 0..<data.length
{
bytes.append(UnsafePointer<UInt8>(dataBytes).memory)
dataBytes = dataBytes.successor()
}
self = 0
if endian == .LittleEndian
{
for (i, byte) in bytes.reverse().enumerate()
{
self += Int(pow(2.0, 8.0 * Double(i))) * Int(byte)
}
}
else
{
for (i, byte) in bytes.enumerate()
{
self += Int(pow(2.0, 8.0 * Double(i))) * Int(byte)
}
}
}
}
extension Double
{
/// Creates an Double from binary data using the endian to parse the binary data.
///
/// - Warning: This function will fail if the `length` of `data != 8`. Therefore data must be of length 8.
/// - parameter data: The binary data to use to form the double.
/// - parameter endian: The endianness with which to read the data.
///
/// - returns: An initialized Double read from the binary data.
init(binary data: NSData, endian: Endianness)
{
assert(data.length == 8)
self = 0
memcpy(&self, data.bytes, data.length)
}
}
extension NSDate : Comparable
{
/// A convenience initializer for NSDate that creates an NSDate using an epochBinary data of length 8. The underlying double in the binary data must be a date of the form of time interval in the Mac + iOS epoch format, i.e. the reference date is 1/1/2001. This method only supports `BigEndian` endianness.
///
/// - Warning: This function will fail if the `length` of `data != 8`. Therefore data must be of length 8.
/// - parameter data: The epoch binary data to use to form the NSDate
///
/// - returns: An initialized NSDate created using the underlying Double value.
convenience init(epochBinary data: NSData)
{
let timeInterval = Double(binary: data, endian: .BigEndian)
self.init(timeIntervalSinceReferenceDate: timeInterval)
}
}
public func < (lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.compare(rhs) == .OrderedAscending
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.compare(rhs) == .OrderedSame
}
extension Array where Element : Equatable
{
mutating func removeElement(element: Element)
{
for (i, elem) in enumerate()
{
if elem == element
{
self.removeAtIndex(i)
return
}
}
}
}
| mit | b9d934171e6adc1a0e64093f358a3604 | 34.210526 | 307 | 0.709417 | 3.752103 | false | false | false | false |
yujiaao/SwiftHN | SwiftHN/AppDelegate.swift | 6 | 3366 | //
// AppDelegate.swift
// SwiftHN
//
// Created by Thomas Ricouard on 05/06/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import UIKit
import SwiftHNShared
import HackerSwifter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
self.setupStyle()
return true
}
func setupStyle() {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false)
UINavigationBar.appearance().barTintColor = UIColor.HNColor()
UINavigationBar.appearance().translucent = true
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 16.0)!]
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
Post.fetch(Post.PostFilter.Top, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in
if (!local) {
completionHandler(UIBackgroundFetchResult.NewData)
}
else if (error != nil) {
completionHandler(UIBackgroundFetchResult.Failed)
}
})
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 | bbf45552549229e26c2d4645d7e056fb | 47.085714 | 285 | 0.715686 | 5.864111 | false | false | false | false |
zyphs21/HSStockChart | HSStockChart/KLineChart/HSKLineStyle.swift | 1 | 1931 | //
// HSKLineStyle.swift
// HSStockChart
//
// Created by Hanson on 2017/10/20.
// Copyright © 2017年 HansonStudio. All rights reserved.
//
import Foundation
import CoreGraphics
import UIKit
public struct HSKLineStyle {
public init()
{
}
public var uperChartHeightScale: CGFloat = 0.7 // 70% 的空间是上部分的走势图
public var lineWidth: CGFloat = 1
public var frameWidth: CGFloat = 0.25
public var xAxisHeitht: CGFloat = 30
public var viewMinYGap: CGFloat = 15
public var volumeGap: CGFloat = 10
public var candleWidth: CGFloat = 5
public var candleGap: CGFloat = 2
public var candleMinHeight: CGFloat = 0.5
public var candleMaxWidth: CGFloat = 30
public var candleMinWidth: CGFloat = 2
public var ma5Color = UIColor.hschart.color(rgba: "#e8de85")
public var ma10Color = UIColor.hschart.color(rgba: "#6fa8bb")
public var ma20Color = UIColor.hschart.color(rgba: "#df8fc6")
public var borderColor = UIColor.hschart.color(rgba: "#e4e4e4")
public var crossLineColor = UIColor.hschart.color(rgba: "#546679")
public var textColor = UIColor.hschart.color(rgba: "#8695a6")
public var riseColor = UIColor.hschart.color(rgba: "#f24957") // 涨 red
public var fallColor = UIColor.hschart.color(rgba: "#1dbf60") // 跌 green
public var priceLineCorlor = UIColor.hschart.color(rgba: "#0095ff")
public var avgLineCorlor = UIColor.hschart.color(rgba: "#ffc004") // 均线颜色
public var fillColor = UIColor.hschart.color(rgba: "#e3efff")
public var baseFont = UIFont.systemFont(ofSize: 10)
func getTextSize(text: String) -> CGSize {
let size = text.size(withAttributes: [NSAttributedString.Key.font: baseFont])
let width = ceil(size.width) + 5
let height = ceil(size.height)
return CGSize(width: width, height: height)
}
}
| mit | 6bbb2ff5a2ebbeea4a6a137cc383016f | 32.821429 | 85 | 0.674234 | 3.635317 | false | false | false | false |
eelcokoelewijn/StepUp | StepUp/Common/AudioPlayer/AudioPlayerView.swift | 1 | 9220 | import UIKit
public protocol AudioPlayerDelegate: class {
func controlPressed(player: AudioPlayerView)
}
public class AudioPlayerView: UIView {
public lazy var itemTitle: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.font = UIFont.regular(withSize: 14)
return l
}()
public lazy var totalTime: UILabel = {
let l = UILabel()
l.font = UIFont.light(withSize: 14)
l.translatesAutoresizingMaskIntoConstraints = false
l.text = String(format: "%02d:%02d", 0, 0)
return l
}()
public lazy var elapsedTime: UILabel = {
let l = UILabel()
l.font = UIFont.light(withSize: 14)
l.translatesAutoresizingMaskIntoConstraints = false
l.text = String(format: "%02d:%02d", 0, 0)
return l
}()
public lazy var controlButton: UIButton = {
let b = UIButton(type: .custom)
b.translatesAutoresizingMaskIntoConstraints = false
b.addTarget(self, action: #selector(controlButtonTapped(sender:)), for: .touchUpInside)
b.titleLabel?.font = UIFont.regular(withSize: 14)
b.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.buttonDisabled, for: .highlighted)
b.backgroundColor = .treamentButtonBackground
b.layer.cornerRadius = 3
b.setTitle("Afspelen", for: .normal)
return b
}()
public weak var delegate: AudioPlayerDelegate?
private lazy var wrapperView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
private lazy var progressIndicator: UIProgressView = {
let p = UIProgressView(progressViewStyle: .bar)
p.translatesAutoresizingMaskIntoConstraints = false
p.trackTintColor = UIColor.buttonDisabled
p.progressTintColor = .baseGreen
return p
}()
override public init(frame: CGRect) {
super.init(frame: frame)
setupViews()
applyViewConstraints()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func reset() {
elapsedTime.text = String(format: "%0d:%02d", 0, 0)
totalTime.text = String(format: "%0d:%02d", 0, 0)
progressIndicator.setProgress(0, animated: false)
controlButton.setTitle("Afspelen", for: .normal)
}
public func progress(totalTime: Double, elapsedTime: Double) {
progressIndicator.setProgress(1.0 / Float(totalTime / elapsedTime), animated: true)
}
@objc private func controlButtonTapped(sender: UIButton) {
delegate?.controlPressed(player: self)
}
private func setupViews() {
addSubview(wrapperView)
wrapperView.addSubview(itemTitle)
wrapperView.addSubview(elapsedTime)
wrapperView.addSubview(totalTime)
wrapperView.addSubview(controlButton)
wrapperView.addSubview(progressIndicator)
}
// swiftlint:disable function_body_length
private func applyViewConstraints() {
let views = ["wrapperView": wrapperView]
var constraints: [NSLayoutConstraint] = []
constraints.append(NSLayoutConstraint(item: itemTitle,
attribute: .top,
relatedBy: .equal,
toItem: wrapperView,
attribute: .top,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: itemTitle,
attribute: .left,
relatedBy: .equal,
toItem: wrapperView,
attribute: .left,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: itemTitle,
attribute: .right,
relatedBy: .equal,
toItem: wrapperView,
attribute: .right,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: elapsedTime,
attribute: .top,
relatedBy: .equal,
toItem: itemTitle,
attribute: .bottom,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: elapsedTime,
attribute: .left,
relatedBy: .equal,
toItem: itemTitle,
attribute: .left,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: totalTime,
attribute: .top,
relatedBy: .equal,
toItem: itemTitle,
attribute: .bottom,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: totalTime,
attribute: .right,
relatedBy: .equal,
toItem: itemTitle,
attribute: .right,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: controlButton,
attribute: .top,
relatedBy: .equal,
toItem: elapsedTime,
attribute: .bottom,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: controlButton,
attribute: .left,
relatedBy: .equal,
toItem: elapsedTime,
attribute: .left,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: progressIndicator,
attribute: .top,
relatedBy: .equal,
toItem: controlButton,
attribute: .bottom,
multiplier: 1, constant: 10))
constraints.append(NSLayoutConstraint(item: progressIndicator,
attribute: .left,
relatedBy: .equal,
toItem: controlButton,
attribute: .left,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: progressIndicator,
attribute: .right,
relatedBy: .equal,
toItem: wrapperView,
attribute: .right,
multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: progressIndicator,
attribute: .bottom,
relatedBy: .equal,
toItem: wrapperView,
attribute: .bottom,
multiplier: 1, constant: 0))
NSLayoutConstraint.activate(constraints)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[wrapperView]|",
options: [],
metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[wrapperView]|",
options: [],
metrics: nil, views: views))
}
// swiftlint:enable function_body_length
}
| mit | 10cd432eee9f57ece61994c1537f6df2 | 46.282051 | 95 | 0.443167 | 6.958491 | false | false | false | false |
KeepGoing2016/Swift- | DUZB_XMJ/DUZB_XMJ/Classes/Home/Controller/HomeViewController.swift | 1 | 3457 | //
// HomeViewController.swift
// DUZB_XMJ
//
// Created by user on 16/12/16.
// Copyright © 2016年 XMJ. All rights reserved.
//
import UIKit
private let kPageTitleViewH:CGFloat = 40
class HomeViewController: UIViewController {
fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in
let pageTitleV = PageTitleView(frame: CGRect(x: 0, y: kStatusBarH+kNavigationBarH, width: kScreenW, height: kPageTitleViewH), titles: ["推荐","游戏","娱乐","趣玩"])
pageTitleV.delegate = self
// pageTitleV.backgroundColor = UIColor.orange
return pageTitleV
}()
fileprivate lazy var pageContentView:PageContentView = {[weak self] in
let v1 = RecommendViewController()
let v2 = GameViewController()
let v3 = FunViewController()
let v4 = FunnyViewController()
let pageContentVY = kStatusBarH+kNavigationBarH+kPageTitleViewH
let contentVF = CGRect(x: 0, y:pageContentVY , width: kScreenW, height: kScreenH-pageContentVY-kTapBarH)
let pageContentV = PageContentView(frame: contentVF, childVCs: [v1,v2,v3,v4], parentVC: self!)
pageContentV.delegate = self
return pageContentV
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
setUI()
}
}
//MARK:-设置UI
extension HomeViewController{
fileprivate func setUI(){
// 0.不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//设置导航
setUpNav()
//设置头部选择标题
view.addSubview(pageTitleView)
//设置中间内容
view.addSubview(pageContentView)
}
fileprivate func setUpNav() {
// let leftBtn = UIButton()
// leftBtn.setImage(UIImage(named:"logo"), for: .normal)
// leftBtn.sizeToFit()
// navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
let itemSize = CGSize(width: 40, height: 40)
let search = UIBarButtonItem(imageName: "btn_search", selImageName: "btn_search_clicked", itemSize: itemSize)
let history = UIBarButtonItem(imageName: "image_my_history", selImageName: "Image_my_history_click", itemSize: itemSize)
let scan = UIBarButtonItem(imageName: "Image_scan", selImageName: "Image_scan_click", itemSize: itemSize)
navigationItem.rightBarButtonItems = [search,history,scan]
}
// fileprivate func setupHeaderTitle(){
//
// let pageTitleView = PageTitleView(frame: CGRect(x: 0, y: kStatusBarH+kNavigationBarH, width: kScreenW, height: 40), titles: ["推荐","手游","娱乐","游戏","趣玩"])
//// pageTitleView.backgroundColor = UIColor.brown
// view.addSubview(pageTitleView)
// }
}
//代理方法
extension HomeViewController:PageTitleViewDelegate,PageContentViewDelegate{
internal func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) {
pageContentView.pageContentViewScrollTo(index: index)
}
func pageContentView(_ pageContentView: PageContentView,fromIndex:Int ,toIndex: Int, progress: CGFloat) {
pageTitleView.pageTitleViewScrollTo(fromIndex:fromIndex,toIndex: toIndex, progress: progress)
}
}
| apache-2.0 | 1ad5616e220e401c0f785fcb866b6514 | 34.284211 | 164 | 0.663186 | 4.642659 | false | false | false | false |
icecrystal23/ios-charts | Source/Charts/Data/Implementations/Standard/PieChartData.swift | 3 | 3106 | //
// PieData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class PieChartData: ChartData
{
public override init()
{
super.init()
}
public override init(dataSets: [IChartDataSet]?)
{
super.init(dataSets: dataSets)
}
/// - returns: All DataSet objects this ChartData object holds.
@objc open override var dataSets: [IChartDataSet]
{
get
{
assert(super.dataSets.count <= 1, "Found multiple data sets while pie chart only allows one")
return super.dataSets
}
set
{
super.dataSets = newValue
}
}
@objc var dataSet: IPieChartDataSet?
{
get
{
return dataSets.count > 0 ? dataSets[0] as? IPieChartDataSet : nil
}
set
{
if let newValue = newValue
{
dataSets = [newValue]
}
else
{
dataSets = []
}
}
}
open override func getDataSetByIndex(_ index: Int) -> IChartDataSet?
{
if index != 0
{
return nil
}
return super.getDataSetByIndex(index)
}
open override func getDataSetByLabel(_ label: String, ignorecase: Bool) -> IChartDataSet?
{
if dataSets.count == 0 || dataSets[0].label == nil
{
return nil
}
if ignorecase
{
if let label = dataSets[0].label, label.caseInsensitiveCompare(label) == .orderedSame
{
return dataSets[0]
}
}
else
{
if label == dataSets[0].label
{
return dataSets[0]
}
}
return nil
}
open override func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
return dataSet?.entryForIndex(Int(highlight.x))
}
open override func addDataSet(_ d: IChartDataSet!)
{
super.addDataSet(d)
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
open override func removeDataSetByIndex(_ index: Int) -> Bool
{
if index >= _dataSets.count || index < 0
{
return false
}
return false
}
/// - returns: The total y-value sum across all DataSet objects the this object represents.
@objc open var yValueSum: Double
{
guard let dataSet = dataSet else { return 0.0 }
var yValueSum: Double = 0.0
for i in 0..<dataSet.entryCount
{
yValueSum += dataSet.entryForIndex(i)?.y ?? 0.0
}
return yValueSum
}
}
| apache-2.0 | ce999540e76f6e0d44ab813871eade2d | 22.892308 | 105 | 0.525113 | 4.930159 | false | false | false | false |
iOSTestApps/CardsAgainst | CardsAgainst/Controllers/WhiteCardFlowLayout.swift | 3 | 1399 | //
// WhiteCardFlowLayout.swift
// CardsAgainst
//
// Created by JP Simard on 11/3/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import UIKit
private func easeInOut(var t: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat) -> CGFloat {
t /= d/2
if t < 1 {
return c/2*t*t*t + b
}
t -= 2
return c/2*(t*t*t + 2) + b
}
final class WhiteCardFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let layoutAttributes = super.layoutAttributesForElementsInRect(rect)
let topContentInset = collectionView!.contentInset.top + 20
let transitionRegion = CGFloat(120)
for attributes in layoutAttributes as [UICollectionViewLayoutAttributes] {
let yOriginInSuperview = collectionView!.convertPoint(attributes.frame.origin, toView: collectionView!.superview).y
if topContentInset > yOriginInSuperview {
let difference = topContentInset - yOriginInSuperview
let progress = difference/transitionRegion
attributes.alpha = easeInOut(min(progress, 1), 1, -0.95, 1)
} else {
attributes.alpha = 1
}
}
return layoutAttributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
| mit | b5aa35849f86c06ea7fec0df34a30542 | 32.309524 | 127 | 0.647605 | 4.67893 | false | false | false | false |
openHPI/xikolo-ios | Stockpile/Protocols/Pullable.swift | 1 | 9484 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import CoreData
import Marshal
public protocol Pullable: ResourceRepresentable, Validatable {
static func value(from object: ResourceData, with context: SynchronizationContext) throws -> Self
mutating func update(from object: ResourceData, with context: SynchronizationContext) throws
// strategy
static var resourceKeyAttribute: String { get }
static func queryItems<Query>(forQuery query: Query) -> [URLQueryItem] where Query: ResourceQuery
static func validateObjectCreation(object: ResourceData) throws
static func extractResourceData(from object: ResourceData) throws -> ResourceData
static func extractResourceData(from object: ResourceData) throws -> [ResourceData]
static func extractIncludedResourceData(from object: ResourceData) -> [ResourceData]
}
extension Pullable where Self: NSManagedObject {
public static func value(from object: ResourceData, with context: SynchronizationContext) throws -> Self {
try Self.validateObjectCreation(object: object)
var managedObject = self.init(entity: self.entity(), insertInto: context.coreDataContext)
try managedObject.id = object.value(for: Self.resourceKeyAttribute)
try managedObject.update(from: object, with: context)
return managedObject
}
public func updateRelationship<A>(forKeyPath keyPath: ReferenceWritableKeyPath<Self, A>,
forKey key: KeyType,
fromObject object: ResourceData,
with context: SynchronizationContext) throws where A: NSManagedObject & Pullable {
switch context.findIncludedObject(forKey: key, ofObject: object) {
case let .object(_, includedObject):
var existingObject = self[keyPath: keyPath] // TODO: also check if id is equal. update() does not updates the id
do {
try existingObject.update(from: includedObject, with: context)
} catch let error as MarshalError {
throw NestedMarshalError.nestedMarshalError(error, includeType: A.type, includeKey: key)
}
default:
throw SynchronizationError.missingIncludedResource(from: Self.self, to: A.self, withKey: key)
}
}
public func updateRelationship<A>(forKeyPath keyPath: ReferenceWritableKeyPath<Self, A?>,
forKey key: KeyType,
fromObject object: ResourceData,
with context: SynchronizationContext) throws where A: NSManagedObject & Pullable {
switch context.findIncludedObject(forKey: key, ofObject: object) {
case let .object(resourceId, includedObject):
do {
if var existingObject = self[keyPath: keyPath] { // TODO: also check if id is equal. update() does not updates the id
try existingObject.update(from: includedObject, with: context)
} else {
if var fetchedResource = try context.findExistingResource(withId: resourceId, ofType: A.self) {
try fetchedResource.update(from: includedObject, with: context)
self[keyPath: keyPath] = fetchedResource
} else {
self[keyPath: keyPath] = try A.value(from: includedObject, with: context)
}
}
} catch let error as MarshalError {
throw NestedMarshalError.nestedMarshalError(error, includeType: A.type, includeKey: key)
}
case let .id(resourceId):
if let fetchedResource = try context.findExistingResource(withId: resourceId, ofType: A.self) {
self[keyPath: keyPath] = fetchedResource
} else {
self[keyPath: keyPath] = nil
// TODO: logging
// SyncEngine.log?("relationship update saved (\(Self.type) --> \(A.type)?)", .info)
}
case .notExisting:
// relationship does not exist, so we reset delete the possible relationship
self[keyPath: keyPath] = nil
}
}
public func updateRelationship<A>(forKeyPath keyPath: ReferenceWritableKeyPath<Self, Set<A>>,
forKey key: KeyType,
fromObject object: ResourceData,
with context: SynchronizationContext) throws where A: NSManagedObject & Pullable {
var currentObjects = Set(self[keyPath: keyPath])
do {
switch context.findIncludedObjects(forKey: key, ofObject: object) {
case let .included(resourceIdsAndObjects, resourceIds):
for (resourceId, includedObject) in resourceIdsAndObjects {
if var currentObject = currentObjects.first(where: { $0.id == resourceId }) {
try currentObject.update(from: includedObject, with: context)
if let index = currentObjects.firstIndex(where: { $0 == currentObject }) {
currentObjects.remove(at: index)
}
} else {
if var fetchedResource = try context.findExistingResource(withId: resourceId, ofType: A.self) {
try fetchedResource.update(from: includedObject, with: context)
self[keyPath: keyPath].insert(fetchedResource)
} else {
let newObject = try A.value(from: includedObject, with: context)
self[keyPath: keyPath].insert(newObject)
}
}
}
for resourceId in resourceIds {
if let currentObject = currentObjects.first(where: { $0.id == resourceId }) {
if let index = currentObjects.firstIndex(where: { $0 == currentObject }) {
currentObjects.remove(at: index)
}
} else {
if let fetchedResource = try context.findExistingResource(withId: resourceId, ofType: A.self) {
self[keyPath: keyPath].insert(fetchedResource)
}
}
}
case .notExisting:
break
}
} catch let error as MarshalError {
throw NestedMarshalError.nestedMarshalError(error, includeType: A.type, includeKey: key)
}
// TODO: really?
for currentObject in currentObjects {
context.coreDataContext.delete(currentObject)
}
}
public func updateAbstractRelationship<A>(forKeyPath keyPath: ReferenceWritableKeyPath<Self, A?>,
forKey key: KeyType,
fromObject object: ResourceData,
with context: SynchronizationContext,
updatingBlock block: (AbstractPullableContainer<Self, A>) throws -> Void) throws {
let container = AbstractPullableContainer<Self, A>(onResource: self,
withKeyPath: keyPath,
forKey: key,
fromObject: object,
with: context)
try block(container)
}
}
public class AbstractPullableContainer<A, B> where A: NSManagedObject & Pullable, B: NSManagedObject & AbstractPullable {
let resource: A
let keyPath: ReferenceWritableKeyPath<A, B?>
let key: KeyType
let object: ResourceData
let context: SynchronizationContext
init(onResource resource: A,
withKeyPath keyPath: ReferenceWritableKeyPath<A, B?>,
forKey key: KeyType,
fromObject object: ResourceData,
with context: SynchronizationContext) {
self.resource = resource
self.keyPath = keyPath
self.key = key
self.object = object
self.context = context
}
public func update<C>(forType type: C.Type) throws where C: NSManagedObject & Pullable {
let resourceIdentifier = try self.object.value(for: "\(self.key).data") as ResourceIdentifier
guard resourceIdentifier.type == C.type else { return }
switch self.context.findIncludedObject(forKey: self.key, ofObject: self.object) {
case let .object(_, includedObject):
do {
if var existingObject = self.resource[keyPath: self.keyPath] as? C {
try existingObject.update(from: includedObject, with: context)
} else if let newObject = try C.value(from: includedObject, with: context) as? B {
self.resource[keyPath: self.keyPath] = newObject
}
} catch let error as MarshalError {
throw NestedMarshalError.nestedMarshalError(error, includeType: C.type, includeKey: key)
}
default:
// TODO throw error?
break
}
}
}
public protocol AbstractPullable {}
| gpl-3.0 | f38842d39f3596b3c5cb01751027ca52 | 47.630769 | 133 | 0.574607 | 5.3789 | false | false | false | false |
Sadmansamee/quran-ios | Quran/DefaultAudioBannerViewPresenter.swift | 1 | 6064 | //
// DefaultAudioBannerViewPresenter.swift
// Quran
//
// Created by Mohamed Afifi on 5/12/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import UIKit
import KVOController_Swift
class DefaultAudioBannerViewPresenter: NSObject, AudioBannerViewPresenter, AudioPlayerInteractorDelegate {
let qariRetreiver: AnyDataRetriever<[Qari]>
let persistence: SimplePersistence
let gaplessAudioPlayer: AudioPlayerInteractor
let gappedAudioPlayer: AudioPlayerInteractor
var audioPlayer: AudioPlayerInteractor {
switch selectedQari.audioType {
case .gapless:
return gaplessAudioPlayer
case .gapped:
return gappedAudioPlayer
}
}
weak var view: AudioBannerView?
weak var delegate: AudioBannerViewPresenterDelegate?
var selectedQariIndex: Int = 0 {
didSet {
persistence.setValue(selectedQari.id, forKey: .LastSelectedQariId)
}
}
var qaris: [Qari] = []
var selectedQari: Qari {
return qaris[selectedQariIndex]
}
fileprivate var repeatCount: AudioRepeat = .none {
didSet {
view?.setRepeatCount(repeatCount)
}
}
fileprivate var playing: Bool = false {
didSet {
if playing {
view?.setPlaying()
} else {
view?.setPaused()
}
}
}
init(persistence: SimplePersistence,
qariRetreiver: AnyDataRetriever<[Qari]>,
gaplessAudioPlayer: AudioPlayerInteractor,
gappedAudioPlayer: AudioPlayerInteractor) {
self.persistence = persistence
self.qariRetreiver = qariRetreiver
self.gaplessAudioPlayer = gaplessAudioPlayer
self.gappedAudioPlayer = gappedAudioPlayer
super.init()
self.gaplessAudioPlayer.delegate = self
self.gappedAudioPlayer.delegate = self
}
func onViewDidLoad() {
view?.hideAllControls()
qariRetreiver.retrieve { [weak self] (qaris) in
guard let `self` = self else {
return
}
self.qaris = qaris
// get last selected qari id
let lastSelectedQariId = self.persistence.valueForKey(.LastSelectedQariId)
let index = qaris.index { $0.id == lastSelectedQariId }
if let selectedIndex = index {
self.selectedQariIndex = selectedIndex
}
self.audioPlayer.checkIfDownloading { [weak self] (downloading) in
if !downloading {
Queue.main.async { self?.showQariView() }
}
}
}
}
fileprivate func showQariView() {
Crash.setValue(selectedQariIndex, forKey: .QariId)
view?.setQari(name: selectedQari.name, image: selectedQari.imageName.flatMap { UIImage(named: $0) })
}
func setQariIndex(_ index: Int) {
selectedQariIndex = index
showQariView()
}
// MARK: - AudioBannerViewDelegate
func onPlayTapped() {
guard let currentPage = delegate?.currentPage() else { return }
repeatCount = .none
// start downloading & playing
audioPlayer.playAudioForQari(selectedQari, atPage: currentPage)
}
func onPauseResumeTapped() {
playing = !playing
if playing {
audioPlayer.resumeAudio()
} else {
audioPlayer.pauseAudio()
}
}
func onStopTapped() {
audioPlayer.stopAudio()
}
func onForwardTapped() {
audioPlayer.goForward()
}
func onBackwardTapped() {
audioPlayer.goBackward()
}
func onRepeatTapped() {
repeatCount = repeatCount.next()
}
func onQariTapped() {
delegate?.showQariListSelectionWithQari(qaris, selectedIndex: selectedQariIndex)
}
func onCancelDownloadTapped() {
audioPlayer.cancelDownload()
}
// MARK: - AudioPlayerInteractorDelegate
let progressKeyPath = "fractionCompleted"
var progress: Foundation.Progress? {
didSet {
if let oldValue = oldValue {
unobserve(oldValue, keyPath: progressKeyPath)
}
if let newValue = progress {
observe(retainedObservable: newValue,
keyPath: progressKeyPath,
options: [.initial, .new]) { [weak self] (observable, change: ChangeData<Double>) in
if let newValue = change.newValue {
Queue.main.async { self?.view?.setDownloading(Float(newValue)) }
}
}
}
}
}
func willStartDownloading() {
Crash.setValue(true, forKey: .DownloadingQuran)
Queue.main.async { self.view?.setDownloading(0) }
}
func didStartDownloadingAudioFiles(progress: Foundation.Progress) {
self.progress = progress
}
func onPlayingStarted() {
Crash.setValue(false, forKey: .DownloadingQuran)
self.progress = nil
Queue.main.async { self.playing = true }
}
func onPlaybackResumed() {
Queue.main.async { self.playing = true }
}
func onPlaybackPaused() {
Queue.main.async { self.playing = false }
}
func highlight(_ ayah: AyahNumber) {
Crash.setValue(ayah, forKey: .PlayingAyah)
Queue.main.async { self.delegate?.highlightAyah(ayah) }
}
func onFailedDownloadingWithError(_ error: Error) {
Queue.main.async {
let message = (error as? CustomStringConvertible)?.description ?? "Error downloading files"
UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: "Ok").show()
}
}
func onPlaybackOrDownloadingCompleted() {
Crash.setValue(nil, forKey: .PlayingAyah)
Crash.setValue(false, forKey: .DownloadingQuran)
Queue.main.async {
self.showQariView()
self.delegate?.removeHighlighting()
}
}
}
| mit | 911722d5ac6518d449b8993db78f867a | 27.871429 | 108 | 0.600363 | 4.815727 | false | false | false | false |
rustedivan/tapmap | geobaketool/Operations/OperationParseGeoJson.swift | 1 | 5271 | //
// OperationParseGeoJson.swift
// tapmap
//
// Created by Ivan Milles on 2017-04-16.
// Copyright © 2017 Wildbrain. All rights reserved.
//
import Foundation
import SwiftyJSON
class OperationParseGeoJson : Operation {
let input : JSON
let report : ProgressReport
let level : ToolGeoFeature.Level
var output : ToolGeoFeatureMap?
init(json _json: JSON, as _level: ToolGeoFeature.Level, reporter: @escaping ProgressReport) {
input = _json
level = _level
report = reporter
}
override func main() {
guard !isCancelled else { print("Cancelled before starting"); return }
report(0.0, "Parsing \(level)", false)
output = parseFeatures(json: input, dataSet: level)
report(1.0, "Parsed \(level)", true)
}
fileprivate func parseFeatures(json: JSON,
dataSet: ToolGeoFeature.Level) -> ToolGeoFeatureMap? {
guard json["type"] == "FeatureCollection" else {
print("Warning: Root node is not multi-feature")
return ToolGeoFeatureMap() // This is OK.
}
guard let featureArray = json["features"].array else {
print("Error: Did not find the \"features\" array")
return nil
}
let numFeatures = featureArray.count
var parseCount = 0
let parsedFeatures = featureArray.compactMap { (featureJson) -> (RegionHash, ToolGeoFeature)? in
guard let f = parseFeature(featureJson, into: level) else {
return nil
}
report(Double(parseCount) / Double(numFeatures), f.name, false)
parseCount += 1
return (f.geographyId.hashed, f)
}
return ToolGeoFeatureMap(parsedFeatures) { (lhs, rhs) -> ToolGeoFeature in
print("Key collision between \(lhs.geographyId.key) and \(rhs.geographyId.key)")
return lhs
}
}
fileprivate func parseFeature(_ json: JSON, into level: ToolGeoFeature.Level) -> ToolGeoFeature? {
let properties = json["properties"]
guard let featureName = properties["NAME"].string ?? properties["name"].string else {
print("No name in feature")
return nil
}
guard let featureType = json["geometry"]["type"].string else {
print("No feature type in geometry for \"\(featureName)\"")
return nil
}
let loadedPolygons: [Polygon]
switch featureType {
case "MultiPolygon":
let polygonsJson = json["geometry"]["coordinates"]
loadedPolygons = polygonsJson.arrayValue.compactMap { parsePolygon($0) }
case "Polygon":
let polygonJson = json["geometry"]["coordinates"]
if let polygon = parsePolygon(polygonJson) {
loadedPolygons = [polygon]
} else {
print("Polygon in \"\(featureName)\" has no coordinate list.")
loadedPolygons = []
}
case "Point":
let pointJson = json["geometry"]["coordinates"]
if let point = parsePoint(pointJson) {
loadedPolygons = [point]
} else {
print("Point in \"\(featureName)\" has no coordinate.")
loadedPolygons = []
}
default:
print("Malformed feature in \(featureName)")
return nil
}
// Flatten string/value properties
let stringProps = properties.dictionaryValue
.filter { $0.value.type == .string }
.mapValues { $0.stringValue } as ToolGeoFeature.GeoStringProperties
let valueProps = properties.dictionaryValue
.filter { $0.value.type == .number }
.mapValues { $0.doubleValue } as ToolGeoFeature.GeoValueProperties
return ToolGeoFeature(level: level,
polygons: loadedPolygons,
tessellations: [],
places: nil,
children: nil,
stringProperties: stringProps,
valueProperties: valueProps)
}
fileprivate func parsePolygon(_ polygonJson: JSON) -> Polygon? {
guard let ringsJson = polygonJson.array, !ringsJson.isEmpty else {
print("Polygon has no ring array")
return nil
}
let parsedRings = ringsJson.map { parseRing($0.arrayValue) }
return Polygon(rings: parsedRings)
}
fileprivate func parseRing(_ coords: [JSON]) -> VertexRing {
var outVertices: [Vertex] = []
for c in coords {
guard c.type == .array else {
print("Coordinate has unexpected internal type: \(c.type)")
continue
}
let v = Vertex(c[0].doubleValue,
c[1].doubleValue)
outVertices.append(v)
}
return VertexRing(vertices: outVertices)
}
fileprivate func parsePoint(_ pointJson: JSON) -> Polygon? {
guard pointJson.type == .array else {
print("Coordinate has unexpected internal type: \(pointJson.type)")
return nil
}
let midpoint = Vertex(pointJson[0].doubleValue,
pointJson[1].doubleValue)
let exteriorRing = makeStar(around: midpoint, radius: 0.1, points: 5)
return Polygon(rings: [exteriorRing])
}
fileprivate func makeStar(around p: Vertex, radius: Float, points: Int) -> VertexRing {
let vertices = 0..<points * 2
let angles = vertices.map { p -> Double in
let a0 = Double.pi / 2.0
let n = Double(points)
return Double(a0 + Double(p) * 2.0 * Double.pi / n)
}
let circle = angles.map { Vertex(cos($0), sin($0)) }
let star = circle.enumerated().map { (offset: Int, element: Vertex) -> Vertex in
let radius = (offset % 2 == 0) ? 1.0 : 0.6
return Vertex(element.x * radius, element.y * radius)
}
let positionedStar = star.map { Vertex($0.x + p.x, $0.y + p.y) }
return VertexRing(vertices: positionedStar)
}
}
| mit | ff3dfdef50607d797805b0ea42d070cd | 30 | 99 | 0.665465 | 3.558406 | false | false | false | false |
J-Mendes/Weather | Weather/Weather/Extensions/UIImageView+Weather.swift | 1 | 883 | //
// UIImageView+Weather.swift
// Weather
//
// Created by Jorge Mendes on 05/07/17.
// Copyright © 2017 Jorge Mendes. All rights reserved.
//
import UIKit
extension UIImageView {
// MARK: - Async load image
internal func loadImageFrom(link: String, placeholder: String? = nil) {
if placeholder != nil {
DispatchQueue.main.async() { () -> Void in
self.image = UIImage(named: placeholder!)
}
}
NetworkService().getImage(link: link) { (image: UIImage?, error: Error?) in
if error == nil && image != nil {
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}
}
}
internal func cancelLoadImageFrom(link: String) {
NetworkService().cancelRequests(url: link)
}
}
| gpl-3.0 | 31b74305209decc612fb141caae58ccb | 24.2 | 83 | 0.531746 | 4.5 | false | false | false | false |
ethanneff/organize | Organize/IntroViewController.swift | 1 | 2651 | import UIKit
class IntroViewController: UIViewController {
// MARK: - properties
let label: UILabel = UILabel()
let introMessages = [
"level up. reach your full potential.",
"1% better than yesterday.",
"100% focus. always.",
"keep up the momentum.",
"look for ways to both get ahead."
]
// MARK: - load
override func loadView() {
super.loadView()
createView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
label.text = introMessages[Int(arc4random_uniform(UInt32(introMessages.count)))]
}
// MARK: - create
private func createView() {
let indicator = UIActivityIndicatorView()
let image = UIImageView()
let title = UILabel()
view.backgroundColor = Constant.Color.blue
view.addSubview(image)
view.addSubview(indicator)
view.addSubview(title)
title.text = "Organize"
title.font = .boldSystemFontOfSize(22)
title.textColor = .whiteColor()
title.translatesAutoresizingMaskIntoConstraints = false
indicator.activityIndicatorViewStyle = .WhiteLarge
indicator.hidesWhenStopped = true
indicator.startAnimating()
indicator.translatesAutoresizingMaskIntoConstraints = false
image.image = UIImage(named: "icon")!
image.contentMode = .ScaleAspectFit
image.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: title, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: title, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: -view.frame.height/4),
NSLayoutConstraint(item: image, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: image, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: image, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: indicator, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: view.frame.height/4),
])
}
}
| mit | 944b9973a8f58b20178fdeb69eb48359 | 39.784615 | 163 | 0.701622 | 4.578584 | false | false | false | false |
worchyld/FanDuelSample | FanDuelSample/Pods/Dollar/Sources/Dollar.swift | 2 | 60244 | //
// ___ ___ __ ___ ________ _________
// _|\ \__|\ \ |\ \|\ \|\ _____\\___ ___\
// |\ ____\ \ \ \ \ \ \ \ \ \__/\|___ \ \_|
// \ \ \___|\ \ \ __\ \ \ \ \ \ __\ \ \ \
// \ \_____ \ \ \|\__\_\ \ \ \ \ \_| \ \ \
// \|____|\ \ \____________\ \__\ \__\ \ \__\
// ____\_\ \|____________|\|__|\|__| \|__|
// |\___ __\
// \|___|\__\_|
// \|__|
//
// Dollar.swift
// $ - A functional tool-belt for Swift Language
//
// Created by Ankur Patel on 6/3/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
#if os(Linux)
import Glibc
#endif
import Foundation
fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
open class $ {
/// ___ ___ _______ ___ ________ _______ ________
/// |\ \|\ \|\ ___ \ |\ \ |\ __ \|\ ___ \ |\ __ \
/// \ \ \\\ \ \ __/|\ \ \ \ \ \|\ \ \ __/|\ \ \|\ \
/// \ \ __ \ \ \_|/_\ \ \ \ \ ____\ \ \_|/_\ \ _ _\
/// \ \ \ \ \ \ \_|\ \ \ \____\ \ \___|\ \ \_|\ \ \ \\ \|
/// \ \__\ \__\ \_______\ \_______\ \__\ \ \_______\ \__\\ _\
/// \|__|\|__|\|_______|\|_______|\|__| \|_______|\|__|\|__|
///
/// Creates a function that executes passed function only after being called n times.
///
/// - parameter num: Number of times after which to call function.
/// - parameter function: Function to be called that takes params.
/// - returns: Function that can be called n times after which the callback function is called.
open class func after<T, E>(_ num: Int, function: @escaping (T...) -> E) -> ((T...) -> E?) {
var counter = num
return { (params: T...) -> E? in
typealias Function = ([T]) -> E
counter -= 1
if counter <= 0 {
let f = unsafeBitCast(function, to: Function.self)
return f(params)
}
return .none
}
}
/// Creates a function that executes passed function only after being called n times.
///
/// - parameter num: Number of times after which to call function.
/// - parameter function: Function to be called that does not take any params.
/// - returns: Function that can be called n times after which the callback function is called.
open class func after<T>(_ num: Int, function: @escaping () -> T) -> (() -> T?) {
let f = self.after(num) { (params: Any?...) -> T in
return function()
}
return { f() }
}
/// Creates an array of elements from the specified indexes, or keys, of the collection.
/// Indexes may be specified as individual arguments or as arrays of indexes.
///
/// - parameter array: The array to source from
/// - parameter indexes: Get elements from these indexes
/// - returns: New array with elements from the indexes specified.
open class func at<T>(_ array: [T], indexes: Int...) -> [T] {
return self.at(array, indexes: indexes)
}
/// Creates an array of elements from the specified indexes, or keys, of the collection.
/// Indexes may be specified as individual arguments or as arrays of indexes.
///
/// - parameter array: The array to source from
/// - parameter indexes: Get elements from these indexes
/// - returns: New array with elements from the indexes specified.
open class func at<T>(_ array: [T], indexes: [Int]) -> [T] {
var result: [T] = []
for index in indexes {
result.append(array[index])
}
return result
}
/// Creates a function that, when called, invokes func with the binding of arguments provided.
///
/// - parameter function: Function to be bound.
/// - parameter parameters: Parameters to be passed into the function when being invoked.
/// - returns: A new function that when called will invoked the passed function with the parameters specified.
open class func bind<T, E>(_ function: @escaping (T...) -> E, _ parameters: T...) -> (() -> E) {
return { () -> E in
typealias Function = ([T]) -> E
let f = unsafeBitCast(function, to: Function.self)
return f(parameters)
}
}
/// Creates an array of elements split into groups the length of size.
/// If array can’t be split evenly, the final chunk will be the remaining elements.
///
/// - parameter array: to chunk
/// - parameter size: size of each chunk
/// - returns: array elements chunked
open class func chunk<T>(_ array: [T], size: Int = 1) -> [[T]] {
var result = [[T]]()
var chunk = -1
for (index, elem) in array.enumerated() {
if index % size == 0 {
result.append([T]())
chunk += 1
}
result[chunk].append(elem)
}
return result
}
/// Creates an array with all nil values removed.
///
/// - parameter array: Array to be compacted.
/// - returns: A new array that doesnt have any nil values.
open class func compact<T>(_ array: [T?]) -> [T] {
var result: [T] = []
for elem in array {
if let val = elem {
result.append(val)
}
}
return result
}
/// Compose two or more functions passing result of the first function
/// into the next function until all the functions have been evaluated
///
/// - parameter functions: - list of functions
/// - returns: A function that can be called with variadic parameters of values
open class func compose<T>(_ functions: ((T...) -> [T])...) -> ((T...) -> [T]) {
typealias Function = ([T]) -> [T]
return {
var result = $0
for fun in functions {
let f = unsafeBitCast(fun, to: Function.self)
result = f(result)
}
return result
}
}
/// Compose two or more functions passing result of the first function
/// into the next function until all the functions have been evaluated
///
/// - parameter functions: - list of functions
/// - returns: A function that can be called with array of values
open class func compose<T>(_ functions: (([T]) -> [T])...) -> (([T]) -> [T]) {
return {
var result = $0
for fun in functions {
result = fun(result)
}
return result
}
}
/// Checks if a given value is present in the array.
///
/// - parameter array: The array to check against.
/// - parameter value: The value to check.
/// - returns: Whether value is in the array.
open class func contains<T: Equatable>(_ array: [T], value: T) -> Bool {
return array.contains(value)
}
/// Create a copy of an array
///
/// - parameter array: The array to copy
/// - returns: New copy of array
open class func copy<T>(_ array: [T]) -> [T] {
var newArr: [T] = []
for elem in array {
newArr.append(elem)
}
return newArr
}
/// Cycles through the array indefinetly passing each element into the callback function
///
/// - parameter array: to cycle through
/// - parameter callback: function to call with the element
open class func cycle<T, U>(_ array: [T], callback: (T) -> U) {
while true {
for elem in array {
_ = callback(elem)
}
}
}
/// Cycles through the array n times passing each element into the callback function
///
/// - parameter array: to cycle through
/// - parameter times: Number of times to cycle through the array
/// - parameter callback: function to call with the element
open class func cycle<T, U>(_ array: [T], _ times: Int, callback: (T) -> U) {
for _ in 0..<times {
for elem in array {
_ = callback(elem)
}
}
}
/// Creates an array excluding all values of the provided arrays in order
///
/// - parameter arrays: The arrays to difference between.
/// - returns: The difference between the first array and all the remaining arrays from the arrays params.
open class func differenceInOrder<T: Equatable>(_ arrays: [[T]]) -> [T] {
return $.reduce(self.rest(arrays), initial: self.first(arrays)!) { (result, arr) -> [T] in
return result.filter() { !arr.contains($0) }
}
}
/// Creates an array excluding all values of the provided arrays with or without order
/// Without order difference is much faster and at times 100% than difference with order
///
/// - parameter arrays: The arrays to difference between.
/// - parameter inOrder: Optional Paramter which is true by default
/// - returns: The difference between the first array and all the remaining arrays from the arrays params.
open class func difference<T: Hashable>(_ arrays: [T]..., inOrder: Bool = true) -> [T] {
if inOrder {
return self.differenceInOrder(arrays)
} else {
var result: [T] = []
var map: [T: Int] = [T: Int]()
let firstArr: [T] = self.first(arrays)!
let restArr: [[T]] = self.rest(arrays) as [[T]]
for elem in firstArr {
if let val = map[elem] {
map[elem] = val + 1
} else {
map[elem] = 1
}
}
for arr in restArr {
for elem in arr {
map.removeValue(forKey: elem)
}
}
for (key, count) in map {
for _ in 0..<count {
result.append(key)
}
}
return result
}
}
/// Call the callback passing each element in the array
///
/// - parameter array: The array to iterate over
/// - parameter callback: function that gets called with each item in the array
/// - returns: The array passed
open class func each<T>(_ array: [T], callback: (T) -> ()) -> [T] {
for elem in array {
callback(elem)
}
return array
}
/// Call the callback passing index of the element and each element in the array
///
/// - parameter array: The array to iterate over
/// - parameter callback: function that gets called with each item in the array with its index
/// - returns: The array passed
open class func each<T>(_ array: [T], callback: (Int, T) -> ()) -> [T] {
for (index, elem): (Int, T) in array.enumerated() {
callback(index, elem)
}
return array
}
/// Call the callback on all elements that meet the when condition
///
/// - parameter array: The array to check.
/// - parameter when: Condition to check before performing callback
/// - parameter callback: Check whether element value is true or false.
/// - returns: The array passed
open class func each<T>(_ array: [T], when: (T) -> Bool, callback: (T) -> ()) -> [T] {
for elem in array where when(elem) {
callback(elem)
}
return array
}
/// Checks if two optionals containing Equatable types are equal.
///
/// - parameter value: The first optional to check.
/// - parameter other: The second optional to check.
/// - returns: true if the optionals contain two equal values, or both are nil; false otherwise.
open class func equal<T: Equatable>(_ value: T?, _ other: T?) -> Bool {
switch (value, other) {
case (.none, .none):
return true
case (.none, .some(_)):
return false
case (.some(_), .none):
return false
case (.some(let unwrappedValue), .some(let otherUnwrappedValue)):
return unwrappedValue == otherUnwrappedValue
}
}
/// Checks if the given callback returns true value for all items in the array.
///
/// - parameter array: The array to check.
/// - parameter callback: Check whether element value is true or false.
/// - returns: First element from the array.
open class func every<T>(_ array: [T], callback: (T) -> Bool) -> Bool {
for elem in array {
if !callback(elem) {
return false
}
}
return true
}
/// Returns Factorial of integer
///
/// - parameter num: number whose factorial needs to be calculated
/// - returns: factorial
open class func factorial(_ num: Int) -> Int {
guard num > 0 else { return 1 }
return num * $.factorial(num - 1)
}
/// Get element from an array at the given index which can be negative
/// to find elements from the end of the array
///
/// - parameter array: The array to fetch from
/// - parameter index: Can be positive or negative to find from end of the array
/// - parameter orElse: Default value to use if index is out of bounds
/// - returns: Element fetched from the array or the default value passed in orElse
open class func fetch<T>(_ array: [T], _ index: Int, orElse: T? = .none) -> T! {
if index < 0 && -index < array.count {
return array[array.count + index]
} else if index < array.count {
return array[index]
} else {
return orElse
}
}
/// Fills elements of array with value from start up to, but not including, end.
///
/// - parameter array: to fill
/// - parameter withElem: the element to replace
/// - parameter startIndex: start index
/// - parameter endIndex: end index
/// - returns: array elements chunked
open class func fill<T>(_ array: inout [T], withElem elem: T, startIndex: Int = 0, endIndex: Int? = .none) -> [T] {
let endIndex = endIndex ?? array.count
for (index, _) in array.enumerated() {
if index > endIndex { break }
if index >= startIndex && index <= endIndex {
array[index] = elem
}
}
return array
}
/// Iterates over elements of an array and returning the first element
/// that the callback returns true for.
///
/// - parameter array: The array to search for the element in.
/// - parameter callback: The callback function to tell whether element is found.
/// - returns: Optional containing either found element or nil.
open class func find<T>(_ array: [T], callback: (T) -> Bool) -> T? {
for elem in array {
let result = callback(elem)
if result {
return elem
}
}
return .none
}
/// This method is like find except that it returns the index of the first element
/// that passes the callback check.
///
/// - parameter array: The array to search for the element in.
/// - parameter callback: Function used to figure out whether element is the same.
/// - returns: First element's index from the array found using the callback.
open class func findIndex<T>(_ array: [T], callback: (T) -> Bool) -> Int? {
for (index, elem): (Int, T) in array.enumerated() {
if callback(elem) {
return index
}
}
return .none
}
/// This method is like findIndex except that it iterates over elements of the array
/// from right to left.
///
/// - parameter array: The array to search for the element in.
/// - parameter callback: Function used to figure out whether element is the same.
/// - returns: Last element's index from the array found using the callback.
open class func findLastIndex<T>(_ array: [T], callback: (T) -> Bool) -> Int? {
let count = array.count
for (index, _) in array.enumerated() {
let reverseIndex = count - (index + 1)
let elem: T = array[reverseIndex]
if callback(elem) {
return reverseIndex
}
}
return .none
}
/// Gets the first element in the array.
///
/// - parameter array: The array to wrap.
/// - returns: First element from the array.
open class func first<T>(_ array: [T]) -> T? {
if array.isEmpty {
return .none
} else {
return array[0]
}
}
/// Splits a collection into sets, grouped by the result of running each value through a callback.
///
/// - parameter array: The array to group
/// - parameter callback: Function whose response will be used as a key in the new string
/// - returns: grouped collection
open class func groupBy<T, U: Hashable>(_ array: [T], callback: (T) -> U) -> [U: [T]] {
var grouped = [U: [T]]()
for element in array {
let key = callback(element)
if var arr = grouped[key] {
arr.append(element)
grouped[key] = arr
} else {
grouped[key] = [element]
}
}
return grouped
}
/// Gets the second element in the array.
///
/// - parameter array: The array to wrap.
/// - returns: Second element from the array.
open class func second<T>(_ array: [T]) -> T? {
if array.count < 2 {
return .none
} else {
return array[1]
}
}
/// Gets the third element in the array.
///
/// - parameter array: The array to wrap.
/// - returns: Third element from the array.
open class func third<T>(_ array: [T]) -> T? {
if array.count < 3 {
return .none
} else {
return array[2]
}
}
/// Flattens a nested array of any depth.
///
/// - parameter array: The array to flatten.
/// - returns: Flattened array.
open class func flatten<T>(_ array: [T]) -> [T] {
var resultArr: [T] = []
for elem: T in array {
if let val = elem as? [T] {
resultArr += self.flatten(val)
} else {
resultArr.append(elem)
}
}
return resultArr
}
/// Maps a function that converts elements to a list and then concatenates them.
///
/// - parameter array: The array to map.
/// - parameter function: callback function that should return flattened values
/// - returns: The array with the transformed values concatenated together.
open class func flatMap<T, U>(_ array: [T], function: (T) -> ([U])) -> [U] {
return array.map(function).reduce([], +)
}
/// Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional.
///
/// - parameter value: The array to map.
/// - parameter function: callback function that should return mapped values
/// - returns: The array with the transformed values concatenated together.
open class func flatMap<T, U>(_ value: T?, function: (T) -> (U?)) -> U? {
if let unwrapped = value.map(function) {
return unwrapped
} else {
return .none
}
}
/// Returns size of the array
///
/// - parameter array: The array to size.
/// - returns: size of the array
open class func size<T>(_ array: [T]) -> Int {
return array.count
}
/// Randomly shuffles the elements of an array.
///
/// - parameter array: The array to shuffle.
/// - returns: Shuffled array
open class func shuffle<T>(_ array: [T]) -> [T] {
var newArr = self.copy(array)
// Implementation of Fisher-Yates shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_Shuffle
for index in 0..<array.count {
let randIndex = self.random(index)
if index != randIndex {
Swift.swap(&newArr[index], &newArr[randIndex])
}
}
return newArr
}
/// This method returns a dictionary of values in an array mapping to the
/// total number of occurrences in the array.
///
/// - parameter array: The array to source from.
/// - returns: Dictionary that contains the key generated from the element passed in the function.
open class func frequencies<T>(_ array: [T]) -> [T: Int] {
return self.frequencies(array) { $0 }
}
/// This method returns a dictionary of values in an array mapping to the
/// total number of occurrences in the array. If passed a function it returns
/// a frequency table of the results of the given function on the arrays elements.
///
/// - parameter array: The array to source from.
/// - parameter function: The function to get value of the key for each element to group by.
/// - returns: Dictionary that contains the key generated from the element passed in the function.
open class func frequencies<T, U: Equatable>(_ array: [T], function: (T) -> U) -> [U: Int] {
var result = [U: Int]()
for elem in array {
let key = function(elem)
if let freq = result[key] {
result[key] = freq + 1
} else {
result[key] = 1
}
}
return result
}
/// GCD function return greatest common denominator
///
/// - parameter first: number
/// - parameter second: number
/// - returns: Greatest common denominator
open class func gcd(_ first: Int, _ second: Int) -> Int {
var first = first
var second = second
while second != 0 {
(first, second) = (second, first % second)
}
return Swift.abs(first)
}
/// LCM function return least common multiple
///
/// - parameter first: number
/// - parameter second: number
/// - returns: Least common multiple
open class func lcm(_ first: Int, _ second: Int) -> Int {
return (first / $.gcd(first, second)) * second
}
/// The identity function. Returns the argument it is given.
///
/// - parameter arg: Value to return
/// - returns: Argument that was passed
open class func id<T>(_ arg: T) -> T {
return arg
}
/// Gets the index at which the first occurrence of value is found.
///
/// - parameter array: The array to source from.
/// - parameter value: Value whose index needs to be found.
/// - returns: Index of the element otherwise returns nil if not found.
open class func indexOf<T: Equatable>(_ array: [T], value: T) -> Int? {
return self.findIndex(array) { $0 == value }
}
/// Gets all but the last element or last n elements of an array.
///
/// - parameter array: The array to source from.
/// - parameter numElements: The number of elements to ignore in the end.
/// - returns: Array of initial values.
open class func initial<T>(_ array: [T], numElements: Int = 1) -> [T] {
var result: [T] = []
if array.count > numElements && numElements >= 0 {
for index in 0..<(array.count - numElements) {
result.append(array[index])
}
}
return result
}
/// Creates an array of unique values present in all provided arrays.
///
/// - parameter arrays: The arrays to perform an intersection on.
/// - returns: Intersection of all arrays passed.
open class func intersection<T: Hashable>(_ arrays: [T]...) -> [T] {
var map: [T: Int] = [T: Int]()
for arr in arrays {
for elem in arr {
if let val: Int = map[elem] {
map[elem] = val + 1
} else {
map[elem] = 1
}
}
}
var result: [T] = []
let count = arrays.count
for (key, value) in map {
if value == count {
result.append(key)
}
}
return result
}
/// Returns true if i is in range
///
/// - parameter index: to check if it is in range
/// - parameter isIn: to check in
/// - returns: true if it is in range otherwise false
open class func it<T: Comparable>(_ index: T, isIn range: Range<T>) -> Bool {
return index >= range.lowerBound && index < range.upperBound
}
/// Joins the elements in the array to create a concatenated element of the same type.
///
/// - parameter array: The array to join the elements of.
/// - parameter separator: The separator to join the elements with.
/// - returns: Joined element from the array of elements.
open class func join(_ array: [String], separator: String) -> String {
return array.joined(separator: separator)
}
/// Creates an array of keys given a dictionary.
///
/// - parameter dictionary: The dictionary to source from.
/// - returns: Array of keys from dictionary.
open class func keys<T, U>(_ dictionary: [T: U]) -> [T] {
var result: [T] = []
for key in dictionary.keys {
result.append(key)
}
return result
}
/// Gets the last element from the array.
///
/// - parameter array: The array to source from.
/// - returns: Last element from the array.
open class func last<T>(_ array: [T]) -> T? {
if array.isEmpty {
return .none
} else {
return array[array.count - 1]
}
}
/// Gets the index at which the last occurrence of value is found.
///
/// - parameter array: The array to source from.
/// - parameter value: The value whose last index needs to be found.
/// - returns: Last index of element if found otherwise returns nil.
open class func lastIndexOf<T: Equatable>(_ array: [T], value: T) -> Int? {
return self.findLastIndex(array) { $0 == value }
}
/// Maps each element to new value based on the map function passed
///
/// - parameter collection: The collection to source from
/// - parameter transform: The mapping function
/// - returns: Array of elements mapped using the map function
open class func map<T: Collection, E>(_ collection: T, transform: (T.Iterator.Element) -> E) -> [E] {
return collection.map(transform)
}
/// Maps each element to new value based on the map function passed
///
/// - parameter sequence: The sequence to source from
/// - parameter transform: The mapping function
/// - returns: Array of elements mapped using the map function
open class func map<T: Sequence, E>(_ sequence: T, transform: (T.Iterator.Element) -> E) -> [E] {
return sequence.map(transform)
}
/// Retrieves the maximum value in an array.
///
/// - parameter array: The array to source from.
/// - returns: Maximum element in array.
open class func max<T: Comparable>(_ array: [T]) -> T? {
if var maxVal = array.first {
for elem in array {
if maxVal < elem {
maxVal = elem
}
}
return maxVal
}
return .none
}
/// Get memoized function to improve performance
///
/// - parameter function: The function to memoize.
/// - returns: Memoized function
open class func memoize<T: Hashable, U>(_ function: @escaping (((T) -> U), T) -> U) -> ((T) -> U) {
var cache = [T: U]()
var funcRef: ((T) -> U)!
funcRef = { (param: T) -> U in
if let cacheVal = cache[param] {
return cacheVal
} else {
cache[param] = function(funcRef, param)
return cache[param]!
}
}
return funcRef
}
/// Merge dictionaries together, later dictionaries overiding earlier values of keys.
///
/// - parameter dictionaries: The dictionaries to source from.
/// - returns: Merged dictionary with all of its keys and values.
open class func merge<T, U>(_ dictionaries: [T: U]...) -> [T: U] {
var result = [T: U]()
for dict in dictionaries {
for (key, value) in dict {
result[key] = value
}
}
return result
}
/// Merge arrays together in the supplied order.
///
/// - parameter arrays: The arrays to source from.
/// - returns: Array with all values merged, including duplicates.
open class func merge<T>(_ arrays: [T]...) -> [T] {
var result = [T]()
for arr in arrays {
result += arr
}
return result
}
/// Retrieves the minimum value in an array.
///
/// - parameter array: The array to source from.
/// - returns: Minimum value from array.
open class func min<T: Comparable>(_ array: [T]) -> T? {
if var minVal = array.first {
for elem in array {
if minVal > elem {
minVal = elem
}
}
return minVal
}
return .none
}
/// A no-operation function.
///
/// - returns: nil.
open class func noop() -> () {
}
/// Gets the number of seconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).
///
/// - returns: number of seconds as double
open class func now() -> TimeInterval {
return Date().timeIntervalSince1970
}
/// Creates a shallow clone of a dictionary excluding the specified keys.
///
/// - parameter dictionary: The dictionary to source from.
/// - parameter keys: The keys to omit from returning dictionary.
/// - returns: Dictionary with the keys specified omitted.
open class func omit<T, U>(_ dictionary: [T: U], keys: T...) -> [T: U] {
var result: [T: U] = [T: U]()
for (key, value) in dictionary {
if !self.contains(keys, value: key) {
result[key] = value
}
}
return result
}
/// Get a wrapper function that executes the passed function only once
///
/// - parameter function: That takes variadic arguments and return nil or some value
/// - returns: Wrapper function that executes the passed function only once
/// Consecutive calls will return the value returned when calling the function first time
open class func once<T, U>(_ function: @escaping (T...) -> U) -> (T...) -> U {
var result: U?
let onceFunc = { (params: T...) -> U in
typealias Function = ([T]) -> U
if let returnVal = result {
return returnVal
} else {
let f = unsafeBitCast(function, to: Function.self)
result = f(params)
return result!
}
}
return onceFunc
}
/// Get a wrapper function that executes the passed function only once
///
/// - parameter function: That takes variadic arguments and return nil or some value
/// - returns: Wrapper function that executes the passed function only once
/// Consecutive calls will return the value returned when calling the function first time
open class func once<U>(_ function: @escaping () -> U) -> () -> U {
var result: U?
let onceFunc = { () -> U in
if let returnVal = result {
return returnVal
} else {
result = function()
return result!
}
}
return onceFunc
}
/// Creates a function that, when called, invokes func with any additional partial arguments prepended to those provided to the new function.
///
/// - parameter function: to invoke
/// - parameter parameters: to pass the function when invoked
/// - returns: Function with partial arguments prepended
open class func partial<T, E> (_ function: @escaping (T...) -> E, _ parameters: T...) -> ((T...) -> E) {
return { (params: T...) -> E in
typealias Function = ([T]) -> E
let f = unsafeBitCast(function, to: Function.self)
return f(parameters + params)
}
}
/// Produces an array of arrays, each containing n elements, each offset by step.
/// If the final partition is not n elements long it is dropped.
///
/// - parameter array: The array to partition.
/// - parameter n: The number of elements in each partition.
/// - parameter step: The number of elements to progress between each partition. Set to n if not supplied.
/// - returns: Array partitioned into n element arrays, starting step elements apart.
open class func partition<T>(_ array: [T], n num: Int, step: Int? = .none) -> [[T]] {
var num = num
var step = step
var result = [[T]]()
if step == .none { step = num } // If no step is supplied move n each step.
if step < 1 { step = 1 } // Less than 1 results in an infinite loop.
if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason.
if num > array.count { return [[]] }
for i in self.range(from: 0, through: array.count - num, incrementBy: step!) {
result.append(Array(array[i..<(i + num)] as ArraySlice<T>))
}
return result
}
/// Produces an array of arrays, each containing n elements, each offset by step.
///
/// - parameter array: The array to partition.
/// - parameter n: The number of elements in each partition.
/// - parameter step: The number of elements to progress between each partition. Set to n if not supplied.
/// - parameter pad: An array of elements to pad the last partition if it is not long enough to
/// contain n elements. If there are not enough pad elements
/// the last partition may less than n elements long.
/// - returns: Array partitioned into n element arrays, starting step elements apart.
open class func partition<T>(_ array: [T], n num: Int, step: Int? = .none, pad: [T]?) -> [[T]] {
var array = array
var num = num
var step = step
var result: [[T]] = []
var need = 0
if step == .none { step = num } // If no step is supplied move n each step.
if step < 1 { step = 1 } // Less than 1 results in an infinite loop.
if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason.
for i in self.range(from: 0, to: array.count, incrementBy: step!) {
var end = i + num
if end > array.count { end = array.count }
result.append(Array(array[i..<end] as ArraySlice<T>))
if end != i + num { need = i + num - end; break }
}
if need != 0 {
if let padding = pad {
let end = padding.count > need ? need : padding.count
result[result.count - 1] += Array(padding[0..<end] as ArraySlice<T>)
}
}
return result
}
/// Produces an array of arrays, each containing n elements, each offset by step.
///
/// - parameter array: The array to partition.
/// - parameter n: The number of elements in each partition.
/// - parameter step: The number of elements to progress between each partition. Set to n if not supplied.
/// - returns: Array partitioned into n element arrays, starting step elements apart.
open class func partitionAll<T>(_ array: [T], n num: Int, step: Int? = .none) -> [[T]] {
var num = num
var step = step
var result = [[T]]()
if step == .none { step = num } // If no step is supplied move n each step.
if step < 1 { step = 1 } // Less than 1 results in an infinite loop.
if num < 1 { num = 0 } // Allow 0 if user wants [[],[],[]] for some reason.
for i in self.range(from: 0, to: array.count, incrementBy: step!) {
var end = i + num
if end > array.count { end = array.count }
result.append(Array(array[i..<end] as ArraySlice<T>))
}
return result
}
/// Applies function to each element in array, splitting it each time function returns a new value.
///
/// - parameter array: The array to partition.
/// - parameter function: Function which takes an element and produces an equatable result.
/// - returns: Array partitioned in order, splitting via results of function.
open class func partitionBy<T, U: Equatable>(_ array: [T], function: (T) -> U) -> [[T]] {
var result = [[T]]()
var lastValue: U? = .none
for item in array {
let value = function(item)
if let lastValue = lastValue, value == lastValue {
result[result.count-1].append(item)
} else {
result.append([item])
lastValue = value
}
}
return result
}
/// Creates a shallow clone of a dictionary composed of the specified keys.
///
/// - parameter dictionary: The dictionary to source from.
/// - parameter keys: The keys to pick values from.
/// - returns: Dictionary with the key and values picked from the keys specified.
open class func pick<T, U>(_ dictionary: [T: U], keys: T...) -> [T: U] {
var result: [T: U] = [T: U]()
for key in keys {
result[key] = dictionary[key]
}
return result
}
/// Retrieves the value of a specified property from all elements in the array.
///
/// - parameter array: The array to source from.
/// - parameter value: The property on object to pull out value from.
/// - returns: Array of values from array of objects with property of value.
open class func pluck<T, E>(_ array: [[T: E]], value: T) -> [E] {
var result: [E] = []
for obj in array {
if let val = obj[value] {
result.append(val)
}
}
return result
}
/// Removes all provided values from the given array.
///
/// - parameter array: The array to source from.
/// - parameter values: values to remove from the array
/// - returns: Array with values pulled out.
open class func pull<T: Equatable>(_ array: [T], values: T...) -> [T] {
return self.pull(array, values: values)
}
/// Removes all provided values from the given array.
///
/// - parameter array: The array to source from.
/// - parameter values: The values to remove.
/// - returns: Array with values pulled out.
open class func pull<T: Equatable>(_ array: [T], values: [T]) -> [T] {
return array.filter { !self.contains(values, value: $0) }
}
/// Removes all provided values from the given array at the given indices
///
/// - parameter array: The array to source from.
/// - parameter indices: The indices to remove from.
/// - returns: Array with values pulled out.
open class func pullAt<T: Equatable>(_ array: [T], indices: Int...) -> [T] {
var elemToRemove = [T]()
for index in indices {
elemToRemove.append(array[index])
}
return $.pull(array, values: elemToRemove)
}
/// Returns permutation of array
///
/// - parameter character: Characters to source the permutation
/// - returns: Array of permutation of the characters specified
open class func permutation<T>(_ elements: [T]) -> [String] where T : CustomStringConvertible {
guard elements.count > 1 else {
return $.map(elements) { $0.description }
}
let strings = self.permutation($.initial(elements))
if let char = $.last(elements) {
return $.reduce(strings, initial: []) { (result, str) -> [String] in
let splitStr = $.map(str.description.characters) { $0.description }
return result + $.map(0...splitStr.count) { (index) -> String in
var copy = $.copy(splitStr)
copy.insert(char.description, at: (splitStr.count - index))
return $.join(copy, separator: "")
}
}.sorted()
}
return []
}
/// Returns random number from 0 upto but not including upperBound
///
/// - parameter upperBound: upper bound when generating random number
/// - returns: Random number
open class func random(_ upperBound: Int) -> Int {
#if os(Linux)
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
let randomNumber = Glibc.random() % upperBound
#else
let randomNumber = Int(arc4random_uniform(UInt32(upperBound)))
#endif
return randomNumber
}
/// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
///
/// - parameter endVal: End value of range.
/// - returns: Array of elements based on the sequence starting from 0 to endVal and incremented by 1.
open class func range<T: Strideable>(_ endVal: T) -> [T] where T : ExpressibleByIntegerLiteral {
return self.range(from: 0, to: endVal)
}
/// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
///
/// - parameter from: Start value of range
/// - parameter to: End value of range
/// - returns: Array of elements based on the sequence that is incremented by 1
open class func range<T: Strideable>(from startVal: T, to endVal: T) -> [T] where T.Stride : ExpressibleByIntegerLiteral {
return self.range(from: startVal, to: endVal, incrementBy: 1)
}
/// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
///
/// - parameter from: Start value of range.
/// - parameter to: End value of range.
/// - parameter incrementBy: Increment sequence by.
/// - returns: Array of elements based on the sequence.
open class func range<T: Strideable>(from startVal: T, to endVal: T, incrementBy: T.Stride) -> [T] {
let range = stride(from: startVal, to: endVal, by: incrementBy)
return self.sequence(range)
}
/// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
///
/// - parameter from: Start value of range
/// - parameter through: End value of range
/// - returns: Array of elements based on the sequence that is incremented by 1
open class func range<T: Strideable>(from startVal: T, through endVal: T) -> [T] where T.Stride : ExpressibleByIntegerLiteral {
return self.range(from: startVal, to: endVal + 1, incrementBy: 1)
}
/// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
///
/// - parameter from: Start value of range.
/// - parameter through: End value of range.
/// - parameter incrementBy: Increment sequence by.
/// - returns: Array of elements based on the sequence.
open class func range<T: Strideable>(from startVal: T, through endVal: T, incrementBy: T.Stride) -> [T] {
return self.range(from: startVal, to: endVal + 1, incrementBy: incrementBy)
}
/// Reduce function that will resolve to one value after performing combine function on all elements
///
/// - parameter array: The array to source from.
/// - parameter initial: Initial value to seed the reduce function with
/// - parameter combine: Function that will combine the passed value with element in the array
/// - returns: The result of reducing all of the elements in the array into one value
open class func reduce<U, T>(_ array: [T], initial: U, combine: (U, T) -> U) -> U {
return array.reduce(initial, combine)
}
/// Creates an array of an arbitrary sequence. Especially useful with builtin ranges.
///
/// - parameter seq: The sequence to generate from.
/// - returns: Array of elements generated from the sequence.
open class func sequence<S: Sequence>(_ seq: S) -> [S.Iterator.Element] {
return Array<S.Iterator.Element>(seq)
}
/// Removes all elements from an array that the callback returns true.
///
/// - parameter array: The array to wrap.
/// - parameter callback: Remove elements for which callback returns true.
/// - returns: Array with elements filtered out.
open class func remove<T>(_ array: [T], callback: (T) -> Bool) -> [T] {
return array.filter { !callback($0) }
}
/// Removes an element from an array.
///
/// - parameter array: The array to source from.
/// - parameter value: Element that is to be removed
/// - returns: Array with element removed.
open class func remove<T: Equatable>(_ array: [T], value: T) -> [T] {
return self.remove(array, callback: {$0 == value})
}
/// The opposite of initial this method gets all but the first element or first n elements of an array.
///
/// - parameter array: The array to source from.
/// - parameter numElements: The number of elements to exclude from the beginning.
/// - returns: The rest of the elements.
open class func rest<T>(_ array: [T], numElements: Int = 1) -> [T] {
var result: [T] = []
if numElements < array.count && numElements >= 0 {
for index in numElements..<array.count {
result.append(array[index])
}
}
return result
}
/// Returns a sample from the array.
///
/// - parameter array: The array to sample from.
/// - returns: Random element from array.
open class func sample<T>(_ array: [T]) -> T {
return array[self.random(array.count)]
}
/// Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array.
///
/// - parameter array: The array to slice.
/// - parameter start: Start index.
/// - parameter end: End index.
/// - returns: First element from the array.
open class func slice<T>(_ array: [T], start: Int, end: Int = 0) -> [T] {
var uend = end
if uend == 0 {
uend = array.count
}
if end > array.count || start > array.count || uend < start {
return []
} else {
return Array(array[start..<uend])
}
}
/// Gives the smallest index at which a value should be inserted into a given the array is sorted.
///
/// - parameter array: The array to source from.
/// - parameter value: Find sorted index of this value.
/// - returns: Index of where the elemnt should be inserted.
open class func sortedIndex<T: Comparable>(_ array: [T], value: T) -> Int {
for (index, elem) in array.enumerated() {
if elem > value {
return index
}
}
return array.count
}
/// Invokes interceptor with the object and then returns object.
///
/// - parameter object: Object to tap into.
/// - parameter function: Callback function to invoke.
/// - returns: Returns the object back.
open class func tap<T>(_ object: T, function: (T) -> ()) -> T {
function(object)
return object
}
/// Call a function n times and also passes the index. If a value is returned
/// in the function then the times method will return an array of those values.
///
/// - parameter num: Number of times to call function.
/// - parameter function: The function to be called every time.
/// - returns: Values returned from callback function.
open class func times<T>(_ num: Int, function: () -> T) -> [T] {
return self.times(num) { (index: Int) -> T in
return function()
}
}
/// Call a function n times and also passes the index. If a value is returned
/// in the function then the times method will return an array of those values.
///
/// - parameter num: Number of times to call function
/// - parameter function: The function to be called every time
open class func times(_ num: Int, function: (Void) -> Void) {
_ = self.times(num) { (index: Int) -> () in
function()
}
}
/// Call a function n times and also passes the index. If a value is returned
/// in the function then the times method will return an array of those values.
///
/// - parameter num: Number of times to call function.
/// - parameter function: The function to be called every time that takes index.
/// - returns: Values returned from callback function.
open class func times<T>(_ num: Int, function: (Int) -> T) -> [T] {
var result: [T] = []
for index in (0..<num) {
result.append(function(index))
}
return result
}
/// Transposes matrix if able. If unable; parameter matrix is returned.
///
/// - parameter matrix: Generic matrix containing any type.
/// - returns: A transposed version of input matrix.
open class func transpose<T>(_ matrix: [[T]]) -> [[T]] {
guard matrix.filter({ return $0.count == matrix[0].count }).count == matrix.count else {
return matrix
}
var returnMatrix: [[T?]] = Array(repeating: Array(repeating: nil, count: matrix.count),
count: matrix.first!.count)
for (rowNumber, row) in matrix.enumerated() {
for (index, item) in row.enumerated() {
returnMatrix[index][rowNumber] = item
}
}
return returnMatrix.flatMap { $0.flatMap { $0 } }
}
/// Creates an array of unique values, in order, of the provided arrays.
///
/// - parameter arrays: The arrays to perform union on.
/// - returns: Resulting array after union.
open class func union<T: Hashable>(_ arrays: [T]...) -> [T] {
var result: [T] = []
for arr in arrays {
result += arr
}
return self.uniq(result)
}
/// Creates a duplicate-value-free version of an array.
///
/// - parameter array: The array to source from.
/// - returns: An array with unique values.
open class func uniq<T: Hashable>(_ array: [T]) -> [T] {
var result: [T] = []
var map: [T: Bool] = [T: Bool]()
for elem in array {
if map[elem] == .none {
result.append(elem)
}
map[elem] = true
}
return result
}
/// Create a duplicate-value-free version of an array based on the condition.
/// Uses the last value generated by the condition function
///
/// - parameter array: The array to source from.
/// - parameter condition: Called per iteration
/// - returns: An array with unique values.
open class func uniq<T: Hashable, U: Hashable>(_ array: [T], by condition: (T) -> U) -> [T] {
var result: [T] = []
var map: [U: Bool] = [U: Bool]()
for elem in array {
let val = condition(elem)
if map[val] == .none {
result.append(elem)
}
map[val] = true
}
return result
}
/// Creates an array of values of a given dictionary.
///
/// - parameter dictionary: The dictionary to source from.
/// - returns: An array of values from the dictionary.
open class func values<T, U>(_ dictionary: [T: U]) -> [U] {
var result: [U] = []
for value in dictionary.values {
result.append(value)
}
return result
}
/// Creates an array excluding all provided values.
///
/// - parameter array: The array to source from.
/// - parameter values: Values to exclude.
/// - returns: Array excluding provided values.
open class func without<T: Equatable>(_ array: [T], values: T...) -> [T] {
return self.pull(array, values: values)
}
/// Creates an array that is the symmetric difference of the provided arrays.
///
/// - parameter arrays: The arrays to perform xor on in order.
/// - returns: Resulting array after performing xor.
open class func xor<T: Hashable>(_ arrays: [T]...) -> [T] {
var map: [T: Bool] = [T: Bool]()
for arr in arrays {
for elem in arr {
map[elem] = !(map[elem] ?? false)
}
}
var result: [T] = []
for (key, value) in map {
if value {
result.append(key)
}
}
return result
}
/// Creates an array of grouped elements, the first of which contains the first elements
/// of the given arrays.
///
/// - parameter arrays: The arrays to be grouped.
/// - returns: An array of grouped elements.
open class func zip<T>(_ arrays: [T]...) -> [[T]] {
var result: [[T]] = []
for _ in self.first(arrays)! as [T] {
result.append([] as [T])
}
for (_, array) in arrays.enumerated() {
for (elemIndex, elem): (Int, T) in array.enumerated() {
result[elemIndex].append(elem)
}
}
return result
}
/// Creates an object composed from arrays of keys and values.
///
/// - parameter keys: The array of keys.
/// - parameter values: The array of values.
/// - returns: Dictionary based on the keys and values passed in order.
open class func zipObject<T, E>(_ keys: [T], values: [E]) -> [T: E] {
var result = [T: E]()
for (index, key) in keys.enumerated() {
result[key] = values[index]
}
return result
}
/// Returns the collection wrapped in the chain object
///
/// - parameter collection: of elements
/// - returns: Chain object
open class func chain<T>(_ collection: [T]) -> Chain<T> {
return Chain(collection)
}
}
// ________ ___ ___ ________ ___ ________
// |\ ____\|\ \|\ \|\ __ \|\ \|\ ___ \
// \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \\ \ \
// \ \ \ \ \ __ \ \ __ \ \ \ \ \\ \ \
// \ \ \____\ \ \ \ \ \ \ \ \ \ \ \ \\ \ \
// \ \_______\ \__\ \__\ \__\ \__\ \__\ \__\\ \__\
// \|_______|\|__|\|__|\|__|\|__|\|__|\|__| \|__|
//
open class Chain<C> {
fileprivate var result: Wrapper<[C]>
fileprivate var funcQueue: [(Wrapper<[C]>) -> Wrapper<[C]>] = []
open var value: [C] {
get {
var result: Wrapper<[C]> = self.result
for function in self.funcQueue {
result = function(result)
}
return result.value
}
}
/// Initializer of the wrapper object for chaining.
///
/// - parameter collection: The array to wrap.
public init(_ collection: [C]) {
self.result = Wrapper(collection)
}
/// Get the first object in the wrapper object.
///
/// - returns: First element from the array.
open func first() -> C? {
return $.first(self.value)
}
/// Get the second object in the wrapper object.
///
/// - returns: Second element from the array.
open func second() -> C? {
return $.second(self.value)
}
/// Get the third object in the wrapper object.
///
/// - returns: Third element from the array.
open func third() -> C? {
return $.third(self.value)
}
/// Flattens nested array.
///
/// - returns: The wrapper object.
open func flatten() -> Chain {
return self.queue {
return Wrapper($.flatten($0.value))
}
}
/// Keeps all the elements except last one.
///
/// - returns: The wrapper object.
open func initial() -> Chain {
return self.initial(1)
}
/// Keeps all the elements except last n elements.
///
/// - parameter numElements: Number of items to remove from the end of the array.
/// - returns: The wrapper object.
open func initial(_ numElements: Int) -> Chain {
return self.queue {
return Wrapper($.initial($0.value, numElements: numElements))
}
}
/// Maps elements to new elements.
///
/// - parameter function: Function to map.
/// - returns: The wrapper object.
open func map(_ function: @escaping (C) -> C) -> Chain {
return self.queue {
var result: [C] = []
for elem: C in $0.value {
result.append(function(elem))
}
return Wrapper(result)
}
}
/// Get the first object in the wrapper object.
///
/// - parameter function: The array to wrap.
/// - returns: The wrapper object.
open func map(_ function: @escaping (Int, C) -> C) -> Chain {
return self.queue {
var result: [C] = []
for (index, elem) in $0.value.enumerated() {
result.append(function(index, elem))
}
return Wrapper(result)
}
}
/// Get the first object in the wrapper object.
///
/// - parameter function: The array to wrap.
/// - returns: The wrapper object.
open func each(_ function: @escaping (C) -> ()) -> Chain {
return self.queue {
for elem in $0.value {
function(elem)
}
return $0
}
}
/// Get the first object in the wrapper object.
///
/// - parameter function: The array to wrap.
/// - returns: The wrapper object.
open func each(_ function: @escaping (Int, C) -> ()) -> Chain {
return self.queue {
for (index, elem) in $0.value.enumerated() {
function(index, elem)
}
return $0
}
}
/// Filter elements based on the function passed.
///
/// - parameter function: Function to tell whether to keep an element or remove.
/// - returns: The wrapper object.
open func filter(_ function: @escaping (C) -> Bool) -> Chain {
return self.queue {
return Wrapper(($0.value).filter(function))
}
}
/// Returns if all elements in array are true based on the passed function.
///
/// - parameter function: Function to tell whether element value is true or false.
/// - returns: Whether all elements are true according to func function.
open func all(_ function: (C) -> Bool) -> Bool {
return $.every(self.value, callback: function)
}
/// Returns if any element in array is true based on the passed function.
///
/// - parameter function: Function to tell whether element value is true or false.
/// - returns: Whether any one element is true according to func function in the array.
open func any(_ function: (C) -> Bool) -> Bool {
let resultArr = self.value
for elem in resultArr {
if function(elem) {
return true
}
}
return false
}
/// Returns size of the array
///
/// - returns: The wrapper object.
open func size() -> Int {
return self.value.count
}
/// Slice the array into smaller size based on start and end value.
///
/// - parameter start: Start index to start slicing from.
/// - parameter end: End index to stop slicing to and not including element at that index.
/// - returns: The wrapper object.
open func slice(_ start: Int, end: Int = 0) -> Chain {
return self.queue {
return Wrapper($.slice($0.value, start: start, end: end))
}
}
fileprivate func queue(_ function: @escaping (Wrapper<[C]>) -> Wrapper<[C]>) -> Chain {
funcQueue.append(function)
return self
}
}
private struct Wrapper<V> {
let value: V
init(_ value: V) {
self.value = value
}
}
| gpl-3.0 | 4dc76dfd6704cadd983e37af0cd42ec0 | 36.533956 | 145 | 0.556804 | 4.28281 | false | false | false | false |
yeziahehe/Gank | Gank/ViewControllers/Category/ArticleViewController.swift | 1 | 12055 | //
// ArticleViewController.swift
// Gank
//
// Created by 叶帆 on 2017/7/26.
// Copyright © 2017年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
class ArticleViewController: BaseViewController {
public var category: String!
fileprivate var gankArray = [Gank]()
fileprivate var page: Int = 1
fileprivate var canLoadMore: Bool = false
fileprivate var isLoading: Bool = false
fileprivate var isNoData: Bool = false
@IBOutlet weak var articleTableView: UITableView! {
didSet {
articleTableView.tableFooterView = UIView()
articleTableView.refreshControl = refreshControl
articleTableView.registerNibOf(DailyGankCell.self)
articleTableView.registerNibOf(ArticleGankLoadingCell.self)
articleTableView.registerNibOf(LoadMoreCell.self)
}
}
fileprivate var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl.init()
refreshControl.layer.zPosition = -1
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
return refreshControl
}()
fileprivate lazy var noDataFooterView: NoDataFooterView = {
let noDataFooterView = NoDataFooterView.instanceFromNib()
noDataFooterView.reasonAction = { [weak self] in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let networkViewController = storyboard.instantiateViewController(withIdentifier: "NetworkViewController")
self?.navigationController?.pushViewController(networkViewController , animated: true)
}
noDataFooterView.reloadAction = { [weak self] in
self?.refreshControl.beginRefreshing()
self?.articleTableView.contentOffset = CGPoint(x:0, y: 0-(self?.refreshControl.frame.size.height)!)
self?.refresh((self?.refreshControl)!)
}
noDataFooterView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: GankConfig.getScreenHeight()-64)
return noDataFooterView
}()
fileprivate lazy var customFooterView: CustomFooterView = {
let footerView = CustomFooterView.instanceFromNib()
footerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 73)
return footerView
}()
deinit {
articleTableView?.delegate = nil
gankLog.debug("deinit ArticleViewController")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refreshControl.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
title = category
updateArticleView()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showDetail":
let vc = segue.destination as! GankDetailViewController
let url = sender as! String
vc.gankURL = url
default:
break
}
}
fileprivate enum UpdateArticleViewMode {
case first
case top
case loadMore
}
fileprivate func updateArticleView(mode: UpdateArticleViewMode = .first, finish: (() -> Void)? = nil) {
if isLoading {
finish?()
return
}
isNoData = false
isLoading = true
var maxPage = page
switch mode {
case .first:
canLoadMore = true
maxPage = 1
articleTableView.isScrollEnabled = false
articleTableView.separatorStyle = .none
articleTableView.rowHeight = 94
//noDataFooterView.removeFromSuperview()
case .top:
maxPage = 1
canLoadMore = true
articleTableView.estimatedRowHeight = 195.5
articleTableView.rowHeight = UITableView.automaticDimension
case .loadMore:
maxPage += 1
}
let failureHandler: FailureHandler = { reason, message in
SafeDispatch.async { [weak self] in
switch mode {
case .first:
//self?.view.addSubview((self?.noDataFooterView)!)
self?.isNoData = true
self?.articleTableView.isScrollEnabled = true
self?.articleTableView.tableFooterView = self?.noDataFooterView
self?.articleTableView.reloadData()
gankLog.debug("加载失败")
case .top, .loadMore:
GankHUD.error("加载失败")
gankLog.debug("加载失败")
}
self?.isLoading = false
finish?()
}
}
gankofCategory(category: category, page: maxPage, failureHandler: failureHandler, completion: { (data) in
SafeDispatch.async { [weak self] in
self?.isNoData = false
self?.articleTableView.isScrollEnabled = true
self?.articleTableView.tableFooterView = UIView()
guard let strongSelf = self else {
return
}
strongSelf.canLoadMore = (data.count == 20)
strongSelf.page = maxPage
let newGankArray = data
let oldGankArray = strongSelf.gankArray
var wayToUpdate: UITableView.WayToUpdate = .none
switch mode {
case .first:
strongSelf.gankArray = newGankArray
wayToUpdate = .reloadData
case .top:
strongSelf.gankArray = newGankArray
if Set(oldGankArray.map({ $0.id })) == Set(newGankArray.map({ $0.id })) {
wayToUpdate = .none
} else {
wayToUpdate = .reloadData
}
case .loadMore:
let oldGankArratCount = oldGankArray.count
let oldGankArrayIdSet = Set<String>(oldGankArray.map({ $0.id }))
var realNewGankArray = [Gank]()
for gank in newGankArray {
if !oldGankArrayIdSet.contains(gank.id) {
realNewGankArray.append(gank)
}
}
strongSelf.gankArray += realNewGankArray
let newGankArrayCount = strongSelf.gankArray.count
let indexPaths = Array(oldGankArratCount..<newGankArrayCount).map({ IndexPath(row: $0, section: 0) })
if !indexPaths.isEmpty {
wayToUpdate = .reloadData
}
if !strongSelf.canLoadMore {
strongSelf.articleTableView.tableFooterView = strongSelf.customFooterView
}
}
wayToUpdate.performWithTableView(strongSelf.articleTableView)
strongSelf.isLoading = false
finish?()
}
})
}
}
extension ArticleViewController {
@objc fileprivate func refresh(_ sender: UIRefreshControl) {
if isNoData {
updateArticleView() {
SafeDispatch.async {
sender.endRefreshing()
}
}
} else {
updateArticleView(mode: .top) {
SafeDispatch.async {
sender.endRefreshing()
}
}
}
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension ArticleViewController: UITableViewDataSource, UITableViewDelegate {
fileprivate enum Section: Int {
case gank
case loadMore
}
func numberOfSections(in tableView: UITableView) -> Int {
guard isNoData else {
return gankArray.isEmpty || !canLoadMore ? 1 : 2
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard !isNoData else {
return 0
}
guard !gankArray.isEmpty else {
return 8
}
guard let section = Section(rawValue: section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
return gankArray.count
case .loadMore:
return canLoadMore ? 1 : 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard gankArray.isEmpty else {
guard let section = Section(rawValue: indexPath.section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
let cell: DailyGankCell = tableView.dequeueReusableCell()
let gankDetail: Gank = gankArray[indexPath.row]
if category == "all" {
cell.configure(withGankDetail: gankDetail, isHiddenTag: false)
} else {
cell.configure(withGankDetail: gankDetail)
}
cell.selectionStyle = UITableViewCell.SelectionStyle.default
return cell
case .loadMore:
let cell: LoadMoreCell = tableView.dequeueReusableCell()
cell.isLoading = true
return cell
}
}
let cell: ArticleGankLoadingCell = tableView.dequeueReusableCell()
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let section = Section(rawValue: indexPath.section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
break
case .loadMore:
guard let cell = cell as? LoadMoreCell else {
break
}
guard canLoadMore else {
cell.isLoading = false
break
}
gankLog.debug("load more gank")
if !cell.isLoading {
cell.isLoading = true
}
updateArticleView(mode: .loadMore, finish: { [weak cell] in
cell?.isLoading = false
})
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer {
tableView.deselectRow(at: indexPath, animated: true)
}
if !gankArray.isEmpty {
let gankDetail: Gank = gankArray[indexPath.row]
self.performSegue(withIdentifier: "showDetail", sender: gankDetail.url)
}
}
}
| gpl-3.0 | 64d27737a297fafab19034b62d0b3eb3 | 31.497297 | 128 | 0.526613 | 5.94953 | false | false | false | false |
gerardmurphyaw/fishackathon | client/GhostGear/GhostGear/AppDelegate.swift | 1 | 3334 | //
// AppDelegate.swift
// GhostGear
//
// Created by Gerard Murphy on 4/23/16.
// Copyright © 2016 Gerard Murphy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | 70f60e698d15648dc63613248b50d32d | 53.639344 | 285 | 0.765077 | 6.149446 | false | false | false | false |
ocrickard/Theodolite | TheodoliteTests/ComponentMemoizationTests.swift | 1 | 2782 | //
// ComponentMemoizationTests.swift
// TheodoliteTests
//
// Created by Oliver Rickard on 11/1/17.
// Copyright © 2017 Oliver Rickard. All rights reserved.
//
import XCTest
@testable import Theodolite
class ComponentMemoizationTests: XCTestCase {
func test_returningFalse_from_shouldComponentUpdate_doesNotUpdate() {
final class TestComponent: Component, TypedComponent {
typealias PropType = String
func shouldComponentUpdate(previous: Component) -> Bool {
return false
}
}
let c1 = TestComponent("hello")
let scope1 = Scope(listener: nil,
component: c1,
previousScope: nil,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
// Force other props here so the default method would cause it to update
let c2 = TestComponent("argh")
let scope2 = Scope(listener: nil,
component: c2,
previousScope: scope1,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
XCTAssert(scope1._component === c1)
XCTAssert(scope2._component === c1)
}
func test_notChangingProps_doesNotUpdate() {
final class TestComponent: Component, TypedComponent {
typealias PropType = String
}
let c1 = TestComponent("hello")
let scope1 = Scope(listener: nil,
component: c1,
previousScope: nil,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
let c2 = TestComponent("hello")
let scope2 = Scope(listener: nil,
component: c2,
previousScope: scope1,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
XCTAssert(scope1._component === c1)
XCTAssert(scope2._component === c1)
}
func test_changingProps_updates() {
final class TestComponent: Component, TypedComponent {
typealias PropType = String
}
let c1 = TestComponent("hello")
let scope1 = Scope(listener: nil,
component: c1,
previousScope: nil,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
let c2 = TestComponent("argh")
let scope2 = Scope(listener: nil,
component: c2,
previousScope: scope1,
parentIdentifier: ScopeIdentifier(path: []),
stateUpdateMap: [:])
XCTAssert(scope1._component === c1)
XCTAssert(scope2._component === c2)
}
}
| mit | 6b9cc3227524dd50c9a85859d35579ba | 28.273684 | 76 | 0.555915 | 4.922124 | false | true | false | false |
n42corp/N42WebView | Example/N42WebView/ViewController.swift | 1 | 1112 | //
// ViewController.swift
// N42WebView
//
// Created by ChangHoon Jung on 12/17/2015.
// Copyright (c) 2015 ChangHoon Jung. All rights reserved.
//
import UIKit
import N42WebView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func touchWebViewButton(_ sender: AnyObject) {
let vc = N42WebViewController(url: "http://blog.iamseapy.com")
vc.navTitle = "N42 타이틀"
// vc.hideToolbar = true
vc.toolbarStyle = UIBarStyle.default
vc.toolbarTintColor = UIColor.orange
vc.actionUrl = URL(string: "http://seapy.com")
vc.progressViewTintColor = UIColor.red
vc.headers = ["HEADER-KEY-YOYOYOY" : "ddddd"]
vc.allowHosts = ["blog.iamseapy.com"]
navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 9977829199b058273480d11a4994aee6 | 28.105263 | 80 | 0.655515 | 4.081181 | false | false | false | false |
xuzhuoxi/SearchKit | Source/ExSwift/Int.swift | 1 | 5735 | //
// Int.swift
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension Int {
/**
Calls function self times.
- parameter function: Function to call
*/
func times <T> (_ function: @escaping (Void) -> T) {
(0..<self).each { _ in _ = function(); return }
}
/**
Calls function self times.
- parameter function: Function to call
*/
func times (_ function: @escaping (Void) -> Void) {
(0..<self).each { _ in _ = function(); return }
}
/**
Calls function self times passing a value from 0 to self on each call.
- parameter function: Function to call
*/
func times <T> (_ function: @escaping (Int) -> T) {
(0..<self).each { index in _ = function(index); return }
}
/**
Checks if a number is even.
- returns: true if self is even
*/
func isEven () -> Bool {
return (self % 2) == 0
}
/**
Checks if a number is odd.
- returns: true if self is odd
*/
func isOdd () -> Bool {
return !isEven()
}
/**
Iterates function, passing in integer values from self up to and including limit.
- parameter limit: Last value to pass
- parameter function: Function to invoke
*/
func upTo (_ limit: Int, function: (Int) -> ()) {
if limit < self {
return
}
(self...limit).each(function)
}
/**
Iterates function, passing in integer values from self down to and including limit.
- parameter limit: Last value to pass
- parameter function: Function to invoke
*/
func downTo (_ limit: Int, function: (Int) -> ()) {
if limit > self {
return
}
Array(Array(limit...self).reversed()).each(function)
}
/**
Clamps self to a specified range.
- parameter range: Clamping range
- returns: Clamped value
*/
func clamp (_ range: Range<Int>) -> Int {
return clamp(range.lowerBound, range.upperBound - 1)
}
/**
Clamps self to a specified range.
- parameter min: Lower bound
- parameter max: Upper bound
- returns: Clamped value
*/
func clamp (_ min: Int, _ max: Int) -> Int {
return Swift.max(min, Swift.min(max, self))
}
/**
Checks if self is included a specified range.
- parameter range: Range
- parameter strict: If true, "<" is used for comparison
- returns: true if in range
*/
func isIn (_ range: Range<Int>, strict: Bool = false) -> Bool {
if strict {
return range.lowerBound < self && self < range.upperBound - 1
}
return range.lowerBound <= self && self <= range.upperBound - 1
}
/**
Checks if self is included in a closed interval.
- parameter interval: Interval to check
- returns: true if in the interval
*/
func isIn (_ interval: ClosedRange<Int>) -> Bool {
return interval.contains(self)
}
/**
Checks if self is included in an half open interval.
- parameter interval: Interval to check
- returns: true if in the interval
*/
func isIn (_ interval: Range<Int>) -> Bool {
return interval.contains(self)
}
/**
Returns an [Int] containing the digits in self.
:return: Array of digits
*/
func digits () -> [Int] {
var result = [Int]()
for char in String(self).characters {
let string = String(char)
if let toInt = Int(string) {
result.append(toInt)
}
}
return result
}
/**
Absolute value.
- returns: abs(self)
*/
func abs () -> Int {
return Swift.abs(self)
}
/**
Greatest common divisor of self and n.
- parameter n:
- returns: GCD
*/
func gcd (_ n: Int) -> Int {
return n == 0 ? self : n.gcd(self % n)
}
/**
Least common multiple of self and n
- parameter n:
- returns: LCM
*/
func lcm (_ n: Int) -> Int {
return (self * n).abs() / gcd(n)
}
/**
Computes the factorial of self
- returns: Factorial
*/
func factorial () -> Int {
return self == 0 ? 1 : self * (self - 1).factorial()
}
/**
Random integer between min and max (inclusive).
- parameter min: Minimum value to return
- parameter max: Maximum value to return
- returns: Random integer
*/
static func random(_ min: Int = 0, max: Int) -> Int {
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
}
/**
NSTimeInterval conversion extensions
*/
public extension Int {
var years: TimeInterval {
return 365 * self.days
}
var year: TimeInterval {
return self.years
}
var days: TimeInterval {
return 24 * self.hours
}
var day: TimeInterval {
return self.days
}
var hours: TimeInterval {
return 60 * self.minutes
}
var hour: TimeInterval {
return self.hours
}
var minutes: TimeInterval {
return 60 * self.seconds
}
var minute: TimeInterval {
return self.minutes
}
var seconds: TimeInterval {
return TimeInterval(self)
}
var second: TimeInterval {
return self.seconds
}
}
| mit | 8dbf503ee5fe1a8bf72de5b85404dfae | 21.402344 | 91 | 0.520139 | 4.442293 | false | false | false | false |
Touchwonders/Transition | Examples/SimpleExample/SimpleExample/AppDelegate.swift | 1 | 2419 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// 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.
/**
* The example implemented here follows the steps explained in the README.
*/
import UIKit
// • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • //
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var myTransitions: MyNavigationTransitions?
var navigationController: UINavigationController? {
return window?.rootViewController as? UINavigationController
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if let navigationController = navigationController {
navigationController.interactivePopGestureRecognizer?.isEnabled = false
myTransitions = MyNavigationTransitions(navigationController: navigationController)
if let font = UIFont(name: "ArialRoundedMTBold", size: 20.0) {
navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white]
}
}
return true
}
}
| mit | 05d6f3b89826c995583b91fc2d3cce56 | 43.169811 | 163 | 0.702264 | 4.816872 | false | false | false | false |
hhyyg/Miso.Gistan | GistanFileExtension/FileProviderExtension.swift | 1 | 7042 | //
// FileProviderExtension.swift
// GistanFileExtension
//
// Created by Hiroka Yago on 2017/10/08.
// Copyright © 2017 miso. All rights reserved.
//
import FileProvider
import Foundation
class FileProviderExtension: NSFileProviderExtension {
private var fileManager = FileManager()
override init() {
super.init()
let token: String? = KeychainService.get(forKey: .oauthToken)
logger.debug(token ?? "token is null")
//TODO: if token is null
if token == nil {
assertionFailure()
}
}
private func getItem(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
let type = FileProviderSerivce.getIdentifierType(identifier: identifier)
switch type {
case .root:
fatalError()
case .gistItem:
let item = FileProviderSerivce.getGistItem(identifier: identifier)
return GistFileProviderItem(item: item)
case .gistFile:
let parentIdentifier = FileProviderSerivce.getParentIdentifier(identifier: identifier)
let parentGistItem = FileProviderSerivce.getGistItem(identifier: parentIdentifier)
let gistFile = FileProviderSerivce.getGileFile(gistFileIdentifier: identifier)!
return GistFileFileProviderItem(parentItemIdentifier: parentIdentifier, gistItem: parentGistItem, gistFile: gistFile)
}
}
override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
//logger.debug("urlForItem: \(identifier.rawValue)")
if (identifier == NSFileProviderItemIdentifier.rootContainer) {
return nil
}
// resolve the given identifier to a file on disk
guard let item = try? getItem(for: identifier) else {
return nil
}
// in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
let manager = NSFileProviderManager.default
let perItemDirectory = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
return perItemDirectory.appendingPathComponent(item.filename, isDirectory:false)
}
override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
// resolve the given URL to a persistent identifier using a database
let pathComponents = url.pathComponents
// exploit the fact that the path structure has been defined as
// <base storage directory>/<item identifier>/<item file name> above
assert(pathComponents.count > 2)
return NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
}
override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
logger.debug(url)
do {
try fileManager.createDirectory(at: url.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil)
fileManager.createFile(atPath: url.path, contents: nil, attributes: nil)
completionHandler(nil)
} catch let e {
completionHandler(e)
}
}
override func startProvidingItem(at url: URL, completionHandler: ((_ error: Error?) -> Void)?) {
logger.debug(url)
guard let identifier = persistentIdentifierForItem(at: url),
let gistFile = FileProviderSerivce.getGileFile(gistFileIdentifier: identifier) else {
completionHandler?(NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:]))
return
}
GistService.getData(url: URL(string: gistFile.rawUrl)!) { data in
do {
try data.write(to: url)
completionHandler?(nil)
} catch let e {
completionHandler?(e)
}
}
}
override func itemChanged(at url: URL) {
// Called at some point after the file has changed; the provider may then trigger an upload
/* TODO:
- mark file at <url> as needing an update in the model
- if there are existing NSURLSessionTasks uploading this file, cancel them
- create a fresh background NSURLSessionTask and schedule it to upload the current modifications
- register the NSURLSessionTask with NSFileProviderManager to provide progress updates
*/
}
override func stopProvidingItem(at url: URL) {
// Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
// Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
// Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
// TODO: look up whether the file has local changes
let fileHasLocalChanges = false
if !fileHasLocalChanges {
// remove the existing file to free up space
do {
_ = try FileManager.default.removeItem(at: url)
} catch {
// Handle error
}
// write out a placeholder to facilitate future property lookups
self.providePlaceholder(at: url, completionHandler: { _ in
// TODO: handle any error, do any necessary cleanup
})
}
}
// MARK: - Actions
/* TODO: implement the actions for items here
each of the actions follows the same pattern:
- make a note of the change in the local model
- schedule a server request as a background task to inform the server of the change
- call the completion block with the modified item in its post-modification state
*/
// MARK: - Enumeration
override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
let maybeEnumerator: NSFileProviderEnumerator? = nil
if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
return FileProviderEnumerator()
} else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
logger.debug("workingSet")
} else {
logger.debug("item for directory")
// TODO: determine if the item is a directory or a file
// - for a directory, instantiate an enumerator of its subitems
// - for a file, instantiate an enumerator that observes changes to the file
return FileProviderSerivce.getChildlenEnumerator(identifier: containerItemIdentifier)
}
guard let enumerator = maybeEnumerator else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
}
return enumerator
}
}
| mit | 5bb55bf8df51a680c440240bf42de79e | 39.936047 | 145 | 0.656725 | 5.282071 | false | false | false | false |
hhyyg/Miso.Gistan | Gistan/Controller/PreferencesTableViewController.swift | 1 | 1396 | //
// PreferencesTableViewController.swift
// Gistan
//
// Created by Hiroka Yago on 2017/10/17.
// Copyright © 2017 miso. All rights reserved.
//
import UIKit
import SafariServices
class PreferencesTableViewController: UITableViewController {
enum Row: Int {
case
logout
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.prefersLargeTitles = true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch Row(rawValue: indexPath.row)! {
case .logout:
logout()
}
}
func logout() {
KeychainService.set(forKey: .oauthToken, value: "")
KeychainService.set(forKey: .userName, value: "")
goAccountViewController(modalTransitionStyle: .coverVertical)
}
func goAccountViewController(modalTransitionStyle: UIModalTransitionStyle) {
let accountVC = self.storyboard!.instantiateViewController(withIdentifier: "AccountPage") as! AccountViewController
accountVC.delegate = (tabBarController!.viewControllers![0] as! UINavigationController).topViewController as! AccountViewControllerDelegate
accountVC.modalTransitionStyle = modalTransitionStyle
present(accountVC, animated: true) {
self.tabBarController!.selectedIndex = 0
}
}
}
| mit | df7cd0315b705472231693496b2b801e | 27.469388 | 147 | 0.691756 | 5.365385 | false | false | false | false |
myriadmobile/Droar | Droar/Classes/Default Sources/DeviceInfoKnob.swift | 1 | 3884 | //
// DeviceInfoKnob.swift
// Droar
//
// Created by Nathan Jangula on 10/11/17.
//
import Foundation
import SDVersion
internal class DeviceInfoKnob : DroarKnob {
private enum DeviceInfoRow: Int {
case name = 0
case systemName = 1
case systemVersion = 2
case model = 3
case resolution = 4
case ipAddress = 5
case identifier = 6
case count = 7
}
func droarKnobTitle() -> String {
return "Device Info"
}
func droarKnobPosition() -> PositionInfo {
return PositionInfo(position: .bottom, priority: .low)
}
func droarKnobNumberOfCells() -> Int {
return DeviceInfoRow.count.rawValue
}
func droarKnobCellForIndex(index: Int, tableView: UITableView) -> DroarCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DroarLabelCell") as? DroarLabelCell ?? DroarLabelCell.create()
cell.selectionStyle = .none
let device = UIDevice.current
switch DeviceInfoRow(rawValue:index)! {
case .name:
cell.titleLabel.text = "Name"
cell.detailLabel.text = device.name
case .systemName:
cell.titleLabel.text = "System Name"
cell.detailLabel.text = device.systemName
case .systemVersion:
cell.titleLabel.text = "iOS Version"
cell.detailLabel.text = device.systemVersion
case .model:
cell.titleLabel.text = "Model"
cell.detailLabel.text = SDiOSVersion.deviceName(for: SDiOSVersion.deviceVersion())
case .resolution:
cell.titleLabel.text = "Screen Resolution"
cell.detailLabel.text = getScreenResolution()
case .ipAddress:
cell.titleLabel.text = "IP Address"
cell.detailLabel.text = getIPAddress()
case .identifier:
cell.titleLabel.text = "Identifier"
cell.detailLabel.text = device.identifierForVendor?.uuidString
case .count:
cell.titleLabel.text = ""
cell.detailLabel.text = ""
}
return cell
}
func getScreenResolution() -> String {
var size = UIScreen.main.bounds.size
let scale = UIScreen.main.scale
size.width = size.width * scale
size.height = size.height * scale
return String(format:"%.0f x %.0f", size.width, size.height)
}
func getIPAddress() -> String {
var address = "error"
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return address }
guard let firstAddr = ifaddr else { return address }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
}
| mit | 3c5e2ca4c0be02f2411735cb9bd29b13 | 33.371681 | 128 | 0.565396 | 4.668269 | false | false | false | false |
zapdroid/RXWeather | Pods/Quick/Sources/Quick/ExampleGroup.swift | 1 | 3029 | import Foundation
/**
Example groups are logical groupings of examples, defined with
the `describe` and `context` functions. Example groups can share
setup and teardown code.
*/
public final class ExampleGroup: NSObject {
internal weak var parent: ExampleGroup?
internal let hooks = ExampleHooks()
internal var phase: HooksPhase = .nothingExecuted
private let internalDescription: String
private let flags: FilterFlags
private let isInternalRootExampleGroup: Bool
private var childGroups = [ExampleGroup]()
private var childExamples = [Example]()
internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) {
internalDescription = description
self.flags = flags
self.isInternalRootExampleGroup = isInternalRootExampleGroup
}
public override var description: String {
return internalDescription
}
/**
Returns a list of examples that belong to this example group,
or to any of its descendant example groups.
*/
public var examples: [Example] {
var examples = childExamples
for group in childGroups {
examples.append(contentsOf: group.examples)
}
return examples
}
internal var name: String? {
if let parent = parent {
guard let name = parent.name else { return description }
return "\(name), \(description)"
} else {
return isInternalRootExampleGroup ? nil : description
}
}
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
walkUp { group in
for (key, value) in group.flags {
aggregateFlags[key] = value
}
}
return aggregateFlags
}
internal var befores: [BeforeExampleWithMetadataClosure] {
var closures = Array(hooks.befores.reversed())
walkUp { group in
closures.append(contentsOf: Array(group.hooks.befores.reversed()))
}
return Array(closures.reversed())
}
internal var afters: [AfterExampleWithMetadataClosure] {
var closures = hooks.afters
walkUp { group in
closures.append(contentsOf: group.hooks.afters)
}
return closures
}
internal func walkDownExamples(_ callback: (_ example: Example) -> Void) {
for example in childExamples {
callback(example)
}
for group in childGroups {
group.walkDownExamples(callback)
}
}
internal func appendExampleGroup(_ group: ExampleGroup) {
group.parent = self
childGroups.append(group)
}
internal func appendExample(_ example: Example) {
example.group = self
childExamples.append(example)
}
private func walkUp(_ callback: (_ group: ExampleGroup) -> Void) {
var group = self
while let parent = group.parent {
callback(parent)
group = parent
}
}
}
| mit | 42e613581f230ae3c9d958405379dc4a | 28.407767 | 102 | 0.62892 | 5.107926 | false | false | false | false |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift | 6 | 2501 | //
// SingleAssignmentDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Darwin.C.stdatomic
/**
Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception.
*/
public class SingleAssignmentDisposable : DisposeBase, Disposable, Cancelable {
fileprivate enum DisposeState: UInt32 {
case disposed = 1
case disposableSet = 2
}
// Jeej, swift API consistency rules
fileprivate enum DisposeStateInt32: Int32 {
case disposed = 1
case disposableSet = 2
}
// state
private var _state: UInt32 = 0
private var _disposable = nil as Disposable?
/**
- returns: A value that indicates whether the object is disposed.
*/
public var isDisposed: Bool {
return (_state & DisposeState.disposed.rawValue) != 0
}
/**
Initializes a new instance of the `SingleAssignmentDisposable`.
*/
public override init() {
super.init()
}
/**
Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined.
**Throws exception if the `SingleAssignmentDisposable` has already been assigned to.**
*/
public func setDisposable(_ disposable: Disposable) {
_disposable = disposable
let previousState = OSAtomicOr32OrigBarrier(DisposeState.disposableSet.rawValue, &_state)
if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 {
rxFatalError("oldState.disposable != nil")
}
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
disposable.dispose()
_disposable = nil
}
}
/**
Disposes the underlying disposable.
*/
public func dispose() {
let previousState = OSAtomicOr32OrigBarrier(DisposeState.disposed.rawValue, &_state)
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
return
}
if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 {
guard let disposable = _disposable else {
rxFatalError("Disposable not set")
}
disposable.dispose()
_disposable = nil
}
}
}
| mit | 3b3f7a609f4eb4989b0f6321332f8381 | 28.069767 | 141 | 0.6504 | 5 | false | false | false | false |
aojet/Aojet | Sources/Aojet/function/Function.swift | 1 | 696 | //
// Function.swift
// Aojet
//
// Created by Qihe Bian on 16/10/5.
// Copyright © 2016 Qihe Bian. All rights reserved.
//
protocol Function: Identifiable {
associatedtype A
associatedtype R
func apply(_ a: A) -> R
}
class AnyFunction<A, R>: Function, IdentifierHashable {
private let _base: Any?
let objectId: Identifier
private let _apply: (_ a: A) -> R
init<T: Function>(base: T) where T.A == A, T.R == R {
_base = base
objectId = base.objectId
_apply = base.apply
}
init(_ apply: @escaping (_ a: A) -> R) {
_base = nil
objectId = type(of: self).generateObjectId()
_apply = apply
}
func apply(_ a: A) -> R {
return _apply(a)
}
}
| mit | 91f4c5cc200d1b975ae6f3c6ed7798c9 | 18.305556 | 55 | 0.598561 | 3.144796 | false | false | false | false |
Bersaelor/KDTree | Example/KDTree/Star+KDTreePoint.swift | 1 | 699 | //
// Star.swift
// KDTree
//
// Created by Konrad Feiler on 21/03/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import KDTree
import SwiftyHYGDB
extension RadialStar: KDTreePoint {
public static var dimensions = 2
public func kdDimension(_ dimension: Int) -> Double {
return dimension == 0 ? Double(self.normalizedAscension) : Double(self.normalizedDeclination)
}
public func squaredDistance(to otherPoint: RadialStar) -> Double {
let x = self.normalizedAscension - otherPoint.normalizedAscension
let y = self.normalizedDeclination - otherPoint.normalizedDeclination
return Double(x*x + y*y)
}
}
| mit | 588e4ec9c441b94f6dd1e057481b3b69 | 26.92 | 101 | 0.696275 | 4.05814 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/data types/enumerable/XGPokemonStats.swift | 1 | 17140 | //
// Pokemon.swift
// Mausoleum Stats Tool
//
// Created by StarsMmd on 26/12/2014.
// Copyright (c) 2014 StarsMmd. All rights reserved.
//
import Foundation
var kNumberOfPokemon: Int { CommonIndexes.NumberOfPokemon.value } //0x19F
var kFirstPokemonOffset: Int { CommonIndexes.PokemonStats.startOffset }// 0x29DA8 xd us
let kSizeOfPokemonStats = 0x124
let kEXPRateOffset = 0x00
let kCatchRateOffset = 0x01
let kGenderRatioOffset = 0x02
let kBaseEXPOffset = 0x05
let kBaseHappinessOffset = 0x07
let kHeightOffset = 0x08
let kWeightOffset = 0x0A
let kNationalIndexOffset = 0x0E
let kType1Offset = 0x30
let kType2Offset = 0x31
let kAbility1Offset = 0x32
let kAbility2Offset = 0x33
let kFirstTMOffset = 0x34
let kFirstTutorMoveOffset = 0x6E
let kFirstEVYieldOffset = 0x9A
let kFirstEvolutionOffset = 0xA6
let kFirstLevelUpMoveOffset = 0xC4
let kFirstEggMoveOffset = 0x7E
// This table is pointed to by function 0x801d8e20 in RAM if you want to repoint to a larger
// table at some point
var kFirstPokemonPKXIdentifierOffset: Int {
switch region {
case .US: return 0x40a0a8
case .EU: return 0x444988
case .JP: return 0x3e7758
case .OtherGame: return -1
}
} // in start.dol
let kModelDictionaryModelOffset = 0x4
/* Tutor moves order:
*
* Use the appropriate dol patcher function to set them to the correct order
*
* 1: body slam tm8
* 2: double edge tm11
* 3: seismic toss tm3
* 4: mimic tm1
* 5: dream eater tm6
* 6: thunderwave tm2
* 7: substitute tm5
* 8: icy wind tm4
* 9: swagger tm7
* 10: sky attack tm10
* 11: self destruct tm12
* 12: nightmare tm9
*/
let kHeldItem1Offset = 0x7A
let kHeldItem2Offset = 0x7C
let kHPOffset = 0x8F
let kAttackOffset = 0x91
let kDefenseOffset = 0x93
let kSpecialAttackOffset = 0x95
let kSpecialDefenseOffset = 0x97
let kSpeedOffset = 0x99
let kNameIDOffset = 0x18
let kPokemonCryIndexOffset = 0x0C
let kSpeciesNameIDOffset = 0x1C
let kPokemonModelIndexOffset = 0x2E // Same as pokemon's index
let kPokemonBodyOffset = 0x118
let kPokemonBodyShinyOffset = 0x120
let kPokemonFaceIndexOffset = 0x116
final class XGPokemonStats: NSObject, Codable {
var index = 0x0
var startOffset = 0x0
var nameID = 0x0
var speciesNameID = 0x0
var cryIndex = 0x0
var modelIndex = 0x0
var faceIndex = 0x0
var bodyID: UInt32 = 0x0
var bodyShinyID: UInt32 = 0x0
var bodyFileName: String? {
let dance = XGFiles.fsys("poke_dance").fsysData
if let index = dance.indexForIdentifier(identifier: bodyID.int) {
return dance.fileNameForFileWithIndex(index: index)
}
return nil
}
var bodyShinyFileName: String? {
let dance = XGFiles.fsys("poke_dance").fsysData
if let index = dance.indexForIdentifier(identifier: bodyShinyID.int) {
return dance.fileNameForFileWithIndex(index: index)
}
return nil
}
var levelUpRate = XGExpRate.standard
var genderRatio = XGGenderRatios.maleOnly
var catchRate = 0x0
var baseExp = 0x0
var baseHappiness = 0x0
var type1 = XGMoveTypes.normal
var type2 = XGMoveTypes.normal
var ability1 = XGAbilities.index(0)
var ability2 = XGAbilities.index(0)
var heldItem1 = XGItems.index(0)
var heldItem2 = XGItems.index(0)
var hp = 0x0
var speed = 0x0
var attack = 0x0
var defense = 0x0
var specialAttack = 0x0
var specialDefense = 0x0
var levelUpMoves = [XGLevelUpMove]()
var learnableTMs = [Bool]()
var tutorMoves = [Bool]()
var evolutions = [XGEvolution]()
var nationalIndex = 0
var hpYield = 0x0
var speedYield = 0x0
var attackYield = 0x0
var defenseYield = 0x0
var specialAttackYield = 0x0
var specialDefenseYield = 0x0
var height = 0.0 // meters
var weight = 0.0 // kg
var baseStatTotal: Int {
return hp + attack + defense + specialAttack + specialDefense + speed
}
var faceTextureIdentifier: UInt32 {
let id: Int? = pokeFacesTable.dataForEntry(faceIndex)?.get("Image File ID")
return id?.unsigned ?? 0
}
var pkxModelIdentifier: UInt32 {
let id: Int? = pkxPokemonModelsTable.dataForEntry(modelIndex)?.get("File Identifier")
return id?.unsigned ?? 0
}
var pkxFSYSID: Int {
return pkxPokemonModelsTable.dataForEntry(modelIndex)?.get("Fsys ID") ?? 0
}
var pkxData: XGMutableData? {
let fileid = pkxModelIdentifier
let fsysid = pkxFSYSID
guard fileid > 0,
fsysid > 0,
let fsysName = GSFsys.shared.entryWithID(pkxFSYSID)?.name,
let fsysData = XGISO.current.dataForFile(filename: fsysName)
else { return nil }
let fsys = XGFsys(data: fsysData)
guard let index = fsys.indexForIdentifier(identifier: fileid.int) else { return nil }
return fsys.extractDataForFileWithIndex(index: index)
}
var pkxModel: PKXModel? {
guard let data = pkxData else { return nil }
return PKXModel(data: data)
}
var name: XGString {
return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID)
}
var species: XGString {
let file = XGFiles.typeAndFsysName(.msg, "pda_menu")
return XGStringTable(file: file, startOffset: 0, fileSize: file.fileSize).stringSafelyWithID(self.speciesNameID)
}
var numberOfTMs: Int {
return learnableTMs.filter{ $0 }.count
}
var numberOfTutorMoves: Int {
return tutorMoves.filter{ $0 }.count
}
var numberOfLevelUpMoves: Int {
return levelUpMoves.filter{ $0.isSet() }.count
}
var numberOfEvolutions: Int {
return evolutions.filter{ $0.isSet() }.count
}
init(index: Int) {
super.init()
let rel = XGFiles.common_rel.data!
startOffset = CommonIndexes.PokemonStats.startOffset + ( kSizeOfPokemonStats * index )
self.index = index
nameID = rel.getWordAtOffset(startOffset + kNameIDOffset).int
speciesNameID = rel.getWordAtOffset(startOffset + kSpeciesNameIDOffset).int
cryIndex = rel.get2BytesAtOffset(startOffset + kPokemonCryIndexOffset)
modelIndex = rel.get2BytesAtOffset(startOffset + kPokemonModelIndexOffset)
faceIndex = game == .XD ? rel.get2BytesAtOffset(startOffset + kPokemonFaceIndexOffset) : rel.getWordAtOffset(CommonIndexes.PokefaceTextures.startOffset + (index * 8) + 4).int
bodyID = rel.getWordAtOffset(startOffset + kPokemonBodyOffset)
bodyShinyID = rel.getWordAtOffset(startOffset + kPokemonBodyShinyOffset)
height = Double(rel.get2BytesAtOffset(startOffset + kHeightOffset)) / 10
weight = Double(rel.get2BytesAtOffset(startOffset + kWeightOffset)) / 10
levelUpRate = XGExpRate(rawValue: rel.getByteAtOffset(startOffset + kEXPRateOffset)) ?? .standard
genderRatio = XGGenderRatios(rawValue: rel.getByteAtOffset(startOffset + kGenderRatioOffset)) ?? .maleOnly
catchRate = rel.getByteAtOffset(startOffset + kCatchRateOffset)
baseExp = rel.getByteAtOffset(startOffset + kBaseEXPOffset)
baseHappiness = rel.getByteAtOffset(startOffset + kBaseHappinessOffset)
type1 = XGMoveTypes.index(rel.getByteAtOffset(startOffset + kType1Offset))
type2 = XGMoveTypes.index(rel.getByteAtOffset(startOffset + kType2Offset))
let a1 = rel.getByteAtOffset(startOffset + kAbility1Offset)
let a2 = rel.getByteAtOffset(startOffset + kAbility2Offset)
ability1 = .index(a1)
ability2 = .index(a2)
let i1 = rel.get2BytesAtOffset(startOffset + kHeldItem1Offset)
let i2 = rel.get2BytesAtOffset(startOffset + kHeldItem2Offset)
heldItem1 = .index(i1)
heldItem2 = .index(i2)
hp = rel.getByteAtOffset(startOffset + kHPOffset)
attack = rel.getByteAtOffset(startOffset + kAttackOffset)
defense = rel.getByteAtOffset(startOffset + kDefenseOffset)
specialAttack = rel.getByteAtOffset(startOffset + kSpecialAttackOffset)
specialDefense = rel.getByteAtOffset(startOffset + kSpecialDefenseOffset)
speed = rel.getByteAtOffset(startOffset + kSpeedOffset)
hpYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x0)
attackYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x2)
defenseYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x4)
specialAttackYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x6)
specialDefenseYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x8)
speedYield = rel.get2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0xa)
self.nationalIndex = rel.get2BytesAtOffset(startOffset + kNationalIndexOffset)
for i in 0 ..< kNumberOfTMsAndHMs {
self.learnableTMs.append(rel.getByteAtOffset(startOffset + kFirstTMOffset + i) == 1)
}
for i in 0 ..< kNumberOfTutorMoves {
self.tutorMoves.append(rel.getByteAtOffset(startOffset + kFirstTutorMoveOffset + i) == 1)
}
for i in 0 ..< kNumberOfLevelUpMoves {
let currentOffset = startOffset + kFirstLevelUpMoveOffset + (i * kSizeOfLevelUpData)
let level = rel.getByteAtOffset(currentOffset + kLevelUpMoveLevelOffset)
let move = rel.get2BytesAtOffset(currentOffset + kLevelUpMoveIndexOffset)
self.levelUpMoves.append(XGLevelUpMove(level: level, move: move))
}
for i in 0 ..< kNumberOfEvolutions {
let currentOffset = startOffset + kFirstEvolutionOffset + (i * kSizeOfEvolutionData)
let method = rel.getByteAtOffset(currentOffset + kEvolutionMethodOffset)
let condition = rel.get2BytesAtOffset(currentOffset + kEvolutionConditionOffset)
let evolution = rel.get2BytesAtOffset(currentOffset + kEvolvedFormOffset)
evolutions.append(XGEvolution(evolutionMethod: method, condition: condition, evolvedForm: evolution))
}
}
func save() {
let rel = XGFiles.common_rel.data!
rel.replaceWordAtOffset(startOffset + kNameIDOffset, withBytes: UInt32(nameID))
rel.replaceWordAtOffset(startOffset + kSpeciesNameIDOffset, withBytes: UInt32(speciesNameID))
rel.replace2BytesAtOffset(startOffset + kPokemonCryIndexOffset, withBytes: cryIndex)
rel.replace2BytesAtOffset(startOffset + kPokemonModelIndexOffset, withBytes: modelIndex)
rel.replace2BytesAtOffset(startOffset + kPokemonFaceIndexOffset, withBytes: faceIndex)
rel.replaceWordAtOffset(startOffset + kPokemonBodyOffset, withBytes: bodyID)
rel.replaceWordAtOffset(startOffset + kPokemonBodyShinyOffset, withBytes: bodyShinyID)
rel.replace2BytesAtOffset(startOffset + kHeightOffset, withBytes: Int(height * 10))
rel.replace2BytesAtOffset(startOffset + kWeightOffset, withBytes: Int(weight * 10))
rel.replaceByteAtOffset(startOffset + kEXPRateOffset, withByte: levelUpRate.rawValue)
rel.replaceByteAtOffset(startOffset + kGenderRatioOffset, withByte: genderRatio.rawValue)
rel.replaceByteAtOffset(startOffset + kCatchRateOffset, withByte: catchRate)
rel.replaceByteAtOffset(startOffset + kBaseEXPOffset, withByte: baseExp)
rel.replaceByteAtOffset(startOffset + kBaseHappinessOffset, withByte: baseHappiness)
rel.replaceByteAtOffset(startOffset + kType1Offset, withByte: type1.rawValue)
rel.replaceByteAtOffset(startOffset + kType2Offset, withByte: type2.rawValue)
rel.replaceByteAtOffset(startOffset + kAbility1Offset, withByte: ability1.index)
rel.replaceByteAtOffset(startOffset + kAbility2Offset, withByte: ability2.index)
rel.replace2BytesAtOffset(startOffset + kHeldItem1Offset, withBytes: heldItem1.index)
rel.replace2BytesAtOffset(startOffset + kHeldItem2Offset, withBytes: heldItem2.index)
rel.replaceByteAtOffset(startOffset + kHPOffset, withByte: hp)
rel.replaceByteAtOffset(startOffset + kAttackOffset, withByte: attack)
rel.replaceByteAtOffset(startOffset + kDefenseOffset, withByte: defense)
rel.replaceByteAtOffset(startOffset + kSpecialAttackOffset, withByte: specialAttack)
rel.replaceByteAtOffset(startOffset + kSpecialDefenseOffset, withByte: specialDefense)
rel.replaceByteAtOffset(startOffset + kSpeedOffset, withByte: speed)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x0, withBytes: hpYield)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x2, withBytes: attackYield)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x4, withBytes: defenseYield)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x6, withBytes: specialAttackYield)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0x8, withBytes: specialDefenseYield)
rel.replace2BytesAtOffset(startOffset + kFirstEVYieldOffset + 0xa, withBytes: speedYield)
var currentOffset = startOffset + kFirstTMOffset
for i in 0 ..< kNumberOfTMsAndHMs {
rel.replaceByteAtOffset(currentOffset + i, withByte: learnableTMs[i] ? 1 : 0)
}
currentOffset = startOffset + kFirstTutorMoveOffset
for i in 0 ..< kNumberOfTutorMoves {
rel.replaceByteAtOffset(currentOffset + i, withByte: tutorMoves[i] ? 1 : 0)
}
for i in 0 ..< kNumberOfLevelUpMoves {
let currentOffset = startOffset + kFirstLevelUpMoveOffset + (i * kSizeOfLevelUpData)
let (lev, mov) = levelUpMoves[i].toInts()
rel.replaceByteAtOffset(currentOffset + kLevelUpMoveLevelOffset, withByte: lev)
rel.replace2BytesAtOffset(currentOffset + kLevelUpMoveIndexOffset, withBytes: mov)
}
for i in 0 ..< kNumberOfEvolutions {
let currentOffset = startOffset + kFirstEvolutionOffset + (i * kSizeOfEvolutionData)
let (method, condition, evolution) = evolutions[i].toInts()
rel.replaceByteAtOffset(currentOffset + kEvolutionMethodOffset, withByte: method)
rel.replace2BytesAtOffset(currentOffset + kEvolutionConditionOffset, withBytes: condition)
rel.replace2BytesAtOffset(currentOffset + kEvolvedFormOffset, withBytes: evolution)
}
rel.save()
}
}
extension XGPokemonStats: XGEnumerable {
var enumerableName: String {
return name.string
}
var enumerableValue: String? {
return String(format: "%03d", index)
}
static var className: String {
return "Pokemon"
}
static var allValues: [XGPokemonStats] {
var values = [XGPokemonStats]()
for i in 0 ..< CommonIndexes.NumberOfPokemon.value {
values.append(XGPokemonStats(index: i))
}
return values
}
}
extension XGPokemonStats: XGDocumentable {
var isDocumentable: Bool {
return catchRate != 0
}
var documentableName: String {
return enumerableName + " - " + (enumerableValue ?? "")
}
static var DocumentableKeys: [String] {
return ["index", "hex index", "national index", "name", "type 1", "type 2", "ability 1", "ability 2", "base HP", "base attack", "base defense", "base special attack", "base special defense", "base speed", "species", "level up rate", "gender ratio", "catch rate", "exp yield", "base happiness", "wild item 1", "wild item 2", "HP yield", "attack yield", "defense yield", "special attack yield", "special defense yield", "speed yield", "height", "weight", "evolutions", "learnable tutor moves", "learnable TMs", "level up moves"]
}
func documentableValue(for key: String) -> String {
switch key {
case "index":
return index.string
case "hex index":
return index.hexString()
case "name":
return name.string
case "national index":
return nationalIndex.string
case "type 1":
return type1.name
case "type 2":
return type2.name
case "ability 1":
return ability1.name.string
case "ability 2":
return ability2.name.string
case "base attack":
return attack.string
case "base HP":
return hp.string
case "base defense":
return defense.string
case "base special attack":
return specialAttack.string
case "base special defense":
return specialDefense.string
case "base speed":
return speed.string
case "species":
return species.string
case "level up rate":
return levelUpRate.string
case "gender ratio":
return genderRatio.string
case "catch rate":
return catchRate.string
case "exp yield":
return baseExp.string
case "base happiness":
return baseHappiness.string
case "wild item 1":
return heldItem1.name.string
case "wild item 2":
return heldItem2.name.string
case "attack yield":
return attackYield.string
case "defense yield":
return defenseYield.string
case "HP yield":
return hpYield.string
case "special attack yield":
return specialAttackYield.string
case "special defense yield":
return specialDefenseYield.string
case "speed yield":
return speedYield.string
case "height":
return String(format: "%2.1f m", height)
case "weight":
return String(format: "%2.1f kg", weight)
case "evolutions":
var evolutionString = ""
for evolution in evolutions where evolution.evolutionMethod != .none {
evolutionString += "\n" + evolution.documentableFields
}
return evolutionString
case "learnable tutor moves":
var tutorString = ""
for i in 0 ..< tutorMoves.count {
tutorString += "\n" + XGTMs.tutor(i).move.name.string + ": " + tutorMoves[i].string
}
return tutorString
case "learnable TMs":
var tmString = ""
for i in 0 ..< kNumberOfTMsAndHMs {
tmString += "\n" + XGTMs.tm(i + 1).move.name.string + ": " + learnableTMs[i].string
}
return tmString
case "level up moves":
var movesString = ""
for lum in levelUpMoves where lum.move.index != 0 {
movesString += "\n" + lum.documentableFields
}
return movesString
default:
return ""
}
}
}
| gpl-2.0 | 36b2cdd6b9e075067f8efe438f514782 | 31.523719 | 528 | 0.739498 | 3.229697 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/HapticFeedback.swift | 1 | 5466 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
public final class HapticFeedback {
private let createGenerator: () -> UIFeedbackGenerator
private var generator: UIFeedbackGenerator?
private var triggerBlock: () -> Void
private init<T>(
_ generator: @autoclosure @escaping () -> T,
trigger: @escaping (T) -> Void
) where T: UIFeedbackGenerator {
self.createGenerator = generator
// Workaround for compiler error (Variable 'self.triggerBlock' used before being
// initialized).
self.triggerBlock = {}
self.customTriggerBlock(trigger)
}
private func createGeneratorIfNeeded() {
guard generator == nil else { return }
generator = createGenerator()
}
/// Prepares the generator to trigger feedback.
///
/// When you call this method, the generator is placed into a prepared state for
/// a short period of time. While the generator is prepared, you can trigger
/// feedback with lower latency.
///
/// Think about when you can best prepare your generators. Call `prepare()`
/// before the event that triggers feedback. The system needs time to prepare
/// the Taptic Engine for minimal latency. Calling `prepare()` and then
/// immediately triggering feedback (without any time in between) does not
/// improve latency.
///
/// To conserve power, the Taptic Engine returns to an idle state after any of
/// the following events:
///
/// - You trigger feedback on the generator.
/// - A short period of time passes (typically seconds).
/// - The generator is deallocated.
///
/// After feedback is triggered, the Taptic Engine returns to its idle state. If
/// you might trigger additional feedback within the next few seconds,
/// immediately call `prepare()` to keep the Taptic Engine in the prepared
/// state.
///
/// You can also extend the prepared state by repeatedly calling the `prepare()`
/// method. However, if you continue calling `prepare()` without ever triggering
/// feedback, the system may eventually place the Taptic Engine back in an idle
/// state and ignore any further `prepare()` calls until after you trigger
/// feedback at least once.
///
/// If you no longer need a prepared generator, remove all references to the
/// generator object and let the system deallocate it. This lets the Taptic
/// Engine return to its idle state.
///
/// - Note: The `prepare()` method is optional; however, it is highly
/// recommended. Calling this method helps ensure that your feedback has the
/// lowest possible latency.
public func prepare() {
createGeneratorIfNeeded()
generator?.prepare()
}
/// Triggers haptic feedback for the generator type.
public func trigger() {
createGeneratorIfNeeded()
triggerBlock()
}
/// This deallocate the generator so that the Taptic Engine can return to its
/// idle state.
public func sleep() {
generator = nil
}
private func customTriggerBlock<T>(_ trigger: @escaping (T) -> Void) {
triggerBlock = { [weak self] in
guard let generator = self?.generator as? T else { return }
trigger(generator)
}
}
}
extension HapticFeedback {
public static func impact(style: UIImpactFeedbackGenerator.FeedbackStyle) -> HapticFeedback {
switch style {
case .light:
return lightImpactFeedbackGenerator
case .medium:
return mediumImpactFeedbackGenerator
case .heavy:
return heavyImpactFeedbackGenerator
case .soft:
return .softImpactFeedbackGenerator
case .rigid:
return .rigidImpactFeedbackGenerator
@unknown default:
fatalError(because: .unknownCaseDetected(style))
}
}
public static func notification(type: UINotificationFeedbackGenerator.FeedbackType) -> HapticFeedback {
notificationFeedbackGenerator.customTriggerBlock { (generator: UINotificationFeedbackGenerator) in
generator.notificationOccurred(type)
}
return notificationFeedbackGenerator
}
public static let selection = HapticFeedback(UISelectionFeedbackGenerator()) { $0.selectionChanged() }
}
// MARK: - UIImpactFeedbackGenerator
extension HapticFeedback {
private static let lightImpactFeedbackGenerator = HapticFeedback(UIImpactFeedbackGenerator(style: .light)) {
$0.impactOccurred()
}
private static let mediumImpactFeedbackGenerator = HapticFeedback(UIImpactFeedbackGenerator(style: .medium)) {
$0.impactOccurred()
}
private static let heavyImpactFeedbackGenerator = HapticFeedback(UIImpactFeedbackGenerator(style: .heavy)) {
$0.impactOccurred()
}
private static let softImpactFeedbackGenerator = HapticFeedback(UIImpactFeedbackGenerator(style: .soft)) {
$0.impactOccurred()
}
private static let rigidImpactFeedbackGenerator = HapticFeedback(UIImpactFeedbackGenerator(style: .rigid)) {
$0.impactOccurred()
}
}
// MARK: - UINotificationFeedbackGenerator
extension HapticFeedback {
private static let notificationFeedbackGenerator = HapticFeedback(UINotificationFeedbackGenerator()) { _ in }
}
| mit | 996b849a23a2852c2bc493b4ab69938d | 35.677852 | 114 | 0.670997 | 5.239693 | false | false | false | false |
muhamed-hafez/twitter-feed | Twitter Feed/Twitter Feed/Model/TFUser.swift | 1 | 638 | //
// TFUser.swift
// Twitter Feed
//
// Created by Muhamed Hafez on 12/16/16.
// Copyright © 2016 Muhamed Hafez. All rights reserved.
//
import Foundation
class TFUser: TFBaseModel {
var ID: String!
var screenName: String!
var name: String!
var imageURL = ""
required init(withDictionary dictionary: NSDictionary) {
super.init(withDictionary: dictionary)
ID = dictionary["id_str"] as! String
screenName = dictionary["screen_name"] as? String ?? ""
name = dictionary["name"] as? String ?? ""
imageURL = dictionary["profile_image_url_https"] as? String ?? ""
}
}
| mit | d43f09b001ca161c4712190c0256f8c6 | 25.541667 | 73 | 0.629513 | 3.791667 | false | false | false | false |
devcarlos/EncryptApp | EncryptApp/EncryptApp/Classes/Managers/NetworkManager/EncryptorManager.swift | 1 | 8071 | //
// EncryptorManager.swift
// EncryptApp
//
// Created by Carlos Alcala on 3/1/16.
// Copyright (c) 2016 Carlos Alcala. All rights reserved.
//
import UIKit
import Foundation
enum DownloadFileType: String {
case Video = "mp4"
case Image = "jpg"
case Document = "pdf"
}
class EncryptorManager: NSObject {
let password:String = "123456789"
class var sharedInstance: EncryptorManager {
get{
struct StaticObject {
static var instance: EncryptorManager? = nil
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&StaticObject.onceToken) {
StaticObject.instance = EncryptorManager()
}
return StaticObject.instance!
}
}
//using AFHTTPRequestOperation
func downloadWithFinalEncryption(fileURL: String, filename: String, progress: (total: CGFloat) -> Void, completion: (filePath: String) -> Void, failure: (error: NSError) -> Void){
if let url = NSURL(string: fileURL) {
//generate download request operation
let requestURL: NSURLRequest = NSURLRequest(URL: url)
let operation: AFHTTPRequestOperation = AFHTTPRequestOperation(request: requestURL)
let paths: NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let filePath:String = paths.objectAtIndex(0).stringByAppendingPathComponent(filename)
NSLog("FILEURL: \(fileURL)")
NSLog("FILEPATH: \(filePath)")
operation.outputStream = NSOutputStream(toFileAtPath: filePath, append: false)
operation.setDownloadProgressBlock({(bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in
let total:CGFloat = CGFloat(totalBytesRead) / CGFloat(totalBytesExpectedToRead)
NSLog("TOTAL BYTES READ: \(totalBytesRead)")
NSLog("TOTAL BYTES EXP: \(totalBytesExpectedToRead)")
NSLog("BYTES READ: \(bytesRead)")
progress(total: total)
})
operation.setCompletionBlockWithSuccess(
{ (requestOperation: AFHTTPRequestOperation!, result : AnyObject!) -> Void in
//encrypt downloaded file
self.encrypt(filePath,
completion: {(filePath: String) -> Void in
completion(filePath: filePath)
},
failure: {(error: NSError) -> Void in
failure(error: error)
})
},failure: { (requestOperation: AFHTTPRequestOperation!, error: NSError!) -> Void in
failure(error: error)
})
operation.start()
} else {
let error = NSError(domain: "com.crowdvac.EncryptApp.errorURL", code: 1001, userInfo: [NSLocalizedDescriptionKey : "Error: URL is not valid for download"])
failure(error: error)
}
}
//using AFNEtworking+Streaming class (https://github.com/deanWombourne/AFNetworking-streaming)
func downloadWithStreamEncryption(fileURL: String, filename: String, progress: (total: CGFloat) -> Void, completion: (filePath: String) -> Void, failure: (error: NSError) -> Void){
if let url = NSURLComponents(string: fileURL) {
let manager = DWHTTPStreamSessionManager(baseURL: url.URL)
let encryptor = RNCryptor.Encryptor(password: self.password)
let cipherdata = NSMutableData()
manager.GET(fileURL,
parameters: [],
data: {(task: NSURLSessionDataTask!, data: AnyObject!) -> Void in
NSLog("stream encryption")
cipherdata.appendData(encryptor.updateWithData(data as! NSData))
},
success: {(task: NSURLSessionDataTask!) -> Void in
cipherdata.appendData(encryptor.finalData())
self.saveFile(cipherdata, filename: "EncryptedStream.file",
completion: {(filePath: String) -> Void in
completion(filePath: filePath)
},
failure: {(error: NSError) -> Void in
failure(error: error)
})
},
failure: {(task: NSURLSessionDataTask!, error: NSError!) -> Void in
failure(error: error)
})
} else {
let error = NSError(domain: "com.crowdvac.EncryptApp.errorURL", code: 1001, userInfo: [NSLocalizedDescriptionKey : "Error: URL is not valid for download"])
failure(error: error)
}
}
func saveFile(data: NSData, filename: String, completion: (filePath: String) -> Void, failure: (error: NSError) -> Void){
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let filepath = dir.stringByAppendingPathComponent(filename);
//write data to file
do {
try data.writeToFile(filepath, options: NSDataWritingOptions.DataWritingAtomic)
completion(filePath: filepath)
} catch let error as NSError {
print(error.localizedDescription)
failure(error: error)
}
}
}
func encrypt(path: String, completion: (filePath: String) -> Void, failure: (error: NSError) -> Void){
//Execute Encryption
do {
let data = try NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe)
let cipherdata:NSData = RNCryptor.encryptData(data, password: self.password)
print("CIPHER DATA: \(cipherdata)")
//SAVE ENCRYPTED FILE
EncryptorManager.sharedInstance.saveFile(cipherdata,
filename: "EncryptedFile.data",
completion: {(filePath: String) -> Void in
NSLog("ENCRYPTED FILEPATH: \(filePath)")
print("ENCRYPTED: \(cipherdata)")
completion(filePath: filePath)
},
failure: {(error: NSError) -> Void in
failure(error: error)
})
} catch let error as NSError {
print(error.localizedDescription)
}
}
func decrypt(path: String, filename: String, completion: (filePath: String) -> Void, failure: (error: NSError) -> Void){
//Execute Decryption
do {
print("ENCRYPTED PATH: \(path)")
let cipherdata = try NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe)
print("CIPHER DATA: \(cipherdata)")
let originalData = try RNCryptor.decryptData(cipherdata, password: self.password)
//save decrypted filePath
EncryptorManager.sharedInstance.saveFile(originalData,
filename: filename,
completion: {(filePath: String) -> Void in
NSLog("DECRYPTED FILEPATH: \(filePath)")
completion(filePath: filePath)
},
failure: {(error: NSError) -> Void in
failure(error: error)
})
} catch let error as NSError {
print(error.localizedDescription)
}
}
}//end
| mit | bbe08bf808067b576e6bfd4902e28f09 | 40.389744 | 184 | 0.53971 | 5.67182 | false | false | false | false |
lostatseajoshua/Alerts | Alerts/AlertCoordinator.swift | 1 | 11563 | //
// AlertCoordinator.swift
// Alerts
//
// Created by Joshua Alvarado on 6/1/16.
// Copyright © 2016 Joshua Alvarado. All rights reserved.
//
import Foundation
import UIKit
/**
The AlertCoordinator class is used to enqueue `Alert`s to display. The `main` instance of this class is to be used.
The AlertCoorinator enqueues `Alert` type instances to display by enqueuing each by priority. The alerts are placed in a First In First Out collection organized by the alert's priority property.
To use this class enqueue the alerts desired and then call the `display` method to begin the process of displaying the alerts. Use the `pause` method to temporarily hold back alerts from displaying. To tear down the class call the `reset` method and the queue will be emptied.
*/
class AlertCoordinator: NSObject {
private(set) var highPriorityQueue = [Alert]()
private(set) var defaultPriorityQueue = [Alert]()
private(set) var lowPriorityQueue = [Alert]()
private(set) var paused = true
private weak var currentDisplayingAlert: Alert? = nil
static let main = AlertCoordinator()
/// Push an alert to the queue
func enqueue(alert: Alert, atIndex index: Int? = nil) {
switch alert.priority {
case .high:
highPriorityQueue.insert(alert, at: index ?? highPriorityQueue.endIndex)
if !paused {
display()
}
case .medium:
defaultPriorityQueue.insert(alert, at: index ?? defaultPriorityQueue.endIndex)
case .low:
lowPriorityQueue.insert(alert, at: index ?? lowPriorityQueue.endIndex)
}
}
/// Show alerts and unpause coordinator
func display() {
paused = false
dequeueAlert()
}
/**
Stop alerts from being presented.
This will not remove any active alerts on display
*/
func pause() {
paused = true
}
/// Dismiss any actively displaying alert, remove all alerts from the queue and pause the coordinator
func reset() {
removeCurrentDisplayingAlert(force: true, completion: nil)
highPriorityQueue.removeAll()
defaultPriorityQueue.removeAll()
lowPriorityQueue.removeAll()
paused = true
}
fileprivate func onCurrentAlertDismissed() {
currentDisplayingAlert = nil
display()
}
private func nextAlert() -> Alert? {
if !highPriorityQueue.isEmpty {
return highPriorityQueue.removeFirst()
}
if !defaultPriorityQueue.isEmpty {
return defaultPriorityQueue.removeFirst()
}
if !lowPriorityQueue.isEmpty {
return lowPriorityQueue.removeFirst()
}
return nil
}
private func dequeueAlert() {
guard let alert = nextAlert() else {
return
}
removeCurrentDisplayingAlert(force: false) {
if let dismissedAlert = $0 {
self.putBack(dismissedAlert)
self.present(alert)
} else {
self.present(alert)
}
}
}
private func removeCurrentDisplayingAlert(force: Bool, completion: ((Alert?) -> Void)?) {
guard let currentDisplayingAlert = currentDisplayingAlert else {
completion?(nil)
return
}
if force || currentDisplayingAlert.dismissable {
currentDisplayingAlert.dismiss(true) {
completion?(currentDisplayingAlert)
}
}
}
private func putBack(_ alert: Alert) {
enqueue(alert: alert, atIndex: 0)
}
private func present(_ alert: Alert) {
// present alert in a new UIWindow
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert.alertController, animated: true) {
self.currentDisplayingAlert = alert
}
}
override var description: String {
let displaying: String
if currentDisplayingAlert != nil {
displaying = "is displaying"
} else {
displaying = "is not displaying"
}
let numOfAlert = highPriorityQueue.count + defaultPriorityQueue.count + lowPriorityQueue.count
return "Alert Coordinator is " + displaying + "an alert with \(numOfAlert) alerts queued."
}
override var debugDescription: String {
let displaying: String
if currentDisplayingAlert != nil {
displaying = "is displaying"
} else {
displaying = "is not displaying"
}
return "Alert Coordinator is " + displaying + "an alert with \(highPriorityQueue.count) hight alerts, \(defaultPriorityQueue.count) default alerts, and \(lowPriorityQueue.count) low alerts queued."
}
}
/**
An `Alert` is an object that hanldes a `UIAlertController` with added features. This class replaces the direct use of `UIAlertContoller`. With an instance of this class display it by enqueueing to an instance of an `AlertCoordinator`.
*/
class Alert {
let title: String?
let message: String?
let priority: Priority
let style: UIAlertControllerStyle
var actions = [AlertAction]()
fileprivate var dismissable: Bool {
return priority != .high
}
lazy var alertController: UIAlertController = {
let alertController = UIAlertController(title: self.title, message: self.message, preferredStyle: self.style)
// loop through actions and add to alert controller
if !self.actions.isEmpty {
for action in self.actions {
let alertAction = UIAlertAction(title: action.title, style: action.style, handler: action.actionHandler)
alertController.addAction(alertAction)
if action.preferred {
// set preferred action after action has been added
if #available(iOS 9.0, *) {
alertController.preferredAction = alertAction
}
}
}
}
return alertController
}()
enum Priority {
case high
/// Default priorty
case medium
case low
}
/**
Creates and returns an Alert to be used by an `AlertCoordinator`.
After creating the Alert actions can be added by appending to the `actions` property.
- parameters:
- title: The title of the alert. Use this string to get the user’s attention and communicate the reason for the alert.
- message: descriptive text that provides additional details about the reason for the alert.
- priority: The level of urgency of the alert.
- style: The style to use when presenting the alert controller. Use this parameter to configure the alert controller as an action sheet or as a modal alert.
- alertActions: Adds actions
*/
init(title: String?, message: String?, priority: Priority = .medium, style: UIAlertControllerStyle = .alert, alertActions: [AlertAction]?) {
self.title = title
self.message = message
self.priority = priority
if let actions = alertActions {
self.actions = actions
}
self.style = style
}
/**
Dismiss the alert. Calling dismiss on the `alertController` property will give the same result but this method adds the completion of the alert action to keep the AlertCoordinator in sync.
- parameters:
- animated: Pass `true` to animate the transition.
- completion: The block to execute after the alert is dismissed. This block has no return value and takes no parameters. You may specify nil for this parameter.
- important: it is important to call `AlertAction.complete()` on manual of an alert to keep the AlertCoordinator in sync when not using this method. This method does it automatically on completion.
*/
func dismiss(_ animated: Bool, completion: (() -> Void)?) {
alertController.dismiss(animated: true) {
completion?()
AlertAction.complete()
}
}
}
/**
The object for encapsulating an action to add to an `Alert`.
Alert Actions coordinate the completion of their task to the main `AlertCoordinator` so that other alerts can display when the encapsulating alert is done running its work. This is done automatically for actions. It can be done manually if finer control is needed for actions that take more time. To manually control the process by initializing an `AlertAction` with false in the `completeOnDismiss` parameter and call `AlertAction.complete()` wherever the alert action completes. If the `AlertCoordinator` can continue to display alerts (not paused and more alerts are queued) then the coordinator will continue to display alerts after the `complete` call.
- important: fire `AlertAction.complete()` when your custom action handler is complete on escaping long running tasks
*/
struct AlertAction {
let title: String
let style: UIAlertActionStyle
private(set) var actionHandler: ((UIAlertAction) -> Void)?
let preferred: Bool
/**
Creates an instance of an `AlertAction` to be added to an `Alert`
- parameters:
- title: The text to use for the button title. The value you specify should be localized for the user’s current language. This parameter must not be nil, except in a tvOS app where a nil title may be used with cancel.
- style: Additional styling information to apply to the button. Use the style information to convey the type of action that is performed by the button. For a list of possible values, see the constants in UIAlertActionStyle.
- preferred: The preferred action for the user to take from an alert. *NOTE: Only available on iOS 9+
- completeOnDismiss: `true` to call `complete` automatically on the action completion. `false` to not add the complete on the action.
- actionHandler: A block to execute when the user selects the action. This block has no return value and takes the selected action-object as its only parameter.
*/
init(title: String, style: UIAlertActionStyle, preferred: Bool = false, completeOnDismiss: Bool = true, actionHandler: ((UIAlertAction) -> Void)? = nil) {
self.title = title
self.style = style
self.preferred = preferred
self.actionHandler = { action in
actionHandler?(action)
if completeOnDismiss {
AlertAction.complete()
}
}
}
/**
Completes a manual Alert action
The `AlertCoordinator` will display alerts after if any are queued and the coordinator is not paused.
*/
static func complete() {
AlertCoordinator.main.onCurrentAlertDismissed()
}
/**
Creates a default confirmation `AlertAction` with a title of Okay.
- parameter preferred: `true` sets the default action preferred *NOTE: Only available on iOS 9+
- returns: An AlertAction with default style
*/
static func defaultAction(preferred: Bool = false) -> AlertAction {
return AlertAction(title: "Okay", style: .default, preferred: preferred)
}
}
| mit | d259b08ccc71e6458ef0698dc35f34dd | 39.412587 | 658 | 0.648815 | 5.143747 | false | false | false | false |
matsprea/omim | iphone/Maps/UI/Search/SearchBar.swift | 1 | 1685 | @objc enum SearchBarState: Int {
case ready
case searching
case back
}
final class SearchBar: SolidTouchView {
@IBOutlet var searchIcon: UIImageView!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet var backButton: UIButton!
@IBOutlet var searchTextField: SearchTextField!
override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .top, iPad: .left) }
override var placePageAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
override var trafficButtonAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .top, iPad: .left) }
override var tabBarAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: [], iPad: .left) }
@objc var state: SearchBarState = .ready {
didSet {
if state != oldValue {
updateLeftView()
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateLeftView()
searchTextField.leftViewMode = UITextField.ViewMode.always
searchTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
}
private func updateLeftView() {
searchIcon.isHidden = true
activityIndicator.isHidden = true
backButton.isHidden = true
switch state {
case .ready:
searchIcon.isHidden = false
case .searching:
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .back:
backButton.isHidden = false
}
}
}
| apache-2.0 | 9db76cc94de721b0b12acd338f605aad | 30.792453 | 132 | 0.734125 | 4.693593 | false | false | false | false |
Keenan144/SpaceKase | SpaceKase/SettingScene.swift | 1 | 6878 | //
// SettingScene.swift
// SpaceKase
//
// Created by Keenan Sturtevant on 6/5/16.
// Copyright © 2016 Keenan Sturtevant. All rights reserved.
//
import SpriteKit
class SettingScene: SKScene {
var defaults = NSUserDefaults()
var backButton:SKLabelNode!
var easyButton:SKLabelNode!
var normalButton:SKLabelNode!
var hardButton:SKLabelNode!
var resetButton:SKLabelNode!
var godModeButton:SKLabelNode!
var touchLocation:CGPoint!
override func didMoveToView(view: SKView) {
addBackButton()
addLevelButtons()
addGodModeButton()
addResetButton()
}
override func touchesBegan(touches: Set<UITouch>, withEvent: UIEvent?) {
for touch in touches{
touchLocation = touch.locationInNode(self)
let pos = touch.locationInNode(self)
let node = nodeAtPoint(pos)
if (node == backButton) {
startMenu()
} else if (node == easyButton) {
defaults.setObject("Easy", forKey: "Difficulity")
defaults.setObject(200, forKey: "Health")
defaults.setObject(1, forKey: "Damage")
defaults.setObject(1, forKey: "SpawnRate")
addLevelButtons()
} else if (node == normalButton) {
defaults.setObject("Normal", forKey: "Difficulity")
defaults.setObject(150, forKey: "Health")
defaults.setObject(1, forKey: "Damage")
defaults.setObject(0.5, forKey: "SpawnRate")
addLevelButtons()
} else if (node == hardButton) {
defaults.setObject("Hard", forKey: "Difficulity")
defaults.setObject(100, forKey: "Health")
defaults.setObject(1, forKey: "Damage")
defaults.setObject(0.2, forKey: "SpawnRate")
addLevelButtons()
} else if (node == resetButton) {
defaults.setObject("Normal", forKey: "Difficulity")
defaults.setObject(150, forKey: "Health")
defaults.setObject(1, forKey: "Damage")
defaults.setObject(0.5, forKey: "SpawnRate")
defaults.setObject(0, forKey: "p1")
defaults.setObject(0, forKey: "p2")
defaults.setObject(0, forKey: "p3")
defaults.setObject(0, forKey: "p4")
defaults.setObject(0, forKey: "p5")
Helper.toggleInvincibility(false)
startMenu()
} else if (node == godModeButton) {
if Helper.isInvincible() == false {
Helper.toggleInvincibility(true)
self.godModeButton.removeFromParent()
addGodModeButton()
} else {
Helper.toggleInvincibility(false)
self.godModeButton.removeFromParent()
addGodModeButton()
}
} else {
print("UNKNOWN ACTION")
print("ERROR [\(touchLocation)]")
}
}
}
private func setDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(100, forKey: "Health")
defaults.setObject(5, forKey: "Damage")
}
private func addBackButton() {
backButton = SKLabelNode(fontNamed: "Arial")
backButton.text = "Back"
backButton.fontSize = 20
backButton.position = CGPoint(x: self.frame.minX + 30 , y: self.frame.maxY - 30)
self.addChild(backButton)
}
private func addEasyButton() {
easyButton = SKLabelNode(fontNamed: "Arial")
if ((defaults.objectForKey("Difficulity") != nil && defaults.objectForKey("Difficulity") as! String == "Easy")) {
easyButton.text = "-> Easy <-"
easyButton.fontColor = UIColor.yellowColor()
} else {
easyButton.text = "Easy"
}
easyButton.fontSize = 20
easyButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 50)
self.addChild(easyButton)
}
private func addNormalButton() {
normalButton = SKLabelNode(fontNamed: "Arial")
if ((defaults.objectForKey("Difficulity") != nil && defaults.objectForKey("Difficulity") as! String == "Normal")) {
normalButton.text = "-> Normal <-"
normalButton.fontColor = UIColor.yellowColor()
} else {
normalButton.text = "Normal"
}
normalButton.fontSize = 20
normalButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(normalButton)
}
private func addHardButton() {
hardButton = SKLabelNode(fontNamed: "Arial")
if ((defaults.objectForKey("Difficulity") != nil && defaults.objectForKey("Difficulity") as! String == "Hard")) {
hardButton.text = "-> Hard <-"
hardButton.fontColor = UIColor.yellowColor()
} else {
hardButton.text = "Hard"
}
hardButton.fontSize = 20
hardButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 50 )
self.addChild(hardButton)
}
private func addGodModeButton() {
godModeButton = SKLabelNode(fontNamed: "Arial")
godModeButton.text = "God Mode: \(Helper.isInvincible())"
godModeButton.fontSize = 20
godModeButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 90 )
self.addChild(godModeButton)
}
private func addResetButton() {
resetButton = SKLabelNode(fontNamed: "Arial")
resetButton.text = "Reset"
resetButton.fontSize = 10
resetButton.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 220)
self.addChild(resetButton)
}
private func startMenu() {
let skView = self.view as SKView!;
let gameScene = MenuScene(size: (skView?.bounds.size)!)
let transition = SKTransition.fadeWithDuration(0.15)
view!.presentScene(gameScene, transition: transition)
}
private func startSettings() {
let skView = self.view as SKView!;
let gameScene = SettingScene(size: (skView?.bounds.size)!)
let transition = SKTransition.fadeWithDuration(0.15)
view!.presentScene(gameScene, transition: transition)
}
private func addLevelButtons() {
if easyButton != nil{
easyButton.removeFromParent()
}
addEasyButton()
if normalButton != nil {
normalButton.removeFromParent()
}
addNormalButton()
if hardButton != nil {
hardButton.removeFromParent()
}
addHardButton()
}
}
| mit | 7a0cae8b194e1bccc0539251782fb717 | 35.194737 | 123 | 0.569289 | 4.662373 | false | false | false | false |
apple/swift-nio-extras | Sources/NIOSOCKS/Messages/Errors.swift | 1 | 2705 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Wrapper for SOCKS protcol error.
public enum SOCKSError {
/// The SOCKS client was in a different state to that required.
public struct InvalidClientState: Error, Hashable {
public init() {
}
}
/// The SOCKS server was in a different state to that required.
public struct InvalidServerState: Error, Hashable {
public init() {
}
}
/// The protocol version was something other than *5*. Note that
/// we currently only supported SOCKv5.
public struct InvalidProtocolVersion: Error, Hashable {
public var actual: UInt8
public init(actual: UInt8) {
self.actual = actual
}
}
/// Reserved bytes should always be the `NULL` byte *0x00*. Something
/// else was encountered.
public struct InvalidReservedByte: Error, Hashable {
public var actual: UInt8
public init(actual: UInt8) {
self.actual = actual
}
}
/// SOCKSv5 only supports IPv4 (*0x01*), IPv6 (*0x04*), or FQDN(*0x03*).
public struct InvalidAddressType: Error, Hashable {
public var actual: UInt8
public init(actual: UInt8) {
self.actual = actual
}
}
/// The server selected an authentication method not supported by the client.
public struct InvalidAuthenticationSelection: Error, Hashable {
public var selection: AuthenticationMethod
public init(selection: AuthenticationMethod) {
self.selection = selection
}
}
/// The client and server were unable to agree on an authentication method.
public struct NoValidAuthenticationMethod: Error, Hashable {
public init() {
}
}
/// The SOCKS server failed to connect to the target host.
public struct ConnectionFailed: Error, Hashable {
public var reply: SOCKSServerReply
public init(reply: SOCKSServerReply) {
self.reply = reply
}
}
/// The client or server receieved data when it did not expect to.
public struct UnexpectedRead: Error, Hashable {
public init() {
}
}
}
| apache-2.0 | bbae394cba832ded13ddd4f60d8e67d8 | 29.738636 | 81 | 0.586322 | 4.945155 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/GameSequence.swift | 1 | 6763 | //
// CurrentGame.swift
// MEGameTracker
//
// Created by Emily Ivie on 8/9/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
public struct GameSequence: Codable {
enum CodingKeys: String, CodingKey {
case uuid
case lastPlayedShepard
}
// MARK: Constants
public typealias ShepardVersionIdentifier = (uuid: String, gameVersion: GameVersion)
// MARK: Properties
public var rawData: Data? { get { return nil } set {} } // block this behavior
public var id: UUID { return uuid }
public var uuid: UUID
public var shepard: Shepard?
/// (DateModifiable Protocol)
/// Date when value was created.
public var createdDate = Date()
/// (DateModifiable Protocol)
/// Date when value was last changed.
public var modifiedDate = Date()
/// (CloudDataStorable Protocol)
/// Flag for whether the local object has changes not saved to the cloud.
public var isSavedToCloud = false
/// (CloudDataStorable Protocol)
/// A set of any changes to the local object since the last cloud sync.
public var pendingCloudChanges = CodableDictionary()
/// (CloudDataStorable Protocol)
/// A copy of the last cloud kit record.
public var lastRecordData: Data?
/// (Interface Builder) (Transient)
public var isDummyData = false
// MARK: Computed Properties
public var gameVersion: GameVersion {
return shepard?.gameVersion ?? .game1
}
// MARK: Change Listeners And Change Status Flags
/// (DateModifiable Protocol) (Transient)
/// Flag to indicate that there are changes pending a core data sync.
public var hasUnsavedChanges = false
// MARK: Initialization
public init(uuid: UUID? = nil) {
self.uuid = uuid ?? UUID()
let shepard = Shepard(gameSequenceUuid: self.uuid, gameVersion: .game1)
self.shepard = shepard
markChanged()
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
uuid = try container.decode(UUID.self, forKey: .uuid)
if let lastPlayedShepard = try container.decodeIfPresent(UUID.self, forKey: .lastPlayedShepard),
lastPlayedShepard != self.shepard?.uuid,
let shepard = Shepard.get(uuid: lastPlayedShepard) {
self.shepard = shepard
} else {
// you only reach this if there was an error saving shepard last game save.
self.shepard = Shepard.lastPlayed(gameSequenceUuid: uuid)
?? Shepard(gameSequenceUuid: self.uuid, gameVersion: .game1)
markChanged()
}
try unserializeDateModifiableData(decoder: decoder)
try unserializeLocalCloudData(decoder: decoder)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(uuid, forKey: .uuid)
try container.encode(shepard?.uuid, forKey: .lastPlayedShepard)
try serializeDateModifiableData(encoder: encoder)
try serializeLocalCloudData(encoder: encoder)
}
}
// MARK: Retrieval Functions of Related Data
extension GameSequence {
public func getAllShepards() -> [Shepard] {
return Shepard.getAll(gameSequenceUuid: uuid)
}
}
// MARK: Data Change Actions
extension GameSequence {
/// Changes current shepard to a different game version shepard, creating that shepard if necessary.
/// Warning: due to App static current shepard signal, DO NOT call this directly.
internal mutating func change(gameVersion newGameVersion: GameVersion) {
guard newGameVersion != gameVersion else { return }
// save prior shepard
_ = shepard?.saveAnyChanges(isCascadeChanges: .down, isAllowDelay: false)
// locate different gameVersion shepard
guard var shepard = getShepardFromVersion(newGameVersion) else { return }
// save if new
if shepard.isNew {
shepard.isNew = false
addNewShepardVersion(shepard)
}
self.shepard = shepard
markChanged()
// save current game and shepard (to mark most recent)
_ = save(isAllowDelay: false)
}
/// Used to change game version OR to load a shepard to test conditions against (see: Decision)
public func getShepardFromVersion(_ newGameVersion: GameVersion) -> Shepard? {
guard newGameVersion != gameVersion else { return nil }
// locate new shepard
if let foundShepard = Shepard.get(gameVersion: newGameVersion, gameSequenceUuid: uuid) {
return foundShepard
} else {
let gender = shepard?.gender ?? .male
var newShepard = Shepard(gameSequenceUuid: uuid, gender: gender, gameVersion: newGameVersion)
// share all data from other game version:
if let shepard = self.shepard {
newShepard.setNewData(oldData: shepard.getSharedData())
}
newShepard.isNew = true
return newShepard
}
}
private mutating func addNewShepardVersion(_ shepard: Shepard) {
var shepard = shepard
shepard.gameSequenceUuid = uuid
_ = shepard.saveAnyChanges(isCascadeChanges: .down) //isAllowDelay = true
// markChanged()
// _ = saveAnyChanges() // this is called later in GameSequence change(gameVersion:)
}
/// Creates a clone of the prior game, resetting at the game version specified
func restarted(at gameVersion: GameVersion, isAllowDelay: Bool) -> GameSequence {
var newGameSequence = GameSequence()
_ = copyAll(below: gameVersion, destinationGame: newGameSequence)
if let newShepard = Shepard.get(gameVersion: gameVersion, gameSequenceUuid: newGameSequence.uuid) {
newGameSequence.shepard = newShepard.incrementDuplicationCount(
isSave: true,
isNotify: false
)
}
return newGameSequence
}
}
// MARK: Dummy data for Interface Builder
extension GameSequence {
public static func getDummy() -> GameSequence? {
var game = GameSequence()
game.isDummyData = true
game.shepard = Shepard.getDummy()
game.shepard?.gameSequenceUuid = game.uuid
return game
}
}
// MARK: DateModifiable
extension GameSequence: DateModifiable {
/// (Override)
public mutating func markChanged() {
rawData = nil
touch()
notifySaveToCloud(fields: ["lastPlayedShepard": shepard?.uuid ?? ""])
hasUnsavedChanges = true
}
}
// MARK: Sorting
extension GameSequence {
static func sort(_ first: GameSequence, _ second: GameSequence) -> Bool {
return (first.shepard?.modifiedDate ?? Date())
.compare(second.shepard?.modifiedDate ?? Date()) == .orderedDescending
}
}
// MARK: Equatable
extension GameSequence: Equatable {
public static func == (_ lhs: GameSequence, _ rhs: GameSequence) -> Bool { // not true equality, just same db row
return lhs.uuid == rhs.uuid
}
}
//// MARK: Hashable
//extension GameSequence: Hashable {
// public var hashValue: Int { return uuid.hashValue }
//}
| mit | 6c84b7e85029da6030e69e90e738ca5a | 31.509615 | 114 | 0.70349 | 4.215711 | false | false | false | false |
ElvishJerricco/DispatchKit | Sources/DispatchQueue.swift | 2 | 4192 | //
// DispatchQueue.swift
// DispatchKit <https://github.com/anpol/DispatchKit>
//
// Copyright (c) 2014 Andrei Polushin. All rights reserved.
//
import Foundation
public struct DispatchQueue : DispatchObject, DispatchResumable {
@available(*, unavailable, renamed="rawValue")
public var queue: dispatch_queue_t {
return rawValue
}
@available(*, unavailable, renamed="DispatchQueue(rawValue:)")
public init(raw queue: dispatch_queue_t) {
self.rawValue = queue
}
public let rawValue: dispatch_queue_t
public init(rawValue: dispatch_queue_t) {
self.rawValue = rawValue
}
public init!(_ label: String! = nil,
attr: DispatchQueueAttr = .Serial,
qosClass: DispatchQOSClass = .Unspecified,
relativePriority: Int = 0) {
assert(Int(QOS_MIN_RELATIVE_PRIORITY)...0 ~= relativePriority,
"Invalid parameter: relative_priority")
if qosClass == .Unspecified {
guard let rawValue = dispatch_queue_create(label, attr.rawValue) else {
return nil
}
self.rawValue = rawValue
} else if #available(iOS 8.0, *) {
// iOS 8 and later: apply QOS class
guard
let qosAttr = dispatch_queue_attr_make_with_qos_class(
attr.rawValue, qosClass.rawClass, Int32(relativePriority)),
let rawValue = dispatch_queue_create(label, qosAttr)
else {
return nil
}
self.rawValue = rawValue
} else {
guard let rawValue = dispatch_queue_create(label, attr.rawValue) else {
return nil
}
self.rawValue = rawValue
// iOS 7 and earlier: simulate QOS class by applying a target queue.
let priority = DispatchQueuePriority(qosClass: qosClass)
let target = dispatch_get_global_queue(priority.rawValue, 0)
dispatch_set_target_queue(rawValue, target)
}
}
public var clabel: UnsafePointer<CChar> {
// this function never returns NULL, despite its documentation.
return dispatch_queue_get_label(rawValue)
}
public var label: String {
let (s, _) = String.fromCStringRepairingIllFormedUTF8(clabel)
return s ?? "(null)"
}
public var isMainQueue: Bool {
return label == "com.apple.main-thread"
}
public var isGlobalQueue: Bool {
return label.hasPrefix("com.apple.root.")
}
public var isSystemQueue: Bool {
return label.hasPrefix("com.apple.")
}
// NOTE set to nil to reset target queue to default
public func setTargetQueue(targetQueue: DispatchQueue?) {
assert(!isSystemQueue)
dispatch_set_target_queue(rawValue, targetQueue?.rawValue)
}
public func suspend() {
dispatch_suspend(rawValue)
}
public func resume() {
dispatch_resume(rawValue)
}
public func sync(block: dispatch_block_t) {
dispatch_sync(rawValue, block)
}
public func barrierSync(block: dispatch_block_t) {
assert(!isSystemQueue)
dispatch_barrier_sync(rawValue, block)
}
public func apply(iterations: Int, block: (Int) -> Void) {
dispatch_apply(iterations, rawValue, { block($0) })
}
public func async(block: dispatch_block_t) {
dispatch_async(rawValue, block)
}
public func async(group: DispatchGroup, block: dispatch_block_t) {
dispatch_group_async(group.rawValue, rawValue, block)
}
public func barrierAsync(block: dispatch_block_t) {
assert(!isSystemQueue)
dispatch_barrier_async(rawValue, block)
}
public func after(when: DispatchTime, block: dispatch_block_t) {
dispatch_after(when.rawValue, rawValue, block)
}
}
public struct DispatchCurrentQueue {
public var clabel: UnsafePointer<CChar> {
return dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)
}
public var label: String {
let (s, _) = String.fromCStringRepairingIllFormedUTF8(clabel)
return s ?? "(null)"
}
}
| mit | c43a0866f3a3172409c12c6416b3ce89 | 27.324324 | 83 | 0.61355 | 4.380355 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift- | SinaWeibo(stroyboard)/SinaWeibo/Classes/Main/Resource/UserAccount.swift | 1 | 3372 | //
// UserAccount.swift
// SinaWeibo
//
// Created by Minghe on 11/11/15.
// Copyright © 2015 Stanford swift. All rights reserved.
//
import UIKit
class UserAccount: NSObject, NSCoding {
///
static var userAccount: UserAccount?
///
var uid: String?
///
var access_token: String?
/// access_token的生命周期,单位是秒数
var expires_in: NSNumber?
{
didSet{
expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
}
}
/// 过期时间(年月日时分秒)
var expires_Date: NSDate?
/// 用户昵称
var screen_name: String?
/// 用户头像地址(大图),180*180
var avatar_large: String?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let property = ["access_token","expires_in","uid"]
let dict = dictionaryWithValuesForKeys(property)
return "\(dict)"
}
static let filePath = "userAccount.plist".cacheDir()
// MARK: - 外部控制方法 ------------------------------
/// 保存授权模型到文件中
func saveAccount() {
NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
}
/// 从文件中读取保存的授权模型
class func loadUserAccount() -> UserAccount?
{
// print(filePath)
// 1.判断是否已经加载过
if userAccount != nil {
// MHzLog("已经加载过了,直接返回")
return userAccount
}
// 2.如果没有加载过,就从文件中加载
userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filePath) as? UserAccount
// 3.判断是否过期
guard let date = userAccount?.expires_Date where date.compare(NSDate()) == NSComparisonResult.OrderedDescending else
{
MHzLog("已经过期了")
userAccount = nil
return userAccount
}
return userAccount
}
/// 判断是否已经登陆
class func login() -> Bool {
return UserAccount.loadUserAccount() != nil
}
// MARK: - NSCoding ------------------------------
//
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
}
//
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_Date, forKey: "expires_Date")
aCoder.encodeObject(screen_name, forKey: "screen_name")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
}
}
| mit | 6f6398baa95a9599dfb3ea28b60df207 | 26.743363 | 124 | 0.589793 | 4.596774 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYImageCaptionButton.swift | 1 | 3861 | //
// IMGLYImageCaptionButton.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 13/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
private let ImageSize = CGSize(width: 36, height: 36)
private let ImageCaptionMargin = 2
public class IMGLYImageCaptionButton: UIControl {
// MARK: - Properties
public private(set) lazy var textLabel: UILabel = {
let label = UILabel()
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont.systemFontOfSize(11)
label.textColor = UIColor.whiteColor()
return label
}()
public private(set) lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .Center
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
return imageView
}()
public override var highlighted: Bool {
didSet {
if highlighted {
backgroundColor = UIColor(white: 1, alpha: 0.2)
} else if !selected {
backgroundColor = UIColor.clearColor()
}
}
}
public override var selected: Bool {
didSet {
if selected {
backgroundColor = UIColor(white: 1, alpha: 0.2)
} else if !highlighted {
backgroundColor = UIColor.clearColor()
}
}
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = UIColor.clearColor()
configureViews()
}
// MARK: - Configuration
private func configureViews() {
let containerView = UIView()
containerView.userInteractionEnabled = false
containerView.setTranslatesAutoresizingMaskIntoConstraints(false)
containerView.addSubview(imageView)
containerView.addSubview(textLabel)
addSubview(containerView)
let views = [
"containerView" : containerView,
"imageView" : imageView,
"textLabel" : textLabel
]
let metrics: [ NSObject: NSNumber ] = [
"imageHeight" : ImageSize.height,
"imageWidth" : ImageSize.width,
"imageCaptionMargin" : ImageCaptionMargin
]
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-(>=0)-[imageView(==imageWidth)]-(>=0)-|",
options: nil,
metrics: metrics,
views: views))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-(>=0)-[textLabel]-(>=0)-|",
options: nil,
metrics: metrics,
views: views))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[imageView(==imageHeight)]-(imageCaptionMargin)-[textLabel]|",
options: .AlignAllCenterX,
metrics: metrics,
views: views))
addConstraint(NSLayoutConstraint(item: containerView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: containerView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
}
// MARK: - UIView
public override func sizeThatFits(size: CGSize) -> CGSize {
return systemLayoutSizeFittingSize(size)
}
public override class func requiresConstraintBasedLayout() -> Bool {
return true
}
}
| apache-2.0 | 3d6db1508d46417dd4e85531a0c94784 | 30.137097 | 165 | 0.600104 | 5.476596 | false | false | false | false |
johnpatrickmorgan/wtfautolayout | Sources/App/Parsing/Partials/AnonymousConstraint.swift | 1 | 3857 | import Foundation
struct AnonymousConstraint {
let first: LayoutItemAttribute
let second: LayoutItemAttribute?
let relation: Constraint.Relation
let constant: Constant
let multiplier: Multiplier
}
extension AnonymousConstraint {
init(first: (partialInstance: PartialInstance, attribute: Attribute), relation: Constraint.Relation, multiplier: Multiplier, second: (partialInstance: PartialInstance, attribute: Attribute)?, constant: Constant, names: [String:Instance]) throws {
let instance1 = try first.partialInstance.getInstance(names: names)
self.init(
first: LayoutItemAttribute(layoutItem: instance1,
attribute: first.attribute),
second: try second.map { LayoutItemAttribute(layoutItem: try $0.partialInstance.getInstance(names: names),
attribute: $0.attribute) },
relation: relation,
constant: constant,
multiplier: multiplier
)
}
init(axis: Attribute.Axis, partialInstance2: PartialInstance, comparison: (relation: Constraint.Relation, amount: Double), partialInstance1: PartialInstance, names: [String:Instance]) throws {
let instance1 = try partialInstance1.getInstance(names: names)
let instance2 = try partialInstance2.getInstance(names: names)
let pinpoints: (Attribute.PinPoint, Attribute.PinPoint) = {
switch (partialInstance1, partialInstance2) {
case (.superview, _):
return (.end, .end)
case (_, .superview):
return (.start, .start)
default:
return (.start, .end)
}
}()
let attribute1 = try Attribute(axis: axis, pinPoint: pinpoints.0)
let attribute2 = try Attribute(axis: axis, pinPoint: pinpoints.1)
self.init(first: LayoutItemAttribute(layoutItem: instance1,
attribute: attribute1),
second: LayoutItemAttribute(layoutItem: instance2,
attribute: attribute2),
relation: comparison.relation,
constant: Constant(comparison.amount),
multiplier: Multiplier())
}
init(axis: Attribute.Axis, partialInstance: PartialInstance, comparison: (relation: Constraint.Relation, amount: Double), names: [String:Instance]) throws {
let instance = try partialInstance.getInstance(names: names)
let attribute = try Attribute(axis: axis, pinPoint: .extent)
let first = LayoutItemAttribute(layoutItem: instance, attribute: attribute)
self.init(
first: first,
second: nil,
relation: comparison.relation,
constant: Constant(comparison.amount),
multiplier: Multiplier()
)
}
}
extension AnonymousConstraint {
func deanonymized(instance: Instance, isFromAutoresizingMask: Bool) -> Constraint {
let origin: Constraint.Origin
if isFromAutoresizingMask {
origin = .autoresizingMask
} else if let identifier = instance.identifier, identifier.hasPrefix("UIView-Encapsulated-Layout") {
origin = .encapsulatedLayout
} else if let identifier = instance.identifier, identifier.hasPrefix("UISV") {
origin = .stackView
} else {
origin = .user
}
return Constraint(
identity: instance,
first: first,
second: second,
relation: relation,
constant: constant,
multiplier: multiplier,
origin: origin
)
}
}
| mit | 11c250644d26f7e133d1bf41d048218e | 37.959596 | 250 | 0.590874 | 5.371866 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | App_MVC_COMPLETE/App_MVC_COMPLETE/ICOAlbumView.swift | 1 | 2315 | //
// ICOAlbumView.swift
// App_MVC_COMPLETE
//
// Created by cice on 11/7/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class ICOAlbumView: UIView {
//Vamos a añadir variables que solo deben ser vistas en esta clase
//Esta variable caratula Album representa la portada del Album de musica
private var caratulaAlbumFinal : UIImageView?
//este inicializador solo se usa cuando no tenemos control del Storyboard, es decir
//siempre que tengamos el AppDelegate determina el arranque de los controladores y
//de las vistas, esto es abstracto para el appDelegate
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//Metdodo propio
inicializadorComun()
}
init(frame: CGRect, caratulaAlbum : String) {
super.init(frame: frame)
inicializadorComun()
//NOTIFICACIONES
//Es un patron de subscripcion o publicacion que permite que un objeto ( edite siendo un remitente de un mensaje)
//este mensaje se envia a un abonado(observador/oyente/receptor de mensaje)
//Enviamos una notificacion a traves del singleton de la app, que contiene una imageView?(caratulaAlbumFimanl) y la
//direccion "urlCaratula"
//> ICOLibraryAPI
NSNotificationCenter.defaultCenter().postNotificationName("ICODescargaImagenesNotification", object: self,userInfo: ["imageView": caratulaAlbum, "urlCaratula":caratulaAlbum])
}
//Esta funcion establece valores predeterminados para la vista del album, vamos a colocar
//un fondo negro a la vista, con un margen de 5 puntos
func inicializadorComun(){
backgroundColor = UIColor.blackColor()
caratulaAlbumFinal = UIImageView(frame: CGRectMake(5, 5, frame.size.width-10, frame.size.height-10))
caratulaAlbumFinal?.layer.cornerRadius = (caratulaAlbumFinal?.frame.size.width)! / 2
caratulaAlbumFinal?.contentMode = .ScaleAspectFill
caratulaAlbumFinal?.clipsToBounds = true
addSubview(caratulaAlbumFinal!)
}
func hightLightAlbum(didHighLightView view : Bool){
if view{
backgroundColor = UIColor.whiteColor()
}else{
backgroundColor = UIColor.blackColor()
}
}
}
| apache-2.0 | 647a0c93b89d2be9269ad572d0318eb6 | 34.045455 | 178 | 0.68569 | 3.920339 | false | false | false | false |
kaojohnny/CoreStore | Sources/CoreStore.swift | 1 | 2459 | //
// CoreStore.swift
// CoreStore
//
// Copyright © 2014 John Rommel Estropia
//
// 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 CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - CoreStore
/**
`CoreStore` is the main entry point for all other APIs.
*/
public enum CoreStore {
/**
The default `DataStack` instance to be used. If `defaultStack` is not set before the first time accessed, a default-configured `DataStack` will be created.
- SeeAlso: `DataStack`
- Note: Changing the `defaultStack` is thread safe, but it is recommended to setup `DataStacks` on a common queue (e.g. the main queue).
*/
public static var defaultStack: DataStack {
get {
self.defaultStackBarrierQueue.barrierSync {
if self.defaultStackInstance == nil {
self.defaultStackInstance = DataStack()
}
}
return self.defaultStackInstance!
}
set {
self.defaultStackBarrierQueue.barrierAsync {
self.defaultStackInstance = newValue
}
}
}
// MARK: Private
private static let defaultStackBarrierQueue = GCDQueue.createConcurrent("com.coreStore.defaultStackBarrierQueue")
private static var defaultStackInstance: DataStack?
}
| mit | f8a4e401514ab7363147f46e47d03375 | 33.138889 | 160 | 0.66843 | 4.754352 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Matchers/Equal.swift | 172 | 5345 | import Foundation
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue == expectedValue && expectedValue != nil
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return matches
}
}
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable, C: Equatable>(expectedValue: [T: C]?) -> NonNilMatcherFunc<[T: C]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualValue!
}
}
/// A Nimble matcher that succeeds when the actual collection is equal to the expected collection.
/// Items must implement the Equatable protocol.
public func equal<T: Equatable>(expectedValue: [T]?) -> NonNilMatcherFunc<[T]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualValue!
}
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T>(expectedValue: Set<T>?) -> NonNilMatcherFunc<Set<T>> {
return equal(expectedValue, stringify: stringify)
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T: Comparable>(expectedValue: Set<T>?) -> NonNilMatcherFunc<Set<T>> {
return equal(expectedValue, stringify: {
if let set = $0 {
return stringify(Array(set).sort { $0 < $1 })
} else {
return "nil"
}
})
}
private func equal<T>(expectedValue: Set<T>?, stringify: Set<T>? -> String) -> NonNilMatcherFunc<Set<T>> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if let expectedValue = expectedValue {
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "<\(stringify(actualValue))>"
if expectedValue == actualValue {
return true
}
let missing = expectedValue.subtract(actualValue)
if missing.count > 0 {
failureMessage.postfixActual += ", missing <\(stringify(missing))>"
}
let extra = actualValue.subtract(expectedValue)
if extra.count > 0 {
failureMessage.postfixActual += ", extra <\(stringify(extra))>"
}
}
} else {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
}
public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func ==<T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func !=<T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func !=<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
extension NMBObjCMatcher {
public class func equalMatcher(expected: NSObject) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
return try! equal(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
| mit | 9d53a1de5ff5ba8f1e19b32f962d4ab1 | 35.114865 | 106 | 0.623948 | 4.587983 | false | false | false | false |
macfeteria/JKNotificationPanel | Example/JKNotificationPanel/JKViewController.swift | 1 | 7790 | //
// JKViewController.swift
// JKNotificationPanel
//
// Created by Ter on 12/20/2558 BE.
// http://www.macfeteria.com
// Copyright © 2558 CocoaPods. All rights reserved.
//
import UIKit
import JKNotificationPanel
class JKViewController: UIViewController,JKNotificationPanelDelegate {
var panel = JKNotificationPanel()
var defaultView:JKDefaultView?
var demoList = [String] ()
@IBOutlet weak var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "JK Demo"
demoList.append("Success")
demoList.append("Success with Custom color")
demoList.append("Warning")
demoList.append("Subtitle")
demoList.append("Subtitle with color")
demoList.append("Failed")
demoList.append("Long text")
demoList.append("Custom View")
demoList.append("Wait until tap")
demoList.append("On TableView")
demoList.append("On Navigation")
demoList.append("Delegate")
demoList.append("Completion and Alert")
demoList.append("Success with custom Image and Text")
let header = self.tableView.dequeueReusableCell(withIdentifier: "header")
header?.textLabel?.text = "JKNotificationPanel"
self.tableView.tableHeaderView = header
}
// Support oritation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.panel.transitionTo(size: self.view.frame.size)
}, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoList.count
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = demoList[(indexPath as NSIndexPath).row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
// reset to default value
panel.timeUntilDismiss = 2
panel.enableTapDismiss = false
panel.delegate = nil
switch (indexPath as NSIndexPath).row {
// Success
case 0:
panel.showNotify(withStatus: .success, belowNavigation: self.navigationController!)
// Custom color
case 1:
let view = panel.createDefaultView(withStatus: .success, title: nil)
view.setColor(UIColor(red: 67.0/255.0, green: 69.0/255.0, blue: 80.0/255.0, alpha: 1))
panel.showNotify(withView: view, belowNavigation: self.navigationController!)
// Warning
case 2:
panel.showNotify(withStatus: .warning, belowNavigation: self.navigationController!)
// Subtitle
case 3:
panel.showNotify(withStatus: .warning, belowNavigation: self.navigationController!, title: "Chelsea Football Club", message: "I have to solve the situation because every game we concede two goals minimum.' - Antonio Conte speaking after the game.")
// Subtitle with Custom color
case 4:
let view = panel.createSubtitleView(withStatus: .warning, title: "Chelsea Football Club", message: "I have to solve the situation because every game we concede two goals minimum.' - Antonio Conte speaking after the game.")
view.setColor(UIColor(red: 67.0/255.0, green: 69.0/255.0, blue: 80.0/255.0, alpha: 1))
panel.showNotify(withView: view, belowNavigation: self.navigationController!)
// Failed
case 5:
panel.showNotify(withStatus: .failed, belowNavigation: self.navigationController!)
// Long Text
case 6:
let longtext = "Guus Hiddink meeting the Chelsea players after the game."
panel.showNotify(withStatus: .success, belowNavigation: self.navigationController!, title: longtext)
// Custom View
case 7:
let nib = UINib(nibName: "CustomNotificationView", bundle: Bundle(for: type(of: self)))
let customView = nib.instantiate(withOwner: nil, options: nil).first as! UIView
let width:CGFloat = UIScreen.main.bounds.size.width
customView.frame = CGRect(x: 0, y: 0, width: width, height: 42)
panel.showNotify(withView: customView, belowNavigation: self.navigationController!)
// Wait until tap
case 8:
let text = "Tap me to dissmiss"
panel.timeUntilDismiss = 0 // zero for wait forever
panel.enableTapDismiss = true
panel.showNotify(withStatus: .success, belowNavigation: self.navigationController!, title: text)
// On the top of table view
case 9:
let text = "The Panel display on the top of the table, pull the table to see the result and tap the panel to dismiss"
panel.timeUntilDismiss = 0
panel.enableTapDismiss = true
panel.showNotify(withStatus: .warning, inView:self.tableView, title: text)
// On navigation
case 10:
let navView = self.navigationController?.view
panel.showNotify(withStatus: .success, inView: navView!)
// Delegate
case 11:
let text = "Alert after notifying done (Delegate style)"
panel.delegate = self
panel.showNotify(withStatus: .success, belowNavigation: self.navigationController!, title: text)
// Completion block
case 12:
let text = "Tab me to show alert"
panel.timeUntilDismiss = 0
panel.enableTapDismiss = false
panel.setPanelDidTapAction() {
self.notificationPanelDidTap()
}
panel.showNotify(withStatus: .success, belowNavigation: self.navigationController!, title: text)
// Custom Image
case 13:
let view = panel.createDefaultView(withStatus: .success, title: "Success panel with custom Image and text")
view.setImage(UIImage(named: "airplane-icon")!)
panel.showNotify(withView: view, belowNavigation: self.navigationController!)
default: break
}
}
// Delegate
func notificationPanelDidTap() {
let alert = UIAlertController(title: "Hello!!", message: "This is an example of how to work with completion block.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (alert) -> Void in
// Since alertview take 0.2 to dismiss, therefor fade animate must
// longer than 0.2
self.panel.dismiss(withFadeDuration: 0.4)
}))
self.present(alert, animated: true, completion: nil)
}
func notificationPanelDidDismiss() {
let alert = UIAlertController(title: "Nofity Completed", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func notifyCompleted() {
let alert = UIAlertView()
alert.title = "Nofity Completed"
alert.addButton(withTitle: "Ok")
alert.show()
}
}
| mit | 9251d6ed8ed97953d4b9eccbecf0df10 | 38.338384 | 260 | 0.626781 | 4.840895 | false | false | false | false |
lelandjansen/fatigue | ios/fatigue/YesNoQuestionCell.swift | 1 | 3127 | import UIKit
class YesNoQuestionCell: QuestionCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override var question: Question? {
didSet {
guard let question = question, question is YesNoQuestion else {
return
}
switch question.selection {
case YesNoQuestion.Answer.yes.rawValue:
selection = YesNoQuestion.Answer.yes
case YesNoQuestion.Answer.no.rawValue:
selection = YesNoQuestion.Answer.no
default:
selection = YesNoQuestion.Answer.none
}
}
}
var selection: YesNoQuestion.Answer = .none {
didSet {
switch selection {
case .yes:
yesButton.isSelected = true
noButton.isSelected = false
case .no:
yesButton.isSelected = false
noButton.isSelected = true
default:
yesButton.isSelected = false
noButton.isSelected = false
}
delegate?.setQuestionSelection(
toValue: selection.rawValue,
forCell: self
)
}
}
lazy var yesButton: UIButton = {
let button = UIButton.createStyledSelectButton(withColor: .violet)
button.setTitle(YesNoQuestion.Answer.yes.rawValue, for: .normal)
button.addTarget(self, action: #selector(handleYes), for: .touchUpInside)
return button
}()
lazy var noButton: UIButton = {
let button = UIButton.createStyledSelectButton(withColor: .violet)
button.setTitle(YesNoQuestion.Answer.no.rawValue, for: .normal)
button.addTarget(self, action: #selector(handleNo), for: .touchUpInside)
return button
}()
func handleYes() {
selection = .yes
delegate?.updateQuestionnaireOrder()
delegate?.moveToNextPage()
}
func handleNo() {
selection = .no
delegate?.updateQuestionnaireOrder()
delegate?.moveToNextPage()
}
override func setupViews() {
super.setupViews()
addSubview(yesButton)
addSubview(noButton)
yesButton.frame = CGRect(
x: (self.frame.size.width - UIConstants.buttonWidth) / 2,
y: (self.frame.size.height - UIConstants.navigationBarHeight - UIConstants.buttonHeight - UIConstants.buttonSpacing) / 2,
width: UIConstants.buttonWidth,
height: UIConstants.buttonHeight
)
noButton.frame = CGRect(
x: (self.frame.size.width - UIConstants.buttonWidth) / 2,
y: (self.frame.size.height - UIConstants.navigationBarHeight + UIConstants.buttonHeight + UIConstants.buttonSpacing) / 2 ,
width: UIConstants.buttonWidth,
height: UIConstants.buttonHeight
)
}
}
| apache-2.0 | 66f0242c66db81ee53988dd1ec5f3a3e | 29.656863 | 134 | 0.566997 | 5.059871 | false | false | false | false |
jam891/ReactKitCatalog | Shared/Helper.swift | 1 | 1847 | //
// Helper.swift
// ReactKitCatalog
//
// Created by Yasuhiro Inami on 2015/03/21.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Foundation
import Dollar
import SwiftTask
import Alamofire
import SwiftyJSON
// pick `count` random elements from `sequence`
func _pickRandom<S: SequenceType>(sequence: S, _ count: Int) -> [S.Generator.Element]
{
var array = Array(sequence)
var pickedArray = Array<S.Generator.Element>()
for _ in 0..<count {
if array.isEmpty { break }
pickedArray.append(array.removeAtIndex($.random(array.count)))
}
return pickedArray
}
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss.SSS"
return formatter
}()
func _dateString(date: NSDate) -> String
{
return dateFormatter.stringFromDate(date)
}
enum CatalogError: String, ErrorType
{
case InvalidArgument
}
/// analogous to JavaScript's `$.getJSON(requestUrl)` using Alamofire & SwiftyJSON
func _requestTask(request: Alamofire.Request) -> Task<Void, SwiftyJSON.JSON, ErrorType>
{
guard let urlString = request.request?.URLString else {
return Task(error: CatalogError.InvalidArgument)
}
return Task { fulfill, reject in
print("request to \(urlString)")
request.responseJSON { request, response, jsonObject, error in
print("response from \(urlString)")
if let error = error {
reject(error)
return
}
Async.background {
let json = JSON(jsonObject!)
Async.main {
fulfill(json)
}
}
}
return
}
} | mit | 237a0118cd9c6d140292c8098d68a1b6 | 22.666667 | 87 | 0.591328 | 4.62406 | false | false | false | false |
rmavani/SocialQP | QPrint/Controllers/MyFiles/MyFilesViewController.swift | 1 | 8285 | //
// MyFilesViewController.swift
// QPrint
//
// Created by Admin on 23/02/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
// MARK: - MyFilesCell
class MyFilesCell : UITableViewCell {
// MARK: - Initialize IBOutlets
@IBOutlet var lblFileName : UILabel!
@IBOutlet var lblFilePages : UILabel!
@IBOutlet var lblFileDate : UILabel!
@IBOutlet var btnDelete : UIButton!
@IBOutlet var btnDownload : UIButton!
}
// MARK: - MyFilesViewController
class MyFilesViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Initialize IBOutlets
@IBOutlet var lblTitle : UILabel!
@IBOutlet var tblList : UITableView!
var arrayFiles = NSMutableArray()
// MARK: - Initialize Variables
var strUserId : String = ""
var arrFilesList : NSMutableArray = NSMutableArray()
// MARK: - Initialize
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
lblTitle.layer.shadowOpacity = 0.5
lblTitle.layer.shadowOffset = CGSize(width : 0.5, height : 0.5)
lblTitle.layer.shadowColor = UIColor.darkGray.cgColor
let dictData = UserDefaults.standard.data(forKey: "UserData")
let dictRegisterData = NSKeyedUnarchiver.unarchiveObject(with: dictData!) as! NSMutableDictionary
strUserId = (dictRegisterData.object(forKey: "userid") as? String)!
// getFilesList()
self.getMyFiles()
}
// MARK: - UIButton Click Events
@IBAction func btn_DeleteClick(_ sender: UIButton) {
// deleteFile()
}
//MARK: - UITableView Delegate & DataSource Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// return arrayFiles.count
return arrFilesList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell : MyFilesCell = tblList.dequeueReusableCell(withIdentifier: "MyFilesCell", for: indexPath) as! MyFilesCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.lblFileName.text = "\(arrFilesList.object(at: indexPath.row))"
cell.btnDelete.tag = indexPath.row
cell.btnDelete.addTarget(self, action: #selector(MyFilesViewController.btnDeleteClick(_:)), for: UIControlEvents.touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func btnDeleteClick(_ sender: UIButton)
{
var documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
documentsUrl = documentsUrl.appendingPathComponent("Inbox")
let fileName : String = arrFilesList.object(at: sender.tag) as! String
documentsUrl = documentsUrl.appendingPathComponent(fileName)
print(documentsUrl)
do
{
try FileManager.default.removeItem(atPath: "\(documentsUrl)")
arrFilesList.removeObject(at: sender.tag)
tblList.reloadData()
}
catch let error as NSError {
print(error.debugDescription)
}
// var error: NSErrorPointer = nil
// var documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// var tempDirPath = documentsUrl.appendingPathComponent("Inbox")
//
// do
// {
// var directoryContents: NSArray = try FileManager.default.contentsOfDirectory(atPath: "\(tempDirPath)") as NSArray
//
// if error == nil {
// for path in directoryContents {
// let fullPath = documentsUrl.appendingPathComponent(path as! String)
// try FileManager.default.removeItem(atPath: "\(fullPath)")
// }
// }else{
//
// print("seomthing went worng \(error)")
// }
// }
// catch let error as NSError {
// print(error.debugDescription)
// }
}
//MARK:- API Methods -
//Apexa
func getFilesList() {
if AppUtilities.isConnectedToNetwork() {
AppUtilities.sharedInstance.showLoader()
let str = NSString(format: "method=getfiles&userid=\(strUserId)" as NSString)
AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in
DispatchQueue.main.async( execute: {
AppUtilities.sharedInstance.hideLoader()
if success
{
print("object ",object!)
if(object?.value(forKeyPath: "error") as! String == "0")
{
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString)
}
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
print(msg)
}
})
})
}
else
{
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!")
}
}
func deleteFile(fileID:String) {
if AppUtilities.isConnectedToNetwork() {
AppUtilities.sharedInstance.showLoader()
let str = NSString(format: "method=deletefiles&userid=\(strUserId)&fileid=\(fileID)" as NSString)
AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in
DispatchQueue.main.async( execute: {
AppUtilities.sharedInstance.hideLoader()
if success
{
print("object ",object!)
if(object?.value(forKeyPath: "error") as! String == "0")
{
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString)
}
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
print(msg)
}
})
})
}
else
{
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!")
}
}
func getMyFiles() {
arrFilesList = []
var documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
documentsUrl = documentsUrl.appendingPathComponent("Inbox")
print(documentsUrl)
let files = FileManager.default.enumerator(at: documentsUrl, includingPropertiesForKeys: nil)
while let file = files?.nextObject() {
let fileName = URL(fileURLWithPath: "\(file)").lastPathComponent
print("fileName:", fileName)
arrFilesList.add(fileName)
}
tblList.reloadData()
}
// MARK: - Other Methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 21e966a110d066ebc177af8c1b2013db | 34.706897 | 135 | 0.552632 | 5.471598 | false | false | false | false |
mityung/XERUNG | IOS/Xerung/Xerung/ShowProfileViewController.swift | 1 | 24731 | //
// ShowProfileViewController.swift
// Xerung
//
// Created by Mac on 06/04/17.
// Copyright © 2017 mityung. All rights reserved.
//
import UIKit
class ShowProfileViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate , UITextFieldDelegate , DropDownViewControllerDelegate , UIPopoverPresentationControllerDelegate {
@IBOutlet var userImage: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var emailLabel: UILabel!
@IBOutlet var numberLabel: UILabel!
@IBOutlet var view1: UIView!
@IBOutlet var alternateText: UITextField!
@IBOutlet var bloodGroupText: UITextField!
@IBOutlet var companyText: UITextField!
@IBOutlet var professionText: UITextField!
@IBOutlet var cityText: UITextField!
@IBOutlet var addressText: UITextField!
@IBOutlet var view2: UIView!
@IBOutlet var alternateView: UIView!
@IBOutlet var bloodView: UIView!
@IBOutlet var companyView: UIView!
@IBOutlet var professionView: UIView!
@IBOutlet var addressView: UIView!
@IBOutlet var cityView: UIView!
@IBOutlet var submitButton: UIButton!
var cityId = [String]()
var cityName = [String]()
var keyboardHeight:CGFloat!
var countryName = [String]()
var countryCode = [String]()
var countryPhoneCode = [String]()
let numberToolbar:UIToolbar = UIToolbar()
var imagePicker = UIImagePickerController()
var tmpTextField:UITextField!
var base64Image:String!
@IBOutlet var countryLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Profile"
base64Image = profileJson["PHOTO"].stringValue
self.tabBarController?.tabBar.isHidden = true
self.fetchProfile()
self.getOffLineData()
self.getOffLineData1()
view1.dropShadow()
view2.dropShadow()
self.fillData()
alternateText.delegate = self
bloodGroupText.delegate = self
companyText.delegate = self
professionText.delegate = self
cityText.delegate = self
addressText.delegate = self
alternateText.autocapitalizationType = .sentences
bloodGroupText.autocapitalizationType = .sentences
companyText.autocapitalizationType = .sentences
professionText.autocapitalizationType = .sentences
cityText.autocapitalizationType = .sentences
addressText.autocapitalizationType = .sentences
alternateText.tag = 1
bloodGroupText.tag = 2
companyText.tag = 3
professionText.tag = 4
cityText.tag = 5
addressText.tag = 6
numberToolbar.items=[
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.Apply))
]
numberToolbar.sizeToFit()
/*submitButton.layer.cornerRadius = 5
submitButton.layer.borderWidth = 1
submitButton.layer.borderColor = themeColor.cgColor
submitButton.addTarget(self, action: #selector(self.SaveData(_:)), for: UIControlEvents.touchUpInside)*/
let dropdown = UIImageView(image: UIImage(named: "drop"))
dropdown.frame = CGRect(x: 0.0, y: 0.0, width: dropdown.image!.size.width+10.0, height: dropdown.image!.size.height);
dropdown.contentMode = UIViewContentMode.center
bloodGroupText.rightView = dropdown;
bloodGroupText.rightViewMode = UITextFieldViewMode.always
let dropdown1 = UIImageView(image: UIImage(named: "drop"))
dropdown1.frame = CGRect(x: 0.0, y: 0.0, width: dropdown1.image!.size.width+10.0, height: dropdown1.image!.size.height);
dropdown1.contentMode = UIViewContentMode.center
cityText.rightView = dropdown1
cityText.rightViewMode = UITextFieldViewMode.always
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.SaveData(_:)))
/*let backgroundImage = UIImageView(frame: self.view.bounds)
backgroundImage.image = UIImage(named: "backScreen.png")
self.view.insertSubview(backgroundImage, at: 0)*/
// let image = UIImage(named: "backScreen.png")!
// self.view.backgroundColor = UIColor(patternImage: image )
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ "
if textField.tag == 1 {
allowedCharacter = "0123456789"
}else if textField.tag == 2 {
allowedCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
}else if textField.tag == 3 {
allowedCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
}else if textField.tag == 4 {
allowedCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
}else if textField.tag == 5 {
allowedCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
}else if textField.tag == 6 {
allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .-"
}else {
allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ "
}
let aSet = CharacterSet(charactersIn:allowedCharacter).inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
if string == numberFiltered{
let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let numberOfChars = newText.characters.count
if textField.tag == 1 {
return numberOfChars < 13
}else if textField.tag == 2 {
return numberOfChars < 4
}else if textField.tag == 3 {
return numberOfChars < 35
}else if textField.tag == 4 {
return numberOfChars < 35
}else if textField.tag == 5 {
return numberOfChars < 31
}else if textField.tag == 6 {
return numberOfChars < 35
}else {
return numberOfChars < 51
}
}else{
return string == numberFiltered
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.tag == 1 {
alternateView.backgroundColor = themeColor
}else if textField.tag == 2 {
bloodGroupText.backgroundColor = themeColor
}else if textField.tag == 3 {
companyView.backgroundColor = themeColor
}else if textField.tag == 4 {
professionView.backgroundColor = themeColor
}else if textField.tag == 5 {
cityView.backgroundColor = themeColor
}else if textField.tag == 6 {
addressView.backgroundColor = themeColor
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 1 {
alternateView.backgroundColor = UIColor.lightGray
}else if textField.tag == 2 {
bloodGroupText.backgroundColor = UIColor.lightGray
}else if textField.tag == 3 {
companyView.backgroundColor = UIColor.lightGray
}else if textField.tag == 4 {
professionView.backgroundColor = UIColor.lightGray
}else if textField.tag == 5 {
cityView.backgroundColor = UIColor.lightGray
}else if textField.tag == 6 {
addressView.backgroundColor = UIColor.lightGray
}
}
func fillData(){
alternateText.keyboardType = .numberPad
alternateText.inputAccessoryView = numberToolbar
nameLabel.text = self.showData(profileJson["NAME"].stringValue)
numberLabel.text = profileJson["PHONENUMBER"].stringValue
emailLabel.text = self.showData(profileJson["EMAIL"].stringValue)
alternateText.text = self.showData(profileJson["ALTERNATENO"].stringValue)
addressText.text = self.showData(profileJson["ADDRESS"].stringValue)
bloodGroupText.text = self.showData(profileJson["BLOODGROUP"].stringValue)
if self.cityId.count != 0 {
if profileJson["CITYID"].stringValue == "0" || profileJson["CITYID"].stringValue == "" {
}else{
let temp = cityId.index(of: profileJson["CITYID"].stringValue)
cityText.text = self.cityName[temp!]
}
}
countryLabel.text = CountryName
companyText.text = self.showData(profileJson["COMPANYNAME"].stringValue)
professionText.text = self.showData(profileJson["PROFESSION"].stringValue)
if profileJson["PHOTO"].stringValue != "" && profileJson["PHOTO"].stringValue != "0" {
if let imageData = Data(base64Encoded: profileJson["PHOTO"].stringValue , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
let DecodedImage = UIImage(data: imageData)
userImage.image = DecodedImage
}
}else{
userImage.image = UIImage(named: "user.png")
}
}
func Apply () {
self.view.endEditing(true)
}
func fetchCityName() {
let sendJson: [String: String] = [
"PCOUNTRYID": CountryCode
]
if Reachability.isConnectedToNetwork() {
DataProvider.sharedInstance.getServerData2(sendJson, path: "fetchCity", successBlock: { (response) in
print(response)
for i in 0 ..< response.count{
self.cityId.append(response[i]["CITYID"].stringValue)
self.cityName.append(response[i]["CITYNAME"].stringValue)
}
self.saveDataOffLine()
}) { (error) in
print(error)
}
}else{
showAlert("Alert", message: "No internet connectivity.")
}
}
func fetchProfile() {
let sendJson: [String: String] = [
"PUID":userID
]
if Reachability.isConnectedToNetwork() {
DataProvider.sharedInstance.getServerData(sendJson, path: "fetchProfile", successBlock: { (response) in
print(response)
profileJson = response
UserDefaults.standard.set(String(describing: profileJson), forKey: "profileJson")
UserDefaults.standard.synchronize()
DispatchQueue.main.async(execute: {
self.fillData()
})
}) { (error) in
print(error)
}
}else{
showAlert("Alert", message: "No internet connectivity.")
}
}
func showData(_ str:String) -> String {
if str == "0"{
return ""
}else{
return str
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func UploadPhoto(_ sender: AnyObject) {
let refreshAlert = UIAlertController(title: "Picture", message: title, preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Library", style: .default, handler: { (action: UIAlertAction!) in
self.openLibrary()
}))
refreshAlert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction!) in
self.openCamera()
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController!, didFinishPickingImage image1: UIImage!, editingInfo: NSDictionary!){
self.dismiss(animated: true, completion: { () -> Void in
})
let image2 = self.resizeImage(image1, targetSize: CGSize(width: 300.0, height: 300.0))
let imageData = UIImageJPEGRepresentation(image2, 0.5)
base64Image = imageData!.base64EncodedString(options: [])
userImage.image = image1
self.savePhoto()
}
// take phota using camera
func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
// take photo from library
func openLibrary() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
// this method is used to resize the image
func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
@IBAction func SaveData(_ sender: AnyObject) {
self.Apply()
if (alternateText.text?.trim().characters.count)! < 10 {
self.showAlert("Alert", message: "Please update valid alternate mobile number.")
return
}
var city = "0"
if cityText.text?.characters.count == 0 {
city = "0"
}else{
let temp = cityName.index(of: cityText.text!)
city = cityId[temp!]
}
if Reachability.isConnectedToNetwork() {
let sendJson: [String: String] = [
"PPHONENUMBER":getMobileNumber(),
"PEMAIL":emailLabel.text!,
"PNAME":nameLabel.text!,
"PADDRESS":addressText.text!,
"PCITYID": city,
"PSTATEID":"0",
"PCOUNTRYCODEID":CountryPhoneCode + "#" + bloodGroupText.text!,
"PCOUNTRYNAME":companyText.text!,
"POTPID":"0",
"PSTATUSID":"0",
"PPROFESSION": getProfessionDetail(),
"PLOGINFLAG":"1"
]
print(sendJson)
startLoader(view: self.view)
DataProvider.sharedInstance.getServerData2(sendJson, path: "RegLogin", successBlock: { (response) in
print(response["STATUS"])
if response["STATUS"].intValue == 1 {
self.showAlert("Confirmation", message: "Profile updated successfully.")
}
stopLoader()
}) { (error) in
stopLoader()
}
}else{
showAlert("Alert", message: "No internet connectivity.")
}
}
func savePhoto() {
if Reachability.isConnectedToNetwork() {
let sendJson: [String: String] = [
"PPHONENUMBER":mobileNo,
"PPHOTO":base64Image,
"PFLAG":"1"
]
print(sendJson)
DataProvider.sharedInstance.getServerData2(sendJson, path: "updatePhotoandAccess", successBlock: { (response) in
print(response)
if response["STATUS"].intValue == 1 {
profileJson["PHOTO"].stringValue = self.base64Image
self.showAlert("Confirmation", message: "Profile Edited Successfully.")
}
}) { (error) in
}
}else{
showAlert("Alert", message: "No internet connectivity.")
}
}
func getMobileNumber() -> String{
var mob:String = "";
if alternateText.text?.trim().characters.count == 0{
mob = "\((mobileNo.trim()))#0";
}else{
mob = "\((mobileNo.trim()))#\((alternateText.text?.trim())!)";
}
return mob;
}
func getProfessionDetail() -> String{
let prof = professionText.text?.trim();
let comp = companyText.text?.trim();
if(prof?.characters.count == 0 && comp?.characters.count == 0){
return "0"+"#"+"0";
}else if(prof?.characters.count == 0 && comp?.characters.count != 0){
return "\((comp)!)#0";
}else if(prof?.characters.count != 0 && comp?.characters.count == 0){
return "0#\((prof)!)";
}else{
return "\((comp)!)#\((prof)!)";
}
}
func showAlert(_ title:String,message:String){
let refreshAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in
if title == "Confirmation" {
self.navigationController?.popToRootViewController(animated: true)
}
}))
present(refreshAlert, animated: true, completion: nil)
}
// when click on textfield show the popup for select the subject
func dropDown(_ textField:UITextField ) {
let selector = ["A+","A-","B+","B-","AB+","AB-","O+","O-"]
let popoverContent = (self.storyboard?.instantiateViewController(withIdentifier: "DropDownViewController"))! as! DropDownViewController
popoverContent.delegate = self
if textField.tag == 2 {
popoverContent.data = selector
}else{
popoverContent.data = cityName
}
let nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.popover
let popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSize(width: 300,height: 265)
popover!.permittedArrowDirections = .any
popover!.delegate = self
popover!.sourceView = textField
popover!.sourceRect = CGRect(x: textField.frame.width/3, y: 20, width: 0, height: 0)
self.present(nav, animated: true, completion: nil)
tmpTextField = textField
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle{
return UIModalPresentationStyle.none
}
func saveString(_ strText: NSString) {
tmpTextField.text = strText as String
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField.tag == 5{
self.dropDown(textField)
return false
}else if textField.tag == 2{
self.dropDown(textField)
return false
} else{
return true
}
}
func getOffLineData1(){
let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")!
let contactDB = FMDatabase(path: String(describing: databasePath))
if (contactDB?.open())! {
let querySQL = "SELECT * FROM Country "
let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil)
self.countryName = []
self.countryCode = []
self.countryPhoneCode = []
while((results?.next()) == true){
self.countryName.append(results!.string(forColumn: "countryName")!)
self.countryCode.append(results!.string(forColumn: "countryCodeId")!)
self.countryPhoneCode.append(results!.string(forColumn: "phoneCountryCode")!)
}
contactDB?.close()
} else {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
func getOffLineData(){
let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")!
let contactDB = FMDatabase(path: String(describing: databasePath))
if (contactDB?.open())! {
let querySQL = "SELECT * FROM City "
let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil)
while((results?.next()) == true){
self.cityId.append(results!.string(forColumn: "cityId")!)
self.cityName.append(results!.string(forColumn: "cityName")!)
}
if cityId.count == 0 {
self.fetchCityName()
}
/* if self.cityId.count != 0 {
if profileJson["CITYID"].stringValue == "0" {
}else{
let temp = cityId.indexOf(profileJson["CITYID"].stringValue)
self.cityText.text = self.cityName[temp!]
}
}*/
contactDB?.close()
} else {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
// save data into sqlite
func saveDataOffLine(){
let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")!
let contactDB = FMDatabase(path: String(describing: databasePath))
if (contactDB?.open())! {
let querySQL = "DELETE FROM City "
_ = contactDB!.executeUpdate(querySQL, withArgumentsIn: nil)
for i in 0 ..< cityId.count {
let insertSQL = "INSERT INTO City (cityId,cityName) VALUES ('\(cityId[i])', '\(cityName[i])')"
let result = contactDB?.executeUpdate(insertSQL , withArgumentsIn: nil)
if !result! {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
} else {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
/*
// 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.
}
*/
}
| apache-2.0 | 3b0664fdfa60c2f2d6a9d80f72465a4b | 35.207906 | 212 | 0.576668 | 5.298907 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/ErrorHUDMiddleware.swift | 1 | 3253 | //
// ErrorHUDMiddleware.swift
// AmandasRecipes
//
// Created by Parker Rushton on 5/10/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import Whisper
struct DisplayNetworkLossMessage: Event { }
struct DisplayLoadingMessage: Event {
var message: String?
}
struct DisplayNavBarMessage: Event {
var nav: UINavigationController
var message: String
var barColor: UIColor = .blue // FIXME:
var time: TimeInterval?
}
struct DisplayMessage: Event {
var message: String
}
struct DisplayUploadMessage: Event { }
struct ErrorEvent: Event {
var error: Error?
var message: String?
}
struct DisplayHugeErrorMessage: Event {
var message: String
}
struct DisplaySuccessMessage: Event {
var message: String
}
struct HideAlerts: Event { }
struct ErrorHUDMiddleware: Middleware {
func process(event: Event, state: AppState) {
switch event {
case let event as ErrorEvent:
print("ERROR:\(String(describing: event.error)) WITH MESSAGE: \(String(describing: event.message))")
guard let message = event.message else { break }
silva(title: message, barColor: state.theme.tintColor)
case let event as DisplayLoadingMessage:
silva(title: event.message ?? "loading...", displayTime: 0)
case let action as DisplayMessage:
silva(title: action.message)
case let action as DisplaySuccessMessage:
silva(title: action.message, barColor: state.theme.tintColor)
case _ as DisplayNetworkLossMessage:
silva(title: "Looking for the internet...", barColor: UIColor.red.withAlphaComponent(0.6), displayTime: 0)
case _ as DisplayUploadMessage:
silva(title: "Uploading...", barColor: UIColor.lightGray.withAlphaComponent(0.75), displayTime: 0)
case let event as DisplayNavBarMessage:
whisper(with: event.message, barColor: event.barColor, displayTime: event.time, nav: event.nav)
case _ as HideAlerts:
hide()
default:
break
}
}
private func silva(title: String = "loading...", barColor: UIColor = UIColor.blue.withAlphaComponent(0.75), displayTime: TimeInterval? = nil) {
let murmur = Murmur(title: title, backgroundColor: barColor, titleColor: .white, font: App.core.state.theme.font(withSize: 14))
let time = displayTime == nil ? title.displayTime : displayTime!
let action = time == 0 ? WhistleAction.present : WhistleAction.show(time)
show(whistle: murmur, action: action)
}
private func whisper(with title: String, barColor: UIColor, displayTime: TimeInterval? = nil, nav: UINavigationController) {
let message = Message(title: title, textColor: .white, backgroundColor: barColor, images: nil)
let action = displayTime == nil ? WhisperAction.present : WhisperAction.show
show(whisper: message, to: nav, action: action)
}
}
extension String {
var displayTime: TimeInterval {
var timeToDisplay = 1.0
let characterCount = self.count
timeToDisplay += Double(characterCount) * 0.06 as TimeInterval
return timeToDisplay
}
}
| mit | 16aaf8f811b3164cbb95d66fad3bb788 | 31.19802 | 147 | 0.660517 | 4.382749 | false | false | false | false |
ruchee/vimrc | vimfiles/bundle/vim-swift/example/URL.swift | 11 | 243 | import UIKit
class Foo: FooViewController, BarScrollable {
var canScroll = false
override func viewDidLoad() {
baseURL = "http://www.oaklandpostonline.com/search/?q=&t=article&c[]=blogs*"
super.viewDidLoad()
}
}
| mit | 0ffb432221137f81a1f6bdc5697936e6 | 21.090909 | 84 | 0.658436 | 3.857143 | false | false | false | false |
orta/SignalKit | SignalKitTests/Extensions/UIKit/UISlider+SignalTests.swift | 1 | 1461 | //
// UISlider+SignalTests.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/16/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import XCTest
class UISlider_SignalTests: XCTestCase {
var slider: MockSlider!
var signalsBag: SignalBag!
override func setUp() {
super.setUp()
signalsBag = SignalBag()
slider = MockSlider()
slider.maximumValue = 20
}
func testObserveValueChanges() {
var result: Float = 0
slider.observe().valueChanges
.next { result = $0 }
.addTo(signalsBag)
slider.value = 10
slider.sendActionsForControlEvents(.ValueChanged)
XCTAssertEqual(result, 10, "Should observe for value changes in UISlider")
}
func testObserveCurrentValue() {
var result: Float = 0
slider.value = 10
slider.observe().valueChanges
.next { result = $0 }
.addTo(signalsBag)
XCTAssertEqual(result, 10, "Should dispatch the current value from UISlider")
}
func testBindToValue() {
let signal = MockSignal<Float>()
signal.dispatch(5)
signal.bindTo(valueIn: slider).addTo(signalsBag)
XCTAssertEqual(slider.value, 5, "Should bind a Float value to the value property of UISlider")
}
}
| mit | ef5f88739e4b5354e756aace22745b67 | 22.934426 | 102 | 0.566438 | 4.915825 | false | true | false | false |
gustavoavena/MOPT | MOPT/TopicServices.swift | 1 | 7639 | //
// TopicServices.swift
// MOPT
//
// Created by Gustavo Avena on 31/03/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import Foundation
/*
class TopicServices: NSObject, TopicDelegate {
let ckHandler: CloudKitHandler
override init() {
ckHandler = CloudKitHandler()
}
func createTopic(title: String, description: String, meetingRecordID: CKRecordID, creatorRecordID:CKRecordID) {
// Default topicID string is: "[title]:[meetingID]"
let recordID = CKRecordID(recordName: String(format: "%@:%@:%@", title, meetingRecordID.recordName, creatorRecordID.recordName))
let topicRecord = CKRecord(recordType: "Topic", recordID: recordID)
print("Creating topic \(title) in meeting = \(meetingRecordID.recordName)")
let meetingReference = CKReference(recordID: meetingRecordID, action: .deleteSelf)
let creatorReference = CKReference(recordID: creatorRecordID, action: .deleteSelf)
topicRecord["title"] = title as NSString
topicRecord["description"] = description as NSString
topicRecord["meeting"] = meetingReference
topicRecord["creator"] = creatorReference
ckHandler.saveRecord(record: topicRecord)
}
//TODO: test, insert in protocol
func removeTopic(meetingRecordID: CKRecordID, topicRecordID: CKRecordID) {
ckHandler.fetchByRecordID(recordID: meetingRecordID) {
(recordResponse, error) in
guard error == nil && recordResponse != nil else {
print("Error fetching meeting")
return
}
let record = recordResponse!
var topics: [CKReference] = record["topic"] as! [CKReference]
let topicReference = CKReference(recordID: topicRecordID, action: .none)
//remover CKReference (participantReference) da NSArray (participants)
let index = topics.index(of: topicReference)
//index! (force unwrap): posso garantir que index nao sera nil, pois para um topico ser removido ele deve existir na tela do usuario (nao existe possibilidade de tentar remover um topico que nao existe) -- TODO: comentar em ingles
topics.remove(at: index!)
record["participants"] = topics as NSArray
print("topic \(topicRecordID.recordName) removed from meeting \(meetingRecordID.recordName).")
self.ckHandler.saveRecord(record: record)
}
}
func getMeetingTopics(meetingRecordID: CKRecordID, completionHandler: @escaping ([CKRecord], Error?)->Void) {
let meetingReference = CKReference(recordID: meetingRecordID, action: .deleteSelf)
let predicate = NSPredicate(format: "meeting = %@", meetingReference)
let query = CKQuery(recordType: "Topic", predicate: predicate)
self.ckHandler.publicDB.perform(query, inZoneWith: nil) {
(responseData, error) in
guard error == nil && responseData != nil else {
print("problem getting topics from meeting")
completionHandler([CKRecord](), error)
return
}
if let records = responseData {
completionHandler(records, nil)
} else {
completionHandler([CKRecord](), nil)
}
}
}
func getSubtopics(topicRecordID: CKRecordID, completionHandler: @escaping ([CKRecord], Error?)-> Void) {
let topicReference = CKReference(recordID: topicRecordID, action: .deleteSelf)
let predicate = NSPredicate(format: "parentTopic = %@", topicReference)
let query = CKQuery(recordType: "Subtopic", predicate: predicate)
self.ckHandler.publicDB.perform(query, inZoneWith: nil) {
(responseData, error) in
guard error == nil && responseData != nil else {
print("problem getting subtopics from meeting")
completionHandler([CKRecord](), error)
return
}
if let records = responseData {
completionHandler(records, nil)
} else {
completionHandler([CKRecord](), nil)
}
}
}
func getTopicComments(topicRecordID: CKRecordID, completionHandler: @escaping ([CKRecord], Error?) -> Void) {
let topicReference = CKReference(recordID: topicRecordID, action: .deleteSelf)
let predicate = NSPredicate(format: "topic = %@", topicReference)
let query = CKQuery(recordType: "Comment", predicate: predicate)
self.ckHandler.publicDB.perform(query, inZoneWith: nil) {
(responseData, error) in
guard error == nil && responseData != nil else {
print("Problem getting topics from meeting")
completionHandler([CKRecord](), error)
return
}
if let records = responseData {
completionHandler(records, nil)
} else {
completionHandler([CKRecord](), error)
}
}
}
func addComment(topicRecordID: CKRecordID, commentText: String, creatorRecordID: CKRecordID) {
let topicReference = CKReference(recordID: topicRecordID, action: .deleteSelf)
let creatorReference = CKReference(recordID: creatorRecordID, action: .deleteSelf)
let createdAt = NSDate()
let commentIDString = String(format: "%@:%@:%@", topicRecordID.recordName, createdAt.description, creatorRecordID.recordName)
let commentRecordID = CKRecordID(recordName: commentIDString)
let record = CKRecord(recordType: "Comment", recordID: commentRecordID)
record["createdAt"] = createdAt
record["text"] = commentText as NSString
record["topic"] = topicReference
record["creator"] = creatorReference
self.ckHandler.saveRecord(record: record)
}
func addTopicConclusion(topicRecordID: CKRecordID, conclusion: String) {
ckHandler.fetchByRecordID(recordID: topicRecordID) {
(response, error) in
guard error == nil else {
print("error fetching topic to add conclusion.")
return
}
if let topic = response {
topic["conclusion"] = conclusion as NSString
self.ckHandler.saveRecord(record: topic)
} else {
print("Couldn't save the conclusion.")
}
}
}
}
*/
extension Topic: TopicDelegate {
static func create(title: String, meeting meetingID: ObjectID, creator creatorID: ObjectID, subject subjectID: ObjectID?, info: String?) -> Topic {
let ID: String = String(format: "%@:%@:%@", title, meetingID, creatorID)
let topic = Topic(ID: ID, title: title, creator: creatorID, meeting: meetingID, subject: subjectID, info: info, date: Date())
Cache.set(inCache: .topic, withID: ID, object: topic) // Adds it to the Cache
CloudKitMapper.createRecord(fromTopic: topic) // Saves it to the DB
return topic
}
func add(comment ID: ObjectID) {
commentIDs.append(ID)
CloudKitMapper.add(comment: ID, object: self)
}
}
| mit | 2f506b1aa8e1151d86652db5fb3cff64 | 33.098214 | 242 | 0.592302 | 5.11245 | false | false | false | false |
Glenmax-ltd/GLXSegmentedControl | GLXSegmentedControl/GLXSegmentAppearance.swift | 1 | 3286 | //
// GLXSegmentAppearance.swift
// GLXSegmentedControl
//
// Created by Si MA on 11/07/2016.
// Copyright © 2016 si.ma and Glenmax Ltd. All rights reserved.
//
import UIKit
open class GLXSegmentAppearance {
// PROPERTIES
open var segmentOnSelectionColor: UIColor
open var segmentOffSelectionColor: UIColor
open var segmentTouchDownColor: UIColor {
get {
var onSelectionHue: CGFloat = 0.0
var onSelectionSaturation: CGFloat = 0.0
var onSelectionBrightness: CGFloat = 0.0
var onSelectionAlpha: CGFloat = 0.0
self.segmentOnSelectionColor.getHue(&onSelectionHue, saturation: &onSelectionSaturation, brightness: &onSelectionBrightness, alpha: &onSelectionAlpha)
var offSelectionHue: CGFloat = 0.0
var offSelectionSaturation: CGFloat = 0.0
var offSelectionBrightness: CGFloat = 0.0
var offSelectionAlpha: CGFloat = 0.0
self.segmentOffSelectionColor.getHue(&offSelectionHue, saturation: &offSelectionSaturation, brightness: &offSelectionBrightness, alpha: &offSelectionAlpha)
return UIColor(hue: onSelectionHue, saturation: (onSelectionSaturation + offSelectionSaturation)/2.0, brightness: (onSelectionBrightness + offSelectionBrightness)/2.0, alpha: (onSelectionAlpha + offSelectionAlpha)/2.0)
}
}
open var titleOnSelectionColor: UIColor
open var titleOffSelectionColor: UIColor
open var titleOnSelectionFont: UIFont
open var titleOffSelectionFont: UIFont
open var contentVerticalMargin: CGFloat
open var contentHorizontalMargin: CGFloat
open var dividerWidth: CGFloat
open var dividerColor: UIColor
// Mark: INITIALISER
public init() {
self.segmentOnSelectionColor = UIColor.darkGray
self.segmentOffSelectionColor = UIColor.gray
self.titleOnSelectionColor = UIColor.white
self.titleOffSelectionColor = UIColor.darkGray
self.titleOnSelectionFont = UIFont.systemFont(ofSize: 17.0)
self.titleOffSelectionFont = UIFont.systemFont(ofSize: 17.0)
self.contentVerticalMargin = 5.0
self.contentHorizontalMargin = 4.0
self.dividerWidth = 1.0
self.dividerColor = UIColor.lightGray
}
public init(contentVerticalMargin: CGFloat, contentHorizontalMargin:CGFloat, segmentOnSelectionColor: UIColor, segmentOffSelectionColor: UIColor, titleOnSelectionColor: UIColor, titleOffSelectionColor: UIColor, titleOnSelectionFont: UIFont, titleOffSelectionFont: UIFont, dividerWidth:CGFloat) {
self.contentVerticalMargin = contentVerticalMargin
self.contentHorizontalMargin = contentHorizontalMargin
self.segmentOnSelectionColor = segmentOnSelectionColor
self.segmentOffSelectionColor = segmentOffSelectionColor
self.titleOnSelectionColor = titleOnSelectionColor
self.titleOffSelectionColor = titleOffSelectionColor
self.titleOnSelectionFont = titleOnSelectionFont
self.titleOffSelectionFont = titleOffSelectionFont
self.dividerWidth = dividerWidth
self.dividerColor = UIColor.lightGray
}
}
| mit | 4b5567110ad6d100683f81adcb7e7d5d | 39.555556 | 299 | 0.705327 | 5.148903 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/PokeMaster/PokeMaster/Utils/Helpers.swift | 1 | 1324 | //
// Helpers.swift
// PokeMaster
//
// Created by Wang Wei on 2019/08/20.
// Copyright © 2019 OneV's Den. All rights reserved.
//
import Foundation
import SwiftUI
extension Color {
init(hex: Int, alpha: Double = 1) {
let components = (
R: Double((hex >> 16) & 0xff) / 255,
G: Double((hex >> 08) & 0xff) / 255,
B: Double((hex >> 00) & 0xff) / 255
)
self.init(
.sRGB,
red: components.R,
green: components.G,
blue: components.B,
opacity: alpha
)
}
}
extension URL {
var extractedID: Int? {
Int(lastPathComponent)
}
}
extension String {
var newlineRemoved: String {
return split(separator: "\n").joined(separator: " ")
}
var isValidEmailAddress: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: self)
}
}
let appDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
let appEncoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}()
| mit | fb89f845f88855ea51a5c54c1d7024e0 | 21.810345 | 76 | 0.57294 | 3.879765 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Me-我/View/XMGMeCell.swift | 1 | 2074 | //
// XMGMeCell.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/3.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGMeCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
let imageView:UIImageView = UIImageView(image: UIImage(named: "mainCellBackground"))
self.backgroundView = imageView;
self.textLabel!.textColor = UIColor.darkGrayColor()
self.textLabel!.font = UIFont.systemFontOfSize(16)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
if (self.imageView!.image == nil) {return}
self.imageView!.width = 30;
self.imageView!.height = self.imageView!.width;
self.imageView!.centerY = self.contentView.height * 0.5;
self.textLabel!.x = CGRectGetMaxX(self.imageView!.frame) + XMGTopicCellMargin;
}
//- (void)setFrame:(CGRect)frame
//{
//// XMGLog(@"%@", NSStringFromCGRect(frame));
// frame.origin.y -= (35 - XMGTopicCellMargin);
// [super setFrame:frame];
//}
//MARK: 重写frame来设置cell的内嵌
/*
override var frame:CGRect{
set{
var frame = newValue
frame.origin.x = XMGTopicCellMargin;
frame.size.width -= 2 * XMGTopicCellMargin;
frame.size.height -= XMGTopicCellMargin;
frame.origin.y += XMGTopicCellMargin;
super.frame=frame
}
get{
return super.frame
}
} */
}
| apache-2.0 | c8e9f5b39f05a2c08de128e6976a9b79 | 25.24359 | 92 | 0.627748 | 4.402151 | false | false | false | false |
darkerk/v2ex | V2EX/Cells/TimelineReplyViewCell.swift | 1 | 2217 | //
// TimelineReplyViewCell.swift
// V2EX
//
// Created by darker on 2017/3/15.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
class TimelineReplyViewCell: UITableViewCell {
@IBOutlet weak var titleContentView: UIView!
@IBOutlet weak var topicTitleLabel: UILabel!
@IBOutlet weak var replyContentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var reply: Reply? {
willSet {
if let model = newValue {
timeLabel.text = model.topic?.lastReplyTime
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 3
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: AppStyle.shared.theme.black102Color, NSAttributedString.Key.paragraphStyle: paragraphStyle]
replyContentLabel.attributedText = NSAttributedString(string: model.content, attributes: attributes)
if let title = model.topic?.title {
let titleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13), NSAttributedString.Key.foregroundColor: AppStyle.shared.theme.black102Color, NSAttributedString.Key.paragraphStyle: paragraphStyle]
topicTitleLabel.attributedText = NSAttributedString(string: title, attributes: titleAttributes)
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let selectedView = UIView()
selectedView.backgroundColor = AppStyle.shared.theme.cellSelectedBackgroundColor
self.selectedBackgroundView = selectedView
self.backgroundColor = AppStyle.shared.theme.cellBackgroundColor
timeLabel.textColor = AppStyle.shared.theme.black153Color
titleContentView.backgroundColor = AppStyle.shared.theme.cellSubBackgroundColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 86aa4773e1e282443fba9fd5f667d478 | 37.842105 | 234 | 0.667118 | 5.548872 | false | false | false | false |
rcach/Tasks | TODO/TaskUIHandler.swift | 1 | 1119 | import Foundation
class TaskUIHandler {
var task: Task
init(task: Task) {
self.task = task
}
func markTaskDoing(onComplete: (error: NSError?) -> ()) {
trackEvent("UserActions", "Task", "MarkDoing", "1")
markTaskAsDoing(task) { errorOrNil in
if errorOrNil == nil {
// TODO: This isn't exactly right, task may be 'Testing'.
self.task = Task(task: self.task, status: Status.Development)
}
onComplete(error: errorOrNil) // TODO: On error perhaps re-fetch task from network.
}
}
func markTaskDone(onComplete: (error: NSError?) -> ()) {
trackEvent("UserActions", "Task", "MarkDone", "1")
markTaskAsDone(task) { errorOrNil in
if errorOrNil == nil {
self.task = Task(task: self.task, status: Status.Done)
}
onComplete(error: errorOrNil)
}
}
func logTime(numberOfSeconds: Int, numberOfHoursRemaining: Int, onComplete: (error: NSError?) -> ()) {
trackEvent("UserActions", "Task", "LogTime", "1")
logTimeInSeconds(numberOfSeconds, hoursRemaining: numberOfHoursRemaining, toTask: task, onComplete)
}
} | apache-2.0 | 7a1a5cf2e950fe5381cc21383b905c3f | 30.111111 | 104 | 0.642538 | 3.871972 | false | false | false | false |
zavsby/PHCSSTheme | Classes/Components/PHBorderInfo.swift | 1 | 3241 | //
// PHBorderInfo.swift
// PHCSSTheme
//
// Created by Sergey on 23.11.15.
// Copyright © 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
public enum PHBorderInfoPattern: Int {
/**
* width-color-cornerRadius
*/
case CornerRadius = 3
/**
* top-left-bottom-right-color
*/
case Border = 5
/**
* top-offset-left-offset-bottom-offset-right-offset-color
*/
case BorderWithOffsets = 9
}
public struct PHBorderInfo {
public let borderLeft: PHStyleMeasure
public var borderLeftOffset: PHStyleMeasure?
public let borderRight: PHStyleMeasure
public var borderRightOffset: PHStyleMeasure?
public let borderTop: PHStyleMeasure
public var borderTopOffset: PHStyleMeasure?
public let borderBottom: PHStyleMeasure
public var borderBottomOffset: PHStyleMeasure?
public let borderColorInfo: PHColorInfo
public var cornerRadius: PHStyleMeasure?
private let borderPattern: PHBorderInfoPattern
public init(string: String) throws {
let parts = string.componentsSeparatedByString("-")
switch parts.count {
case PHBorderInfoPattern.CornerRadius.rawValue:
let width = try PHStyleMeasure(valueString: parts[0])
(borderLeft, borderRight, borderTop, borderBottom) = (width, width, width, width)
borderColorInfo = try PHColorConverter.colorInfoFromAnyFormat(parts[1])
cornerRadius = try PHStyleMeasure(valueString: parts[2])
borderPattern = PHBorderInfoPattern.CornerRadius
case PHBorderInfoPattern.Border.rawValue:
borderTop = try PHStyleMeasure(valueString: parts[0])
borderLeft = try PHStyleMeasure(valueString: parts[1])
borderBottom = try PHStyleMeasure(valueString: parts[2])
borderRight = try PHStyleMeasure(valueString: parts[3])
borderColorInfo = try PHColorConverter.colorInfoFromAnyFormat(parts[4])
borderPattern = PHBorderInfoPattern.Border
case PHBorderInfoPattern.BorderWithOffsets.rawValue:
borderTop = try PHStyleMeasure(valueString: parts[0])
borderTopOffset = try PHStyleMeasure(valueString: parts[1])
borderLeft = try PHStyleMeasure(valueString: parts[2])
borderLeftOffset = try PHStyleMeasure(valueString: parts[3])
borderBottom = try PHStyleMeasure(valueString: parts[4])
borderBottomOffset = try PHStyleMeasure(valueString: parts[5])
borderRight = try PHStyleMeasure(valueString: parts[6])
borderRightOffset = try PHStyleMeasure(valueString: parts[7])
borderColorInfo = try PHColorConverter.colorInfoFromAnyFormat(parts[8])
borderPattern = PHBorderInfoPattern.BorderWithOffsets
default:
throw PHCSSParserError.WrongStringBorderFormat(borderString: string)
}
}
}
extension PHBorderInfo: CustomStringConvertible {
public var description: String {
return "Border: \(borderPattern) with color \(borderColorInfo) (\(borderTop),\(borderLeft),\(borderBottom),\(borderRight))"
}
}
| mit | b107c85d2b8b3dd9c266b02bd61f858b | 34.217391 | 131 | 0.672531 | 4.655172 | false | false | false | false |
masters3d/xswift | exercises/scrabble-score/Sources/ScrabbleScoreExample.swift | 1 | 1398 | import Foundation
private extension String {
func containsCustom(_ input: Character) -> Bool {
return contains(String(input))
}
func lowercasedCustom() -> String {
return lowercased()
}
private func stripCharacters(_ charsToRemove: String) -> String {
var returnString = ""
self.characters.forEach {
if !charsToRemove.containsCustom($0) {
returnString.append($0)
}}
return returnString
}
var stripWhiteSpace: String {
return stripCharacters(" ")
}
var isEmptyOrWhiteSpace: Bool {
return self.stripWhiteSpace.isEmpty
}
}
struct Scrabble {
static var letterScores =
[ "a": 1, "e": 1, "i": 1, "o": 1, "u": 1, "l": 1, "n": 1, "r": 1, "s": 1, "t": 1, "d": 2, "g": 2, "b": 3, "c": 3, "m": 3, "p": 3, "f": 4, "h": 4, "v": 4, "w": 4, "y": 4, "k": 5, "j": 8, "x": 8, "q": 10, "z": 10 ]
static func score(_ input: String) -> Int {
if input.isEmptyOrWhiteSpace {
return 0
}
var count: Int = 0
for each in input.lowercasedCustom().characters {
count += letterScores[String(each)] ?? 0
}
return count
}
var word: String = ""
var score: Int = 0
init(_ word: String?) {
self.word = word ?? ""
self.score = Scrabble.score(word ?? "")
}
}
| mit | 0fa2c266c2649696fd89ec93cbc2db45 | 22.694915 | 220 | 0.512876 | 3.612403 | false | false | false | false |
arcontrerasa/SwiftParseRestClient | ParseRestClient/ParseGenericOperation.swift | 1 | 1080 | //
// ParseGenericOperation.swift
// Pods
//
// Created by Armando Contreras on 9/15/15.
//
//
import Foundation
class ParseGenericOperation<T: ParseModelProtocol>: Operation {
let operationWrapper: ParseOperationWrapper<T>
init(operationWrapper: ParseOperationWrapper<T>) {
self.operationWrapper = operationWrapper
}
override func main() {
let request = operationWrapper.parseRequest.createRequest()
operationWrapper.httpHelper.sendRequest(request, completion: {(data:NSData!, error:NSError!) in
// Display error
if let error = error {
if error.code == -999 { return }
} else if let resData = data {
self.operationWrapper.getResponse().parseDictionary(resData)
}
dispatch_async(dispatch_get_main_queue()) {
self.operationWrapper.notifyCompletion()
self.finish()
}
})
}
} | mit | ada0d6fa5abd656664b051c628eff971 | 24.139535 | 103 | 0.550926 | 5.023256 | false | false | false | false |
Incipia/Goalie | Goalie/UnlockedCharacterCollectionViewCell.swift | 1 | 2375 | //
// UnlockedCharacterCollectionViewCell.swift
// Goalie
//
// Created by Gregory Klein on 3/29/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import UIKit
class UnlockedCharacterCollectionViewCell: UICollectionViewCell
{
@IBOutlet fileprivate weak var _characterView: CharacterView!
@IBOutlet fileprivate weak var _nameLabel: GoalieKerningLabel!
@IBOutlet fileprivate weak var _subtitleLabel: UILabel!
@IBOutlet fileprivate weak var _unlockedBadgeView: UnlockedBadgeView!
fileprivate var _movementAnimator: GoalieMovementAnimator!
fileprivate var _character: GoalieCharacter = .unknown
override func awakeFromNib()
{
super.awakeFromNib()
backgroundColor = UIColor.white
layer.borderColor = UIColor(white: 0.9, alpha: 1).cgColor
layer.borderWidth = 1
layer.cornerRadius = 5.0
_characterView.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
_movementAnimator = GoalieMovementAnimator(view: _characterView.containerView)
let delayTime = DispatchTime.now() + Double(Int64(Double(CGFloat.randRange(0, upper: 0.9)) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self._movementAnimator.startScalingAnimation()
}
}
func configureWithCharacter(_ c: GoalieCharacter)
{
_character = c
_characterView.updateCharacter(c)
_characterView.updateWithPriority(.later)
_nameLabel.updateText(c.name.uppercased())
_nameLabel.updateKerningValue(1.5)
_subtitleLabel.text = c.subtitle
if c == CharacterManager.currentCharacter {
updateUIForSelectedState()
_characterView.animateFace()
}
else {
updateUIForDeselectedState()
}
}
func updateUIForDeselectedState()
{
_unlockedBadgeView.selected = false
_nameLabel.updateTextColor(UIColor(rgbValues: (55.0, 76.0, 86.0)))
_subtitleLabel.textColor = UIColor(rgbValues: (87.0, 123.0, 137.0))
backgroundColor = UIColor.white
}
func updateUIForSelectedState()
{
_unlockedBadgeView.selected = true
_nameLabel.updateTextColor(UIColor.white)
_subtitleLabel.textColor = UIColor.white
backgroundColor = UIColor(priority: .later)
}
}
| apache-2.0 | 2f3430c198e56636643186e4cb280826 | 29.435897 | 144 | 0.681971 | 4.547893 | false | false | false | false |
sammyd/LuggageLocator | Luggage Locator/ViewController.swift | 1 | 1703 | //
// ViewController.swift
// Luggage Locator
//
// Created by Sam Davies on 30/08/2014.
// Copyright (c) 2014 VisualPutty. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController {
@IBOutlet weak var rssiLabel: PaddedLabel!
@IBOutlet weak var accuracyLabel: PaddedLabel!
@IBOutlet weak var luggageImageView: UIImageView!
@IBOutlet weak var overlayImageView: FlashingImageView!
var luggageLocationManager: LuggageLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
luggageLocationManager?.startRangingWithCallback({
[unowned self] beacon in
self.updateViewWithBeacon(beacon)
})
}
func updateViewWithBeacon(beacon: CLBeacon) {
rssiLabel.text = "\(beacon.rssi)dBm"
let accuracy = NSString(format: "%0.2f", beacon.accuracy)
accuracyLabel.text = "\(accuracy)m"
switch beacon.proximity {
case .Unknown:
showOverlayImageNamed(nil)
case .Far:
showOverlayImageNamed("overlay_red")
case .Immediate:
showOverlayImageNamed("overlay_green")
case .Near:
showOverlayImageNamed("overlay_yellow")
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// MARK: - Utility Methods
private func showOverlayImageNamed(name: String?) {
if let name = name {
luggageImageView.alpha = 1.0
overlayImageView.hidden = false
overlayImageView.image = UIImage(named: name)
} else {
luggageImageView.alpha = 0.2
overlayImageView.hidden = true
}
}
}
| mit | 77be87fe6f0bf24974a2a29e144340cd | 24.80303 | 76 | 0.6835 | 4.423377 | false | false | false | false |
tjw/swift | test/SILGen/subclass_existentials.swift | 1 | 23976 |
// RUN: %target-swift-frontend -module-name subclass_existentials -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
// RUN: %target-swift-frontend -module-name subclass_existentials -emit-ir -parse-as-library -primary-file %s
// Note: we pass -verify above to ensure there are no spurious
// compiler warnings relating to casts.
protocol Q {}
class Base<T> : Q {
required init(classInit: ()) {}
func classSelfReturn() -> Self {
return self
}
static func classSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol P {
init(protocolInit: ())
func protocolSelfReturn() -> Self
static func protocolSelfReturn() -> Self
}
class Derived : Base<Int>, P {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {
return self
}
static func protocolSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol R {}
// CHECK-LABEL: sil hidden @$S21subclass_existentials11conversions8baseAndP7derived0fE1R0dE5PType0F4Type0fE5RTypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAA1R_ANXcAaI_ALXcXpANmAaO_ANXcXptF : $@convention(thin) (@guaranteed Base<Int> & P, @guaranteed Derived, @guaranteed Derived & R, @thick (Base<Int> & P).Type, @thick Derived.Type, @thick (Derived & R).Type) -> () {
// CHECK: bb0([[ARG0:%.*]] : $Base<Int> & P,
func conversions(
baseAndP: Base<Int> & P,
derived: Derived,
derivedAndR: Derived & R,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type,
derivedAndRType: (Derived & R).Type) {
// Values
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[BASE:%.*]] = upcast [[REF]] : $@opened("{{.*}}") Base<Int> & P to $Base<Int>
// CHECK: destroy_value [[BASE]] : $Base<Int>
let _: Base<Int> = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $P
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*P, $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*P
// CHECK: dealloc_stack [[RESULT]] : $*P
let _: P = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $Q
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*Q, $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*Q
// CHECK: dealloc_stack [[RESULT]] : $*Q
let _: Q = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG2:%.*]] : $Derived & R
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[RESULT:%.*]] = init_existential_ref [[REF]] : $@opened("{{.*}}") Derived & R : $@opened("{{.*}}") Derived & R, $Base<Int> & P
// CHECK: destroy_value [[RESULT]]
let _: Base<Int> & P = derivedAndR
// Metatypes
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = upcast [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type to $@thick Base<Int>.Type
let _: Base<Int>.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type, $@thick P.Type
let _: P.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type, $@thick Q.Type
let _: Q.Type = baseAndPType
// CHECK: [[RESULT:%.*]] = init_existential_metatype %4 : $@thick Derived.Type, $@thick (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %5 : $@thick (Derived & R).Type to $@thick (@opened("{{.*}}") (Derived & R)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Derived & R)).Type, $@thick (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedAndRType
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials11methodCalls8baseAndP0eF5PTypeyAA1P_AA4BaseCySiGXc_AaE_AHXcXptF : $@convention(thin) (@guaranteed Base<Int> & P, @thick (Base<Int> & P).Type) -> () {
func methodCalls(
baseAndP: Base<Int> & P,
baseAndPType: (Base<Int> & P).Type) {
// CHECK: bb0([[ARG0:%.*]] : $Base<Int> & P,
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $Base<Int> & P to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] : $@opened("{{.*}}") Base<Int> & P
// CHECK: [[CLASS_REF:%.*]] = upcast [[REF]] : $@opened("{{.*}}") Base<Int> & P to $Base<Int>
// CHECK: [[METHOD:%.*]] = class_method [[CLASS_REF]] : $Base<Int>, #Base.classSelfReturn!1 : <T> (Base<T>) -> () -> @dynamic_self Base<T>, $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: [[RESULT_CLASS_REF:%.*]] = apply [[METHOD]]<Int>([[CLASS_REF]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: destroy_value [[CLASS_REF]] : $Base<Int>
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_CLASS_REF]] : $Base<Int> to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") Base<Int> & P : $@opened("{{.*}}") Base<Int> & P, $Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $Base<Int> & P
let _: Base<Int> & P = baseAndP.classSelfReturn()
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $Base<Int> & P to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT_BOX:%.*]] = alloc_stack $@opened("{{.*}}") Base<Int> & P
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $@opened("{{.*}}") Base<Int> & P
// CHECK: store_borrow [[PAYLOAD]] to [[SELF_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") Base<Int> & P, #P.protocolSelfReturn!1 : <Self where Self : P> (Self) -> () -> @dynamic_self Self, [[PAYLOAD]] : $@opened("{{.*}}") Base<Int> & P : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: apply [[METHOD]]<@opened("{{.*}}") Base<Int> & P>([[RESULT_BOX]], [[SELF_BOX]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: dealloc_stack [[SELF_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") Base<Int> & P : $@opened("{{.*}}") Base<Int> & P, $Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $Base<Int> & P
// CHECK: dealloc_stack [[RESULT_BOX]] : $*@opened("{{.*}}") Base<Int> & P
let _: Base<Int> & P = baseAndP.protocolSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[METATYPE_REF:%.*]] = upcast [[METATYPE]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type to $@thick Base<Int>.Type
// CHECK: [[METHOD:%.*]] = function_ref @$S21subclass_existentials4BaseC15classSelfReturnACyxGXDyFZ : $@convention(method) <τ_0_0> (@thick Base<τ_0_0>.Type) -> @owned Base<τ_0_0>
// CHECK: [[RESULT_REF2:%.*]] = apply [[METHOD]]<Int>([[METATYPE_REF]])
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_REF2]] : $Base<Int> to $@opened("{{.*}}") (Base<Int> & P)
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") (Base<Int> & P) : $@opened("{{.*}}") (Base<Int> & P), $Base<Int> & P
// CHECK: destroy_value [[RESULT]]
let _: Base<Int> & P = baseAndPType.classSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = alloc_stack $@opened("{{.*}}") (Base<Int> & P)
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") (Base<Int> & P), #P.protocolSelfReturn!1 : <Self where Self : P> (Self.Type) -> () -> @dynamic_self Self, [[METATYPE]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[METHOD]]<@opened("{{.*}}") (Base<Int> & P)>([[RESULT]], [[METATYPE]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT]] : $*@opened("{{.*}}") (Base<Int> & P)
// CHECK: [[RESULT_VALUE:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") (Base<Int> & P) : $@opened("{{.*}}") (Base<Int> & P), $Base<Int> & P
// CHECK: destroy_value [[RESULT_VALUE]]
// CHECK: dealloc_stack [[RESULT]]
let _: Base<Int> & P = baseAndPType.protocolSelfReturn()
// Partial applications
let _: () -> (Base<Int> & P) = baseAndP.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndP.protocolSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.protocolSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.init(classInit:)
let _: () -> (Base<Int> & P) = baseAndPType.init(protocolInit:)
// CHECK: return
// CHECK-NEXT: }
}
protocol PropertyP {
var p: PropertyP & PropertyC { get set }
subscript(key: Int) -> Int { get set }
}
class PropertyC {
var c: PropertyP & PropertyC {
get {
return self as! PropertyP & PropertyC
}
set { }
}
subscript(key: (Int, Int)) -> Int {
get {
return 0
} set { }
}
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials16propertyAccessesyyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@guaranteed PropertyC & PropertyP) -> () {
func propertyAccesses(_ x: PropertyP & PropertyC) {
var xx = x
xx.p.p = x
xx.c.c = x
propertyAccesses(xx.p)
propertyAccesses(xx.c)
_ = xx[1]
xx[1] = 1
xx[1] += 1
_ = xx[(1, 2)]
xx[(1, 2)] = 1
xx[(1, 2)] += 1
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials19functionConversions15returnsBaseAndP0efG5PType0E7Derived0eI4Type0eiG1R0eiG5RTypeyAA1P_AA0F0CySiGXcyc_AaI_ALXcXpycAA0I0CycANmycAA1R_ANXcycAaO_ANXcXpyctF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Base<Int> & P, @guaranteed @callee_guaranteed () -> @thick (Base<Int> & P).Type, @guaranteed @callee_guaranteed () -> @owned Derived, @guaranteed @callee_guaranteed () -> @thick Derived.Type, @guaranteed @callee_guaranteed () -> @owned Derived & R, @guaranteed @callee_guaranteed () -> @thick (Derived & R).Type) -> () {
func functionConversions(
returnsBaseAndP: @escaping () -> (Base<Int> & P),
returnsBaseAndPType: @escaping () -> (Base<Int> & P).Type,
returnsDerived: @escaping () -> Derived,
returnsDerivedType: @escaping () -> Derived.Type,
returnsDerivedAndR: @escaping () -> Derived & R,
returnsDerivedAndRType: @escaping () -> (Derived & R).Type) {
let _: () -> Base<Int> = returnsBaseAndP
let _: () -> Base<Int>.Type = returnsBaseAndPType
let _: () -> P = returnsBaseAndP
let _: () -> P.Type = returnsBaseAndPType
let _: () -> (Base<Int> & P) = returnsDerived
let _: () -> (Base<Int> & P).Type = returnsDerivedType
let _: () -> Base<Int> = returnsDerivedAndR
let _: () -> Base<Int>.Type = returnsDerivedAndRType
let _: () -> (Base<Int> & P) = returnsDerivedAndR
let _: () -> (Base<Int> & P).Type = returnsDerivedAndRType
let _: () -> P = returnsDerivedAndR
let _: () -> P.Type = returnsDerivedAndRType
// CHECK: return %
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials9downcasts8baseAndP7derived0dE5PType0F4TypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAaG_AJXcXpALmtF : $@convention(thin) (@guaranteed Base<Int> & P, @guaranteed Derived, @thick (Base<Int> & P).Type, @thick Derived.Type) -> () {
func downcasts(
baseAndP: Base<Int> & P,
derived: Derived,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type) {
// CHECK: bb0([[ARG0:%.*]] : $Base<Int> & P, [[ARG1:%.*]] : $Derived, [[ARG2:%.*]] : $@thick (Base<Int> & P).Type, [[ARG3:%.*]] : $@thick Derived.Type):
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $Derived
let _ = baseAndP as? Derived
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $Derived
let _ = baseAndP as! Derived
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $Derived & R
let _ = baseAndP as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $Derived & R
let _ = baseAndP as! (Derived & R)
// CHECK: checked_cast_br %3 : $@thick Derived.Type to $@thick (Derived & R).Type
let _ = derivedType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %3 : $@thick Derived.Type to $@thick (Derived & R).Type
let _ = derivedType as! (Derived & R).Type
// CHECK: checked_cast_br %2 : $@thick (Base<Int> & P).Type to $@thick Derived.Type
let _ = baseAndPType as? Derived.Type
// CHECK: unconditional_checked_cast %2 : $@thick (Base<Int> & P).Type to $@thick Derived.Type
let _ = baseAndPType as! Derived.Type
// CHECK: checked_cast_br %2 : $@thick (Base<Int> & P).Type to $@thick (Derived & R).Type
let _ = baseAndPType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %2 : $@thick (Base<Int> & P).Type to $@thick (Derived & R).Type
let _ = baseAndPType as! (Derived & R).Type
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials16archetypeUpcasts9baseTAndP0E7IntAndP7derivedyq__q0_q1_tAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT) -> () {
func archetypeUpcasts<T,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
baseTAndP: BaseTAndP,
baseIntAndP : BaseIntAndP,
derived : DerivedT) {
// CHECK: bb0([[ARG0:%.*]] : $BaseTAndP, [[ARG1:%.*]] : $BaseIntAndP, [[ARG2:%.*]] : $DerivedT)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $BaseTAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseTAndP : $BaseTAndP, $Base<T> & P
let _: Base<T> & P = baseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG1]] : $BaseIntAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseIntAndP : $BaseIntAndP, $Base<Int> & P
let _: Base<Int> & P = baseIntAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG2]] : $DerivedT
// CHECK-NEXT: init_existential_ref [[COPIED]] : $DerivedT : $DerivedT, $Base<Int> & P
let _: Base<Int> & P = derived
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @$S21subclass_existentials18archetypeDowncasts1s1t2pt5baseT0F3Int0f6TAndP_C00fg5AndP_C008derived_C00ji2R_C00fH10P_concrete0fgi2P_K0yx_q_q0_q1_q2_q3_q4_q5_AA1R_AA7DerivedCXcAA1P_AA4BaseCyq_GXcAaQ_ASySiGXctAaQR0_ATRb1_AURb2_ATRb3_AaQR3_AURb4_AaQR4_APRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in_guaranteed S, @in_guaranteed T, @in_guaranteed PT, @guaranteed BaseT, @guaranteed BaseInt, @guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT, @guaranteed Derived & R, @guaranteed Base<T> & P, @guaranteed Base<Int> & P) -> () {
func archetypeDowncasts<S,
T,
PT : P,
BaseT : Base<T>,
BaseInt : Base<Int>,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
s: S,
t: T,
pt: PT,
baseT : BaseT,
baseInt : BaseInt,
baseTAndP_archetype: BaseTAndP,
baseIntAndP_archetype : BaseIntAndP,
derived_archetype : DerivedT,
derivedAndR_archetype : Derived & R,
baseTAndP_concrete: Base<T> & P,
baseIntAndP_concrete: Base<Int> & P) {
// CHECK: ([[ARG0:%.*]] : $*S, [[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $*PT, [[ARG3:%.*]] : $BaseT, [[ARG4:%.*]] : $BaseInt, [[ARG5:%.*]] : $BaseTAndP, [[ARG6:%.*]] : $BaseIntAndP, [[ARG7:%.*]] : $DerivedT, [[ARG8:%.*]] : $Derived & R, [[ARG9:%.*]] : $Base<T> & P, [[ARG10:%.*]] : $Base<Int> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to Base<T> & P in [[RESULT]] : $*Base<T> & P
let _ = s as? (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to Base<T> & P in [[RESULT]] : $*Base<T> & P
let _ = s as! (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to Base<Int> & P in [[RESULT]] : $*Base<Int> & P
let _ = s as? (Base<Int> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to Base<Int> & P in [[RESULT]] : $*Base<Int> & P
let _ = s as! (Base<Int> & P)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseTAndP to $Derived & R
let _ = baseTAndP_archetype as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseTAndP to $Derived & R
let _ = baseTAndP_archetype as! (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always Base<T> & P in [[COPY]] : $*Base<T> & P to S in [[PAYLOAD]] : $*S
let _ = baseTAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr Base<T> & P in [[COPY]] : $*Base<T> & P to S in [[RESULT]] : $*S
let _ = baseTAndP_concrete as! S
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseT
let _ = baseTAndP_concrete as? BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseT
let _ = baseTAndP_concrete as! BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseInt
let _ = baseTAndP_concrete as? BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseInt
let _ = baseTAndP_concrete as! BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseTAndP
let _ = baseTAndP_concrete as? BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseTAndP
let _ = baseTAndP_concrete as! BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseIntAndP to $Derived & R
let _ = baseIntAndP_archetype as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseIntAndP to $Derived & R
let _ = baseIntAndP_archetype as! (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always Base<Int> & P in [[COPY]] : $*Base<Int> & P to S in [[PAYLOAD]] : $*S
let _ = baseIntAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr Base<Int> & P in [[COPY]] : $*Base<Int> & P to S in [[RESULT]] : $*S
let _ = baseIntAndP_concrete as! S
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $DerivedT
let _ = baseIntAndP_concrete as? DerivedT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $DerivedT
let _ = baseIntAndP_concrete as! DerivedT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseT
let _ = baseIntAndP_concrete as? BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseT
let _ = baseIntAndP_concrete as! BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseInt
let _ = baseIntAndP_concrete as? BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseInt
let _ = baseIntAndP_concrete as! BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseTAndP
let _ = baseIntAndP_concrete as? BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseTAndP
let _ = baseIntAndP_concrete as! BaseTAndP
// CHECK: return
// CHECK-NEXT: }
}
| apache-2.0 | 24089576c4d77d983cacb9b9312e2ab1 | 50.06823 | 766 | 0.588284 | 3.098047 | false | false | false | false |
daniel-beard/LocalNotificationActionCategories | LocalNotificationCategories/ViewController.swift | 1 | 1093 | //
// ViewController.swift
// LocalNotificationCategories
//
// Created by Daniel Beard on 4/16/15.
// Copyright (c) 2015 DanielBeard. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func presentNotificationWithDelay(delay: NSTimeInterval, category: String) {
let notification = UILocalNotification()
notification.alertTitle = "Title"
notification.alertBody = "Message body"
notification.category = category
notification.fireDate = NSDate().dateByAddingTimeInterval(delay)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
@IBAction func showDelayedInviteNotification(sender: UIButton) {
self.presentNotificationWithDelay(5, category: "inviteCategory")
}
@IBAction func showDelayedViewNotification(sender: UIButton) {
self.presentNotificationWithDelay(5, category: "viewCategory")
}
}
| mit | 0a6feffef0d0f4aa7c90757819248f88 | 30.228571 | 81 | 0.713632 | 5.013761 | false | false | false | false |
pyanfield/ataturk_olympic | swift_programming_optional_chaining.playground/section-1.swift | 1 | 3577 | // Playground - noun: a place where people can play
import UIKit
// 2.17
// 可选链(Optional Chaining)是一种可以请求和调用属性、方法及下标脚本的过程,它的可选性体现于请求或调用的目标当前可能为空(nil)。
// 如果可选的目标有值,那么调用就会成功;相反,如果选择的目标为空(nil),则这种调用将返回空(nil)。
// 通过在想调用的属性、方法、或下标脚本的可选值(optional value)(非空)后面放一个问号,可以定义一个可选链。这一点很像在可选值后面放一个叹号来强制拆得其封包内的值。
// 为了反映可选链可以调用空(nil),不论你调用的属性、方法、下标脚本等返回的值是不是可选值,它的返回结果都是一个可选值。
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if (buildingName != nil) {
return buildingName
} else if (buildingNumber != nil) {
return buildingNumber
} else {
return nil
}
}
}
class Room {
let name: String
init(name: String) { self.name = name }
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
return rooms[i]
}
// 返回 Void 类型
func printNumberOfRooms() {
println("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
class Person {
var residence: Residence?
}
let john = Person()
// 这里 numberOfRooms 返回的时一个 Int? 类型,而不是 Int
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// 即使这个方法本身没有定义返回值,你也可以使用if语句来检查是否能成功调用printNumberOfRooms方法:
// 如果方法通过可选链调用成功,printNumberOfRooms的隐式返回值将会是Void,如果没有成功,将返回nil
if (john.residence?.printNumberOfRooms() != nil) {
println("It was possible to print the number of rooms.")
} else {
println("It was not possible to print the number of rooms.")
}
if let firstRoomName = john.residence?[0].name {
println("The first room name is \(firstRoomName).")
} else {
println("Unable to retrieve the first room name.")
}
let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "Living Room"))
johnsHouse.rooms.append(Room(name: "Kitchen"))
john.residence = johnsHouse
if let firstRoomName = john.residence?[0].name {
println("The first room name is \(firstRoomName).")
} else {
println("Unable to retrieve the first room name.")
}
let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
// 在 johnsAddress 被赋值之前,需要确定 john.residence 实际值,因为在此之前其是一个可选值
john.residence!.address = johnsAddress
if let johnsStreet = john.residence?.address?.street {
println("John's street name is \(johnsStreet).")
} else {
println("Unable to retrieve the address.")
}
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
println("John's building identifier is \(buildingIdentifier).")
}
if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString {
println("John's uppercase building identifier is \(upper).")
}
| mit | 05250581e9e9476b0391fa00a61f5d84 | 26.457143 | 91 | 0.693722 | 3.403778 | false | false | false | false |
colbylwilliams/bugtrap | iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraIssue.swift | 1 | 608 | //
// JiraIssue.swift
// bugTrap
//
// Created by Colby L Williams on 12/5/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class JiraIssue : JiraSimpleItem {
var fields = JiraIssueFields()
override func serialize () -> NSMutableDictionary {
let dict = NSMutableDictionary()
dict.setObject(fields.serialize(), forKey: "fields")
return dict
}
var valid: Bool {
return fields.project.id != nil && fields.issueType.id != nil && fields.priority.id != nil && !fields.assignee.name.isEmpty && !fields.summary.isEmpty && !fields.description.isEmpty
}
} | mit | 5316c7c9a62244281ff67bfd6d8b9a00 | 20.75 | 183 | 0.685855 | 3.619048 | false | false | false | false |
slashkeys/FacebookAuth | Tests/Base/AskForPermissionsCompletionTests.swift | 1 | 1129 | //
// Created by Moritz Lang on 13.08.17.
// Copyright (c) 2017 Slashkeys. All rights reserved.
//
import XCTest
@testable import FacebookAuth
final class AskForPermissionsCompletionTests: XCTestCase {
var facebookAuth: FacebookAuth!
var config: FacebookAuth.Config!
override func setUp() {
super.setUp()
config = FacebookAuth.Config(appID: "1234657")
facebookAuth = FacebookAuth(config: config)
}
func test_it_includes_the_granted_permissions() {
let exp = expectation(description: "result contains granted permissions")
let expectedPermissions: [FacebookAuth.Permission] = [.publicProfile, .email, .adsManagement]
facebookAuth.ask(for: expectedPermissions, onTopOf: UIViewController()) { result in
XCTAssertNil(result.error)
XCTAssertEqual(result.token, "12")
XCTAssertEqual(result.granted!, expectedPermissions)
exp.fulfill()
}
let url = URL(string: "fb\(config.appID)://authorize/#access_token=12&expires_in=1&granted_scopes=public_profile,email,ads_management")!
XCTAssertTrue(facebookAuth.handle(url))
waitForExpectations(timeout: 0.2)
}
}
| mit | 4f8386d3f375013db0b71d082e917150 | 31.257143 | 140 | 0.729849 | 4.017794 | false | true | false | false |
gsaslis/Rocket.Chat.iOS | Rocket.Chat.iOS/Models/User.swift | 3 | 2499 | //
// User.swift
// Rocket.Chat.iOS
//
// Created by Mobile Apps on 8/5/15.
// Copyright © 2015 Rocket.Chat. All rights reserved.
//
import Foundation
import CoreData
class User : NSManagedObject {
/// Status of the `User`
/// This uses raw values, in order to facilitate CoreData
enum Status : Int16{
case ONLINE = 0
case AWAY = 1
case BUSY = 2
case INVISIBLE = 3
}
@NSManaged dynamic var id : String
@NSManaged dynamic var username : String
@NSManaged dynamic var password : String? //Password is only for the local user, not remote
/// Avatar url or image name.
/// In case this is not a url the code calling must know how to construct the url
@NSManaged dynamic var avata : NSData!
/// This is to make CoreData work, since it doesn't support enums
/// We store this private int to CoreData and use `status` for public usage
@NSManaged dynamic private var statusVal : NSNumber
var status : Status {
get {
return Status(rawValue: statusVal.shortValue) ?? .ONLINE
}
set {
//self.statusVal = NSNumber(short: newValue.rawValue)
setValue(NSNumber(short: newValue.rawValue), forKey: "statusVal")
}
}
@NSManaged dynamic var statusMessage : String?
@NSManaged dynamic private var timezoneVal : String
var timezone : NSTimeZone {
get {
return NSTimeZone(name: timezoneVal) ?? NSTimeZone.systemTimeZone()
}
set {
self.timezoneVal = newValue.name
}
}
convenience init(context: NSManagedObjectContext, id:String, username:String, avatar:UIImage!, status : Status, timezone : NSTimeZone){
let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.id = id
self.username = username
self.avata = UIImagePNGRepresentation(avatar)!
//TODO: Setting status hear will cause an exception, come back later and check why (probably swift/compiler bug)
//self.status = status
setValue(NSNumber(short: status.rawValue), forKey: "statusVal")
self.timezoneVal = timezone.name
}
//For Hashable
override var hashValue : Int {
return id.hashValue
}
}
//For Equalable (part of Hashable)
func == (left : User, right: User) -> Bool {
return left.id == right.id
}
| mit | b35a5331d07e8afd786fcf8289d4f62d | 32.756757 | 139 | 0.644115 | 4.541818 | false | false | false | false |
steventhanna/capsul | capsul/capsul/MKTextField.swift | 3 | 6735 | //
// MKTextField.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import QuartzCore
class MKTextField : UITextField {
@IBInspectable var padding: CGSize = CGSize(width: 5, height: 5)
@IBInspectable var floatingLabelBottomMargin: CGFloat = 2.0
@IBInspectable var floatingPlaceholderEnabled: Bool = false
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var aniDuration: Float = 0.65
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var shadowAniEnabled: Bool = true
@IBInspectable var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
// floating label
@IBInspectable var floatingLabelFont: UIFont = UIFont.boldSystemFontOfSize(10.0) {
didSet {
floatingLabel.font = floatingLabelFont
}
}
@IBInspectable var floatingLabelTextColor: UIColor = UIColor.lightGrayColor() {
didSet {
floatingLabel.textColor = floatingLabelTextColor
}
}
@IBInspectable var bottomBorderEnabled: Bool = true {
didSet {
bottomBorderLayer?.removeFromSuperlayer()
bottomBorderLayer = nil
if bottomBorderEnabled {
bottomBorderLayer = CALayer()
bottomBorderLayer?.frame = CGRect(x: 0, y: self.layer.bounds.height - 1, width: self.bounds.width, height: 1)
bottomBorderLayer?.backgroundColor = UIColor.MKColor.Grey.CGColor
self.layer.addSublayer(bottomBorderLayer)
}
}
}
@IBInspectable var bottomBorderWidth: CGFloat = 1.0
@IBInspectable var bottomBorderColor: UIColor = UIColor.lightGrayColor()
@IBInspectable var bottomBorderHighlightWidth: CGFloat = 1.75
override var placeholder: String? {
didSet {
floatingLabel.text = placeholder
floatingLabel.sizeToFit()
setFloatingLabelOverlapTextField()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
private var floatingLabel: UILabel!
private var bottomBorderLayer: CALayer?
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
private func setupLayer() {
self.cornerRadius = 2.5
self.layer.borderWidth = 1.0
self.borderStyle = .None
mkLayer.circleGrowRatioMax = 1.0
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(circleLayerColor)
// floating label
floatingLabel = UILabel()
floatingLabel.font = floatingLabelFont
floatingLabel.alpha = 0.0
self.addSubview(floatingLabel)
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
mkLayer.didChangeTapLocation(touch.locationInView(self))
mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: MKTimingFunction.Linear, duration: 0.75)
mkLayer.animateAlphaForBackgroundLayer(MKTimingFunction.Linear, duration: 0.75)
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override func layoutSubviews() {
super.layoutSubviews()
if !floatingPlaceholderEnabled {
return
}
if !self.text.isEmpty {
floatingLabel.textColor = self.isFirstResponder() ? self.tintColor : floatingLabelTextColor
if floatingLabel.alpha == 0 {
self.showFloatingLabel()
}
} else {
self.hideFloatingLabel()
}
bottomBorderLayer?.backgroundColor = self.isFirstResponder() ? self.tintColor.CGColor : bottomBorderColor.CGColor
let borderWidth = self.isFirstResponder() ? bottomBorderHighlightWidth : bottomBorderWidth
bottomBorderLayer?.frame = CGRect(x: 0, y: self.layer.bounds.height - borderWidth, width: self.layer.bounds.width, height: borderWidth)
}
override func textRectForBounds(bounds: CGRect) -> CGRect {
let rect = super.textRectForBounds(bounds)
var newRect = CGRect(x: rect.origin.x + padding.width, y: rect.origin.y,
width: rect.size.width - 2*padding.width, height: rect.size.height)
if !floatingPlaceholderEnabled {
return newRect
}
if !self.text.isEmpty {
let dTop = floatingLabel.font.lineHeight + floatingLabelBottomMargin
newRect = UIEdgeInsetsInsetRect(newRect, UIEdgeInsets(top: dTop, left: 0.0, bottom: 0.0, right: 0.0))
}
return newRect
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return self.textRectForBounds(bounds)
}
// MARK - private
private func setFloatingLabelOverlapTextField() {
let textRect = self.textRectForBounds(self.bounds)
var originX = textRect.origin.x
switch self.textAlignment {
case .Center:
originX += textRect.size.width/2 - floatingLabel.bounds.width/2
case .Right:
originX += textRect.size.width - floatingLabel.bounds.width
default:
break
}
floatingLabel.frame = CGRect(x: originX, y: padding.height,
width: floatingLabel.frame.size.width, height: floatingLabel.frame.size.height)
}
private func showFloatingLabel() {
let curFrame = floatingLabel.frame
floatingLabel.frame = CGRect(x: curFrame.origin.x, y: self.bounds.height/2, width: curFrame.width, height: curFrame.height)
UIView.animateWithDuration(0.45, delay: 0.0, options: .CurveEaseOut, animations: {
self.floatingLabel.alpha = 1.0
self.floatingLabel.frame = curFrame
}, completion: nil)
}
private func hideFloatingLabel() {
floatingLabel.alpha = 0.0
}
}
| mit | b1d7cfef0fd1b89b803bba8f5aa7d753 | 34.824468 | 143 | 0.639347 | 5.052513 | false | false | false | false |
jegumhon/URWeatherView | Example/URExampleWeatherView/URExampleWeatherViewController.swift | 1 | 11921 | //
// URExampleWeatherViewController.swift
// URExampleWeatherView
//
// Created by DongSoo Lee on 2017. 6. 19..
// Copyright © 2017년 zigbang. All rights reserved.
//
import UIKit
import URWeatherView
class URExampleWeatherViewController: UIViewController {
@IBOutlet var mainView: URWeatherView!
@IBOutlet var btnOne: UIButton!
@IBOutlet var btnTwo: UIButton!
@IBOutlet var segment: UISegmentedControl!
@IBOutlet var effectTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// self.mainView.initView(dataNameOfLottie: "data", backgroundImage: #imageLiteral(resourceName: "img_back"))
self.mainView.initView(mainWeatherImage: #imageLiteral(resourceName: "buildings"), backgroundImage: #imageLiteral(resourceName: "bluesky.en"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tabOne(_ sender: Any) {
if !self.btnOne.isSelected {
self.btnOne.isSelected = true
self.btnTwo.isSelected = false
self.mainView.play()
self.changedMainState()
}
}
@IBAction func tabTwo(_ sender: Any) {
if !self.btnTwo.isSelected {
self.btnOne.isSelected = false
self.btnTwo.isSelected = true
self.mainView.play(eventHandler: {
Timer.scheduledTimer(timeInterval: 0.32, target: self, selector: #selector(self.handleLottieAnimation), userInfo: nil, repeats: false)
})
}
}
@objc func handleLottieAnimation() {
self.mainView.pause()
self.changedMainState()
}
@IBAction func changeSpriteKitDebugOption(_ sender: Any) {
if let segment = sender as? UISegmentedControl {
let selected: Bool = segment.selectedSegmentIndex == 0
self.mainView.enableDebugOption = selected
}
}
}
extension URExampleWeatherViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return URWeatherType.all.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if URWeatherType.all[indexPath.row] == .dust ||
URWeatherType.all[indexPath.row] == .dust2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "effectCell2", for: indexPath) as! URExampleWeatherTableViewCell2
cell.configCell(URWeatherType.all[indexPath.row])
cell.applyWeatherBlock = {
switch cell.weather {
case .dust, .dust2:
if cell.btnDustColor1.isSelected {
self.mainView.startWeatherSceneBulk(.dust, debugOption: self.segment.selectedSegmentIndex == 0, additionalTask: {
if let startBirthRate = cell.weather.startBirthRate {
cell.slBirthRate.value = Float(startBirthRate)
cell.changeBirthRate(cell.slBirthRate)
}
})
}
if cell.btnDustColor2.isSelected {
self.mainView.startWeatherSceneBulk(.dust2, debugOption: self.segment.selectedSegmentIndex == 0, additionalTask: {
if let startBirthRate = cell.weather.startBirthRate {
cell.slBirthRate.value = Float(startBirthRate)
cell.changeBirthRate(cell.slBirthRate)
}
})
}
default:
break
}
}
cell.stopWeatherBlock = {
self.mainView.stop()
}
cell.birthRateDidChange = { (birthRate) in
self.mainView.birthRate = birthRate
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "effectCell1", for: indexPath) as! URExampleWeatherTableViewCell
cell.configCell(URWeatherType.all[indexPath.row])
cell.applyWeatherBlock = {
switch cell.weather {
case .snow:
self.mainView.startWeatherSceneBulk(cell.weather, debugOption: self.segment.selectedSegmentIndex == 0, additionalTask: {
self.changedMainState()
})
case .rain:
self.mainView.startWeatherSceneBulk(cell.weather, debugOption: self.segment.selectedSegmentIndex == 0, additionalTask: {
self.changedMainState()
})
case .lightning, .hot, .comet:
self.mainView.startWeatherSceneBulk(cell.weather, debugOption: self.segment.selectedSegmentIndex == 0)
case .cloudy:
// self.mainView.startWeatherSceneBulk(cell.weather, duration: 33.0, debugOption: self.segment.selectedSegmentIndex == 0)
self.mainView.initWeather()
self.mainView.setUpperImageEffect(customImage: nil)
let option = UREffectCloudOption(CGRect(x: 0.0, y: 0.5, width: 1.0, height: 0.5), angleInDegree: 0.0, movingDuration: 33.0)
self.mainView.startWeatherScene(cell.weather, duration: 33.0, userInfo: [URWeatherKeyCloudOption: option])
default:
self.mainView.setUpperImageEffect()
self.mainView.stop()
self.mainView.enableDebugOption = self.segment.selectedSegmentIndex == 0
}
}
cell.stopWeatherBlock = {
self.mainView.stop()
}
cell.birthRateDidChange = { (birthRate) in
self.mainView.birthRate = birthRate
}
return cell
}
}
func changedMainState() {
let sceneSize: CGSize = self.mainView.weatherSceneSize
switch self.mainView.weatherType {
case .snow:
if self.btnOne.isSelected {
self.mainView.weatherGroundEmitterOptions = [URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.290, y: sceneSize.height * 0.572)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.237, y: sceneSize.height * 0.530)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.188, y: sceneSize.height * 0.484)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.101, y: sceneSize.height * 0.475), rangeRatio: 0.042),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.752, y: sceneSize.height * 0.748), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.829, y: sceneSize.height * 0.602), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.663, y: sceneSize.height * 0.556), rangeRatio: 0.078, degree: -27.0)]
} else {
let diffY: CGFloat = 0.07
self.mainView.weatherGroundEmitterOptions = [URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.290, y: sceneSize.height * (0.572 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.237, y: sceneSize.height * (0.530 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.188, y: sceneSize.height * (0.484 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.101, y: sceneSize.height * (0.475 - diffY)), rangeRatio: 0.042),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.752, y: sceneSize.height * (0.748 + diffY)), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.829, y: sceneSize.height * (0.602 + diffY)), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.663, y: sceneSize.height * (0.556 + diffY)), rangeRatio: 0.078, degree: -27.0)]
}
case .rain:
if self.btnOne.isSelected {
self.mainView.weatherGroundEmitterOptions = [URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.290, y: sceneSize.height * 0.572)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.237, y: sceneSize.height * 0.530)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.188, y: sceneSize.height * 0.484)),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.101, y: sceneSize.height * 0.475), rangeRatio: 0.042),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.752, y: sceneSize.height * 0.748), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.829, y: sceneSize.height * 0.602), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.663, y: sceneSize.height * 0.556), rangeRatio: 0.078, degree: -27.0)]
} else {
let diffY: CGFloat = 0.07
self.mainView.weatherGroundEmitterOptions = [URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.307, y: sceneSize.height * (0.590 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.261, y: sceneSize.height * (0.544 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.208, y: sceneSize.height * (0.497 - diffY))),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.122, y: sceneSize.height * (0.481 - diffY)), rangeRatio: 0.042),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.778, y: sceneSize.height * (0.761 + diffY)), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.855, y: sceneSize.height * (0.614 + diffY)), rangeRatio: 0.094, degree: -27.0),
URWeatherGroundEmitterOption(position: CGPoint(x: sceneSize.width * 0.684, y: sceneSize.height * (0.565 + diffY)), rangeRatio: 0.078, degree: -27.0)]
}
default:
break
}
}
}
| mit | 876e745db2cc291a495e3ac0cf1f97dc | 57.421569 | 210 | 0.559322 | 4.860522 | false | false | false | false |
ghotjunwoo/Tiat | addChatFriend.swift | 1 | 2984 | //
// addChatFriend.swift
// Tiat
//
// Created by 이종승 on 2016. 10. 2..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
class addChatFriend: UIViewController, UITableViewDelegate, UITableViewDataSource {
var users = [User]()
var keys = [String]()
var image = [UIImage]()
let cellId = "friendsCell"
var downloadURL: URL = NSURL(string: "") as! URL
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
keys.removeAll()
fetchUser()
}
func fetchUser () {
FIRDatabase.database().reference().child("users").observe(.childAdded, with: {snapshot in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.name = dictionary["name"] as? String
self.keys.append(snapshot.key)
self.users.append(user)
DispatchQueue.main.async {
self.tableView?.reloadData()
}
}
})
for reference in keys {
let user = User()
let httpsReference = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com").child("users/\(reference)/profileimage") // your download URL
httpsReference.data(withMaxSize: 1 * 7168 * 7168) { (data, error) -> Void in
if (error != nil) {
// Uh-oh, an error occurred!
print(error?.localizedDescription)
} else {
// Data for "images/stars.jpg" is returned
user.image = UIImage(data: data!)
self.users.append(user)
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! FriendTableViewCell
let user = users[indexPath.row]
cell.nameLabel.text = user.name
cell.profileImage.image = user.image
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let newuser = users[indexPath.row]
let usernname = newuser.name! as String
print(usernname)
print(keys[indexPath.row])
let destinationViewController = ChatViewController()
destinationViewController.toUid = keys[indexPath.row]
destinationViewController.userName = usernname
performSegue(withIdentifier: "toChatView", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 5d60b95b8accaeb5ed1d312178e85bcc | 33.195402 | 164 | 0.582857 | 4.933665 | false | false | false | false |
terryxing/Swift | CoreAnimationSample1/CoreAnimationSample1/ViewController.swift | 26 | 1750 | //
// ViewController.swift
// CoreAnimationSample1
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
@IBAction func animate(sender: UIButton) {
var animation:CABasicAnimation = CABasicAnimation(keyPath: "position")
animation.fromValue = NSValue(CGPoint:CGPointMake(image.frame.midX, image.frame.midY))
animation.toValue = NSValue(CGPoint:CGPointMake(image.frame.midX, 340))
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.duration = 1.0
image.layer.addAnimation(animation, forKey: "position")
}
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.
}
}
| gpl-3.0 | 8b469fbc21ba9095d4bedde170256f68 | 37.043478 | 121 | 0.708 | 4.742547 | false | false | false | false |
alimoeeny/Buildasaur | Buildasaur/StatusSyncerViewController.swift | 2 | 11093 | //
// StatusSyncerViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 08/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaUtils
import XcodeServerSDK
import BuildaKit
class StatusSyncerViewController: StatusViewController, SyncerDelegate {
@IBOutlet weak var statusTextField: NSTextField!
@IBOutlet weak var startStopButton: NSButton!
@IBOutlet weak var statusActivityIndicator: NSProgressIndicator!
@IBOutlet weak var syncIntervalStepper: NSStepper!
@IBOutlet weak var syncIntervalTextField: NSTextField!
@IBOutlet weak var lttmToggle: NSButton!
@IBOutlet weak var postStatusCommentsToggle: NSButton!
var isSyncing: Bool {
set {
if let syncer = self.syncer() {
syncer.active = newValue
}
self.delegate.getProjectStatusViewController().editingAllowed = !newValue
self.delegate.getServerStatusViewController().editingAllowed = !newValue
}
get {
if let syncer = self.syncer() {
return syncer.active
}
return false
}
}
func syncer() -> HDGitHubXCBotSyncer? {
if let syncer = self.storageManager.syncers.first {
if syncer.delegate == nil {
syncer.delegate = self
if syncer.active {
self.syncerBecameActive(syncer)
} else {
self.syncerStopped(syncer)
}
}
return syncer
}
return nil
}
func syncerBecameActive(syncer: Syncer) {
self.report("Syncer is now active...")
}
func syncerStopped(syncer: Syncer) {
self.report("Syncer is stopped")
}
func syncerDidStartSyncing(syncer: Syncer) {
var messages = [
"Syncing in progress..."
]
if let lastStartedSync = self.syncer()?.lastSyncStartDate {
let lastSyncString = "Started sync at \(lastStartedSync)"
messages.append(lastSyncString)
}
self.reportMultiple(messages)
}
func syncerDidFinishSyncing(syncer: Syncer) {
var messages = [
"Syncer is Idle... Waiting for the next sync...",
]
if let ourSyncer = syncer as? HDGitHubXCBotSyncer {
//error?
if let error = ourSyncer.lastSyncError {
messages.insert("Last sync failed with error \(error.localizedDescription)", atIndex: 0)
}
//info reports
let reports = ourSyncer.reports
let reportsArray = reports.keys.map({ "\($0): \(reports[$0]!)" })
messages += reportsArray
}
self.reportMultiple(messages)
}
func syncerEncounteredError(syncer: Syncer, error: NSError) {
self.report("Error: \(error.localizedDescription)")
}
func report(string: String) {
self.reportMultiple([string])
}
func reportMultiple(strings: [String]) {
var itemsToReport = [String]()
if let lastFinishedSync = self.syncer()?.lastSuccessfulSyncFinishedDate {
let lastSyncString = "Last successful sync at \(lastFinishedSync)"
itemsToReport.append(lastSyncString)
}
strings.forEach { itemsToReport.append($0) }
self.statusTextField.stringValue = itemsToReport.joinWithSeparator("\n")
}
override func viewDidLoad() {
super.viewDidLoad()
self.statusTextField.stringValue = "-"
}
override func viewDidAppear() {
super.viewDidAppear()
if let syncer = self.syncer() {
Log.info("We have a syncer \(syncer)")
}
}
override func reloadStatus() {
self.startStopButton.title = self.isSyncing ? "Stop" : "Start"
self.syncIntervalStepper.enabled = !self.isSyncing
self.lttmToggle.enabled = !self.isSyncing
self.postStatusCommentsToggle.enabled = !self.isSyncing
if self.isSyncing {
self.statusActivityIndicator.startAnimation(nil)
} else {
self.statusActivityIndicator.stopAnimation(nil)
}
if let syncer = self.syncer() {
self.updateIntervalFromUIToValue(syncer.syncInterval)
self.lttmToggle.state = syncer.waitForLttm ? NSOnState : NSOffState
self.postStatusCommentsToggle.state = syncer.postStatusComments ? NSOnState : NSOffState
} else {
self.updateIntervalFromUIToValue(15) //default
self.lttmToggle.state = NSOffState //default is false
self.postStatusCommentsToggle.state = NSOnState //default is true
}
}
func updateIntervalFromUIToValue(value: NSTimeInterval) {
self.syncIntervalTextField.doubleValue = value
self.syncIntervalStepper.doubleValue = value
}
@IBAction func syncIntervalStepperValueChanged(sender: AnyObject) {
if let stepper = sender as? NSStepper {
let value = stepper.doubleValue
self.updateIntervalFromUIToValue(value)
}
}
@IBAction func startStopButtonTapped(sender: AnyObject) {
self.toggleActiveWithCompletion { () -> () in
//
}
}
@IBAction func branchWatchingTapped(sender: AnyObject) {
if let _ = self.syncer() {
self.performSegueWithIdentifier("showBranchWatching", sender: self)
} else {
UIUtils.showAlertWithText("Syncer must be created first. Click 'Start' and try again.")
}
}
@IBAction func manualBotManagementTapped(sender: AnyObject) {
if let _ = self.syncer() {
self.performSegueWithIdentifier("showManual", sender: self)
} else {
UIUtils.showAlertWithText("Syncer must be created first. Click 'Start' and try again.")
}
}
@IBAction func helpLttmButtonTapped(sender: AnyObject) {
let urlString = "https://github.com/czechboy0/Buildasaur/blob/master/README.md#unlock-the-lttm-barrier"
if let url = NSURL(string: urlString) {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
@IBAction func helpPostStatusCommentsButtonTapped(sender: AnyObject) {
let urlString = "https://github.com/czechboy0/Buildasaur/blob/master/README.md#envelope-posting-status-comments"
if let url = NSURL(string: urlString) {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if let manual = segue.destinationController as? ManualBotManagementViewController {
manual.syncer = self.syncer()!
}
if let branchWatching = segue.destinationController as? BranchWatchingViewController {
branchWatching.syncer = self.syncer()!
}
}
func startSyncing() {
//create a syncer, delete the old one and kick it off
let oldWatchedBranchNames: [String]
if let syncer = self.syncer() {
self.storageManager.removeSyncer(syncer)
oldWatchedBranchNames = syncer.watchedBranchNames
} else {
oldWatchedBranchNames = []
}
let waitForLttm = self.lttmToggle.state == NSOnState
let postStatusComments = self.postStatusCommentsToggle.state == NSOnState
let syncInterval = self.syncIntervalTextField.doubleValue
let project = self.delegate.getProjectStatusViewController().project()!
let serverConfig = self.delegate.getServerStatusViewController().serverConfig()!
if let syncer = self.storageManager.addSyncer(
syncInterval,
waitForLttm: waitForLttm,
postStatusComments: postStatusComments,
project: project,
serverConfig: serverConfig,
watchedBranchNames: oldWatchedBranchNames) {
syncer.active = true
self.isSyncing = true
self.reloadStatus()
} else {
UIUtils.showAlertWithText("Couldn't start syncer, please make sure the sync interval is > 0 seconds.")
}
self.storageManager.saveSyncers()
}
func toggleActiveWithCompletion(completion: () -> ()) {
if self.isSyncing {
//stop syncing
self.isSyncing = false
self.reloadStatus()
} else if self.delegate.getProjectStatusViewController().editing ||
self.delegate.getServerStatusViewController().editing {
UIUtils.showAlertWithText("Please save your configurations above by clicking Done")
} else {
let group = dispatch_group_create()
//validate - check availability for both sources - github and xcodeserver - only kick off if both work
//gather data from the UI + storageManager and try to create a syncer with it
var projectReady: Bool = false
dispatch_group_enter(group)
self.delegate.getProjectStatusViewController().checkAvailability({ (status, done) -> () in
if done {
switch status {
case .Succeeded:
projectReady = true
default:
projectReady = false
}
dispatch_group_leave(group)
}
})
var serverReady: Bool = false
dispatch_group_enter(group)
self.delegate.getServerStatusViewController().checkAvailability({ (status, done) -> () in
if done {
switch status {
case .Succeeded:
serverReady = true
default:
serverReady = false
}
dispatch_group_leave(group)
}
})
dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
let allReady = projectReady && serverReady
if allReady {
self.startSyncing()
} else {
let brokenPart = projectReady ? "Xcode Server" : "Xcode Project"
let message = "Couldn't start syncing, please fix your \(brokenPart) settings and try again."
UIUtils.showAlertWithText(message)
}
})
}
}
}
| mit | 11c7925f07eac6cfcdcb3a949f944290 | 32.615152 | 120 | 0.568196 | 5.554832 | false | false | false | false |
asp2insp/yowl | yowl/AppDelegate.swift | 1 | 2112 | //
// AppDelegate.swift
// yowl
//
// Created by Josiah Gaskin on 5/13/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Set up the data and reactor
setupReactor()
// Set up the drawer controllers:
setupDrawers()
// Download the categories JSON
downloadCategories()
return true
}
func setupReactor() {
Reactor.instance.registerStore("biz", store: DetailsStore())
Reactor.instance.registerStore("filters", store: FiltersStore())
Reactor.instance.registerStore("results", store: SearchResultsStore())
Reactor.instance.registerStore("categories", store: CategoriesStore())
Reactor.instance.debug = false
Reactor.instance.reset()
}
func setupDrawers() {
let drawerController = self.window?.rootViewController as! MMDrawerController
drawerController.setMaximumLeftDrawerWidth(250.0, animated: true, completion: nil)
drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureMode.BezelPanningCenterView
drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.All
drawerController.centerHiddenInteractionMode = MMDrawerOpenCenterInteractionMode.NavigationBarOnly
}
func downloadCategories() {
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet(object: "binary/octet-stream") as Set<NSObject>
manager.GET("https://s3-media2.fl.yelpcdn.com/assets/srv0/developer_pages/5e749b17ad6a/assets/json/categories.json", parameters: nil, success: { (operation, data) -> Void in
Reactor.instance.dispatch("setCategories", payload: data)
}) { (operation, error) -> Void in
println(error.localizedDescription)
}
}
}
| mit | 59e1ec2df213a337c70c94c3061f53b1 | 36.052632 | 181 | 0.696023 | 4.992908 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/BaseSystemBridge.swift | 1 | 3218 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Base application for System purposes
Auto-generated implementation of IBaseSystem specification.
*/
public class BaseSystemBridge : IBaseSystem {
/**
Group of API.
*/
private var apiGroup : IAdaptiveRPGroup? = nil
/**
Default constructor.
*/
public init() {
self.apiGroup = IAdaptiveRPGroup.System
}
/**
Return the API group for the given interface.
*/
public final func getAPIGroup() -> IAdaptiveRPGroup? {
return self.apiGroup!
}
/**
Return the API version for the given interface.
*/
public final func getAPIVersion() -> String? {
return "v2.2.15"
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "BaseSystemBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 0b79bdbade54ff4b40c4e7e5da741ab6 | 33.212766 | 189 | 0.609453 | 5.017161 | false | false | false | false |
hanjoes/Breakout | Breakout/Breakout/Constants.swift | 1 | 1279 | //
// Constants.swift
// Breakout
//
// Created by Hanzhou Shi on 1/18/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
// MARK: - Constants
struct Constants {
/// Brick related
static let DefaultBrickNumPerRow: CGFloat = 10
static let BrickAspectRatio: CGFloat = 2.5
static let DefaultBrickLevels: CGFloat = 5
static let DefaultBrickMarginX: CGFloat = 5
static let DefaultBrickMarginY: CGFloat = 5
static let DefaultBrickColor = UIColor.blueColor()
/// Paddle related
static let DefaultPaddleColor = UIColor.grayColor()
static let DefaultPaddleWidthRatio: CGFloat = 6
static let DefaultPaddleRatio: CGFloat = 5
/// Ball related
static let DefaultBallNum = 1
static let DefaultBallNumMax = 10
static let DefaultBallSize = CGSize(width: 10, height: 10)
static let DefaultBallColor = UIColor.redColor()
static let DefaultPushMagnitude: CGFloat = 0.1
/// Lower bound
static let DefaultLowerBoundColor = UIColor.blackColor()
static let DefaultLowerBoundHeightRatio: CGFloat = 10
/// Identifiers
static let BrickIdentifierPrefix = "BrickIdentifier_"
static let PaddleIdentifier = "PaddleIdentifier"
static let LowerBoundIdentifier = "LowerBoundIdentifier"
} | mit | 1a5a0a4f11e93f156b3cae8973d96612 | 30.975 | 62 | 0.720657 | 4.361775 | false | false | false | false |
danwey/INSPhotoGallery | Example/INSPhotoGallery/CustomOverlayView.swift | 1 | 1854 | //
// CustomOverlayView.swift
// INSPhotoGallery
//
// Created by Michal Zaborowski on 04.04.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
import UIKit
import INSNibLoading
import INSPhotoGalleryFramework
class CustomOverlayView: INSNibLoadedView {
weak var photosViewController: INSPhotosViewController?
@IBOutlet weak var selectButton: UIButton!
@IBOutlet weak var numLabel: UILabel!
@IBOutlet weak var finishButton: UIButton!
// Pass the touches down to other views
override func awakeFromNib() {
numLabel.layer.cornerRadius = 10
numLabel.layer.masksToBounds = true
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, withEvent: event) where hitView != self {
return hitView
}
return nil
}
@IBAction func closeButtonTapped(sender: AnyObject) {
photosViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
extension CustomOverlayView: INSPhotosOverlayViewable {
func populateWithPhoto(photo: INSPhotoViewable) {
}
func setHidden(hidden: Bool, animated: Bool) {
if self.hidden == hidden {
return
}
if animated {
self.hidden = false
self.alpha = hidden ? 1.0 : 0.0
UIView.animateWithDuration(0.2, delay: 0.0, options: [.CurveEaseInOut, .AllowAnimatedContent, .AllowUserInteraction], animations: { () -> Void in
self.alpha = hidden ? 0.0 : 1.0
}, completion: { result in
self.alpha = 1.0
self.hidden = hidden
})
} else {
self.hidden = hidden
}
}
}
| apache-2.0 | ce4fb0733db54ec79b49e548684a1154 | 28.380952 | 157 | 0.612102 | 4.734015 | false | false | false | false |
windaddict/ARFun | ARFun.playground/Sources/ARDebugView.swift | 1 | 1488 | import UIKit
public class ARDebugView: UIView {
let textView = UITextView()
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
backgroundColor = UIColor.white
//size self to be a fixed width and height
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100).isActive = true
//setup textView
textView.translatesAutoresizingMaskIntoConstraints = false
addSubview(textView)
self.topAnchor.constraint(equalTo: textView.topAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: textView.bottomAnchor).isActive = true
self.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
self.trailingAnchor.constraint(equalTo: textView.trailingAnchor).isActive = true
}
public func log(_ logText: String){
var text = textView.text ?? ""
text = text + logText + "\n"
textView.text = text
}
public func clearWithLog(_ logText: String){
textView.text = logText
}
}
| mit | 3d4c9e3143b1d8deba50649414ca6c3b | 35.292683 | 164 | 0.657258 | 4.878689 | false | false | false | false |
matsprea/omim | iphone/Maps/Core/Subscriptions/SubscriptionGroup.swift | 1 | 2950 | @objc enum SubscriptionGroupType: Int {
case allPass
case sightseeing
init?(serverId: String) {
switch serverId {
case MWMPurchaseManager.bookmarksSubscriptionServerId():
self = .sightseeing
case MWMPurchaseManager.allPassSubscriptionServerId():
self = .allPass
default:
return nil
}
}
init(catalogURL: URL) {
guard let urlComponents = URLComponents(url: catalogURL, resolvingAgainstBaseURL: false) else {
self = .allPass
return
}
let subscriptionGroups = urlComponents.queryItems?
.filter({ $0.name == "groups" })
.map({ $0.value ?? "" })
if subscriptionGroups?.first(where: { $0 == MWMPurchaseManager.allPassSubscriptionServerId() }) != nil {
self = .allPass
} else if subscriptionGroups?.first(where: { $0 == MWMPurchaseManager.bookmarksSubscriptionServerId() }) != nil {
self = .sightseeing
} else {
self = .allPass
}
}
var serverId: String {
switch self {
case .sightseeing:
return MWMPurchaseManager.bookmarksSubscriptionServerId()
case .allPass:
return MWMPurchaseManager.allPassSubscriptionServerId()
}
}
}
protocol ISubscriptionGroup {
var count: Int { get }
subscript(period: SubscriptionPeriod) -> ISubscriptionGroupItem? { get }
}
class SubscriptionGroup: ISubscriptionGroup {
private var subscriptions: [ISubscriptionGroupItem]
var count: Int {
return subscriptions.count
}
init(subscriptions: [ISubscription]) {
let formatter = NumberFormatter()
formatter.locale = subscriptions.first?.priceLocale
formatter.numberStyle = .currency
let weekCycle = NSDecimalNumber(value: 7.0)
let mounthCycle = NSDecimalNumber(value: 30.0)
let yearCycle = NSDecimalNumber(value: 12.0 * 30.0)
var rates:[NSDecimalNumber] = []
var maxPriceRate: NSDecimalNumber = NSDecimalNumber.minimum
maxPriceRate = subscriptions.reduce(into: maxPriceRate) { (result, item) in
let price = item.price
var rate: NSDecimalNumber = NSDecimalNumber()
switch item.period {
case .year:
rate = price.dividing(by: yearCycle);
case .month:
rate = price.dividing(by: mounthCycle);
case .week:
rate = price.dividing(by: weekCycle);
case .unknown:
rate = price
}
result = rate.compare(result) == .orderedDescending ? rate : result;
rates.append(rate)
}
self.subscriptions = []
for (idx, subscription) in subscriptions.enumerated() {
let rate = rates[idx]
let discount = NSDecimalNumber(value: 1).subtracting(rate.dividing(by: maxPriceRate)).multiplying(by: 100)
self.subscriptions.append(SubscriptionGroupItem(subscription, discount: discount, formatter: formatter))
}
}
subscript(period: SubscriptionPeriod) -> ISubscriptionGroupItem? {
return subscriptions.first { (item) -> Bool in
return item.period == period
}
}
}
| apache-2.0 | fb23cb61055106569d153f83c2c0983e | 29.412371 | 117 | 0.675932 | 4.462935 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/Examples/Examples/CandleStickExample.swift | 1 | 7434 | //
// CandleStickExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class CandleStickExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
var readFormatter = DateFormatter()
readFormatter.dateFormat = "dd.MM.yyyy"
var displayFormatter = DateFormatter()
displayFormatter.dateFormat = "MMM dd"
let date = {(str: String) -> Date in
return readFormatter.date(from: str)!
}
let calendar = Calendar.current
let dateWithComponents = {(day: Int, month: Int, year: Int) -> Date in
var components = DateComponents()
components.day = day
components.month = month
components.year = year
return calendar.date(from: components)!
}
func filler(_ date: Date) -> ChartAxisValueDate {
let filler = ChartAxisValueDate(date: date, formatter: displayFormatter)
filler.hidden = true
return filler
}
let chartPoints = [
ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39),
ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4),
ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5),
ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5),
ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44),
ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46),
ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5),
ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49),
ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5),
ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39),
ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40),
ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38),
ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39),
ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36),
ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5),
ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31),
ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30),
ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25),
ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5),
ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27),
ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30),
ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31),
ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6),
ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5),
ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6),
ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33)
]
let yValues = stride(from: 20, through: 55, by: 5).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)}
func generateDateAxisValues(_ month: Int, year: Int) -> [ChartAxisValueDate] {
let date = dateWithComponents(1, month, year)
let calendar = Calendar.current
let monthDays = CountableRange<Int>(calendar.range(of: .day, in: .month, for: date)!)
return monthDays.map {day in
let date = dateWithComponents(day, month, year)
let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings)
axisValue.hidden = !(day % 5 == 0)
return axisValue
}
}
let xValues = generateDateAxisValues(10, year: 2015)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let chartPointsLineLayer = ChartCandleStickLayer<ChartPointCandleStick>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, itemWidth: Env.iPad ? 10 : 5, strokeWidth: Env.iPad ? 1 : 0.6)
let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true)
let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true)
let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
dividersLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| mit | b4f8d9cc7c5c99dff27458a68557ad77 | 61.470588 | 220 | 0.646355 | 4.274871 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.