repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mLewisLogic/codepath-assignment3 | twitter/Controllers/MainContainerViewController.swift | 1 | 5847 | //
// MainContainerViewController.swift
// twitter
//
// Created by Michael Lewis on 2/28/15.
// Copyright (c) 2015 Machel. All rights reserved.
//
import UIKit
class MainContainerViewController: UIViewController {
@IBOutlet weak var navMenuView: UIView!
@IBOutlet weak var contentWindowView: UIView!
var profileViewController: ProfileViewController!
var homeViewController: FeedViewController!
var mentionsViewController: FeedViewController!
var tweetViewController: TweetViewController!
var contentViews: [UIViewController]!
// Pan gesture start storage
var navMenuBeginGestureCenter: CGPoint!
// Nav menu X boundaries (of the center)
var navMenuLeftBound: CGPoint!
var navMenuRightBound: CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
var storyboard = UIStoryboard(name: "Main", bundle: nil)
/* Set up the menu bar */
// Set up our nav menu view
self.navMenuLeftBound = self.navMenuView.center
self.navMenuRightBound = self.navMenuLeftBound
self.navMenuRightBound.x += 240.0
/* Set up the content window */
// Set up the child views for the content window
self.profileViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController
self.homeViewController = storyboard.instantiateViewControllerWithIdentifier("HomeViewController") as FeedViewController
self.mentionsViewController = storyboard.instantiateViewControllerWithIdentifier("MentionsViewController") as FeedViewController
self.tweetViewController = storyboard.instantiateViewControllerWithIdentifier("TweetViewController") as TweetViewController
// Set up the sub-controllers
self.profileViewController.setUser(User.currentUser)
self.homeViewController.setFeedType(.Home, params: nil)
self.mentionsViewController.setFeedType(.Mentions, params: nil)
// Collect the views together
self.contentViews = [
self.profileViewController,
self.homeViewController,
self.mentionsViewController,
self.tweetViewController,
]
// Start with these views hidden
self.hideContentViews()
// Set the child views as subviews of our content window and align the frame
self.contentViews.map { (vc) -> () in
self.contentWindowView.addSubview(vc.view)
vc.view.frame = self.contentWindowView.frame
}
// Set the feed view controller as the active view
self.activateContentView("Home", options: nil)
// Subscribe to nav menu changes
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "handleNavMenuChange:",
name: "menuItemSelected",
object: nil
)
}
// Handle the nav menu swiping in and out
@IBAction func didSwipe(sender: UIPanGestureRecognizer) {
switch sender.state {
case .Began:
self.navMenuBeginGestureCenter = self.navMenuView.center
case .Changed:
let posChange = sender.translationInView(self.view)
var newPos = CGPoint(
x: self.navMenuBeginGestureCenter.x + posChange.x,
y: self.navMenuBeginGestureCenter.y
)
// Bound the new position
if newPos.x < navMenuLeftBound.x {
newPos.x = navMenuLeftBound.x
} else if newPos.x > navMenuRightBound.x {
newPos.x = navMenuRightBound.x
}
// Assign the new position as we drag it
self.navMenuView.center = newPos
case .Ended:
var velocity = sender.velocityInView(self.view)
// Using our velocity, determine the new position we're going to
var newPos: CGPoint
if velocity.x > 100.0 {
newPos = self.navMenuRightBound
} else if velocity.x < -100.0 {
newPos = self.navMenuLeftBound
} else {
// If we don't have strong velocity in either direction, just
// topple in whatever way it's leaning, based upon the middle.
if self.navMenuView.center.x < ((self.navMenuLeftBound.x + self.navMenuRightBound.x) / 2.0) {
newPos = self.navMenuLeftBound
} else {
newPos = self.navMenuRightBound
}
}
self.slideNavMenu(newPos)
default:
break
}
}
@IBAction func onLogout(sender: AnyObject) {
User.logout()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "navMenuSegue":
// Set up the delegate when we set up the nav menu controller
var navMenuViewController = segue.destinationViewController as NavMenuViewController
navMenuViewController.delegate = self
default:
break
}
}
}
func closeNavMenu() {
self.slideNavMenu(self.navMenuLeftBound)
}
func handleNavMenuChange(notification: NSNotification) {
var menuLabel = notification.object as String
self.activateContentView(menuLabel, options: nil)
}
/* private below */
private func slideNavMenu(newCenter: CGPoint) {
UIView.animateWithDuration(0.3,
delay: 0.0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.5,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { () -> Void in
self.navMenuView.center = newCenter
},
completion: nil
)
}
private func hideContentViews() {
self.contentViews.map { (vc) -> () in
vc.view.hidden = true
}
}
private func activateContentView(viewName: String, options: AnyObject?) {
self.hideContentViews()
switch viewName {
case "Profile":
self.profileViewController.setUser(User.currentUser)
self.profileViewController.view.hidden = false
case "Home":
self.homeViewController.view.hidden = false
case "Mentions":
self.mentionsViewController.view.hidden = false
default:
break
}
}
}
| mit | a517f559877f57155121cd1299d1d66c | 29.936508 | 133 | 0.697794 | 4.82028 | false | false | false | false |
sweetkk/SWMusic | SWMusic/Pods/ReactiveCocoa/ReactiveCocoa/DynamicProperty.swift | 8 | 2254 | import Foundation
import ReactiveSwift
import enum Result.NoError
/// Wraps a `dynamic` property, or one defined in Objective-C, using Key-Value
/// Coding and Key-Value Observing.
///
/// Use this class only as a last resort! `MutableProperty` is generally better
/// unless KVC/KVO is required by the API you're using (for example,
/// `NSOperation`).
public final class DynamicProperty<Value>: MutablePropertyProtocol {
private weak var object: NSObject?
private let keyPath: String
/// The current value of the property, as read and written using Key-Value
/// Coding.
public var value: Value? {
get {
return object?.value(forKeyPath: keyPath) as! Value
}
set(newValue) {
object?.setValue(newValue, forKeyPath: keyPath)
}
}
/// The lifetime of the property.
public var lifetime: Lifetime {
return object?.reactive.lifetime ?? .empty
}
/// A producer that will create a Key-Value Observer for the given object,
/// send its initial value then all changes over time, and then complete
/// when the observed object has deallocated.
///
/// - important: This only works if the object given to init() is KVO-compliant.
/// Most UI controls are not!
public var producer: SignalProducer<Value?, NoError> {
return (object.map { $0.reactive.values(forKeyPath: keyPath) } ?? .empty)
.map { $0 as! Value }
}
public private(set) lazy var signal: Signal<Value?, NoError> = {
var signal: Signal<DynamicProperty.Value, NoError>!
self.producer.startWithSignal { innerSignal, _ in signal = innerSignal }
return signal
}()
/// Initializes a property that will observe and set the given key path of
/// the given object. The generic type `Value` can be any Swift type, and will
/// be bridged to Objective-C via `Any`.
///
/// - important: `object` must support weak references!
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: Key path to observe on the object.
public init(object: NSObject, keyPath: String) {
self.object = object
self.keyPath = keyPath
/// A DynamicProperty will stay alive as long as its object is alive.
/// This is made possible by strong reference cycles.
_ = object.reactive.lifetime.ended.observeCompleted { _ = self }
}
}
| mit | 12e885b01ad0d20c49faec4c01b34f54 | 33.151515 | 81 | 0.703638 | 3.833333 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/ExperimentItemsDataSource.swift | 1 | 11449 | /*
* Copyright 2019 Google LLC. 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 UIKit
protocol ExperimentItemsDataSourceDelegate: class {
/// Called when the experiment data source changes.
///
/// - Parameters:
/// - experimentDataSource: The experiment data source.
/// - changes: An array of changes.
/// - indexPath: An optional index path to scroll to.
func experimentDataSource(_ experimentDataSource: ExperimentItemsDataSource,
didChange changes: [CollectionViewChange],
scrollToIndexPath indexPath: IndexPath?)
}
/// The data source for displaying experiment items.
class ExperimentItemsDataSource {
// MARK: - Nested types
/// Represents the sections of the experiment view.
enum Section: Int {
// The archived flag.
case archivedFlag
// The experiment data.
case experimentData
// The recording trial.
case recordingTrial
static let numberOfSections = 3
init(collectionViewSection: Int) {
// Force unwrap because an invalid section indicates an invalid application state which
// should crash.
self.init(rawValue: collectionViewSection)!
}
}
// MARK: - Properties
/// The archived flag section index.
var archivedFlagSectionIndex = Section.archivedFlag.rawValue
/// The archived flag index path.
let archivedFlagIndexPath = IndexPath(item: 0, section: Section.archivedFlag.rawValue)
/// Whether to show the archived flag.
var shouldShowArchivedFlag: Bool {
didSet {
guard shouldShowArchivedFlag != oldValue else {
return
}
let change: CollectionViewChange
if shouldShowArchivedFlag {
change = .insert([archivedFlagIndexPath])
} else {
change = .delete([archivedFlagIndexPath])
}
delegate?.experimentDataSource(self, didChange: [change], scrollToIndexPath: nil)
}
}
/// The experiment data section index.
var experimentDataSectionIndex = Section.experimentData.rawValue
/// The recording trial section index.
var recordingTrialSectionIndex = Section.recordingTrial.rawValue
/// The experiment items. These can be trials or notes.
var experimentItems = [DisplayItem]()
/// The delegate.
weak var delegate: ExperimentItemsDataSourceDelegate?
/// The recording trial, if there is one in progress.
private var recordingTrial: DisplayTrial?
// MARK: - Public
/// Designated initializer.
///
/// - Parameter shouldShowArchivedFlag: Whether to show the archived flag.
init(shouldShowArchivedFlag: Bool) {
self.shouldShowArchivedFlag = shouldShowArchivedFlag
}
/// Returns the item at an index, within a section.
///
/// - Parameters:
/// - section: The section.
/// - index: The index.
/// - Returns: The display item.
func item(inSection section: Section, atIndex index: Int) -> DisplayItem? {
switch section {
case .experimentData:
guard index < experimentItems.endIndex else { return nil }
return experimentItems[index]
case .recordingTrial:
// Index 0 is the trial itself. Note indexes are 1 less than `index`.
if index == 0 {
return recordingTrial
} else {
return recordingTrial?.notes[index - 1]
}
default:
return nil
}
}
/// The number of sections in the data source.
var numberOfSections = Section.numberOfSections
/// The total number of experiment data items.
var itemCount: Int {
return experimentItems.count
}
/// The total number of recording trial items.
var recordingTrialItemCount: Int {
guard let recordingTrial = recordingTrial else { return 0 }
// 1 for the trial itself, plus all of the notes.
return 1 + recordingTrial.notes.count
}
/// The number of items in the data source.
func numberOfItemsInSection(_ section: Int) -> Int {
switch Section(collectionViewSection: section) {
case .archivedFlag: return shouldShowArchivedFlag ? 1 : 0
case .experimentData: return itemCount
case .recordingTrial: return recordingTrialItemCount
}
}
/// The section type at the index.
func section(atIndex index: Int) -> Section {
return Section(collectionViewSection: index)
}
/// Whether the section is the archived flag section.
///
/// - Parameter index: A section index.
/// - Returns: True if the section is the archived flag section, false if not.
func isArchivedFlagSection(_ index: Int) -> Bool {
return index == archivedFlagSectionIndex
}
/// Whether the section is the experiment data section.
///
/// - Parameter index: A section index.
/// - Returns: True if the section is the experiment data section, false if not.
func isExperimentDataSection(_ index: Int) -> Bool {
return index == experimentDataSectionIndex
}
/// Whether the section is the recording trial section.
///
/// - Parameter index: A section index.
/// - Returns: True if the section is the recording trial section, false if not.
func isRecordingTrialSection(_ index: Int) -> Bool {
return index == recordingTrialSectionIndex
}
// MARK: - Item Updates
/// If a trial with a matching ID exists it will be updated with the given trial, otherwise the
/// trial will be added in the proper sort order.
///
/// - Parameter displayTrial: A display trial.
func addOrUpdateTrial(_ displayTrial: DisplayTrial) {
if experimentItems.firstIndex(
where: { $0 is DisplayTrial && $0.ID == displayTrial.ID }) != nil {
// Trial exists so update it.
updateTrial(displayTrial)
} else {
// Trial doesn't exist, so add it in the right place.
addItem(displayTrial, sorted: true)
}
}
/// Adds an experiment item to the end of the existing items.
///
/// - Parameters:
/// - displayItem: A display item.
/// - isSorted: Whether the item should be inserted in the correct sort order or added
/// to the end.
func addItem(_ displayItem: DisplayItem, sorted isSorted: Bool) {
var insertIndex: Int
if isSorted {
insertIndex = 0
// Find the index where the item belongs sorted by timestamp ascending.
for (index, item) in experimentItems.enumerated() {
if displayItem.timestamp.milliseconds < item.timestamp.milliseconds {
break
}
insertIndex = index + 1
}
} else {
insertIndex = experimentItems.endIndex
}
experimentItems.insert(displayItem, at: insertIndex)
let indexPath = IndexPath(item: insertIndex, section: experimentDataSectionIndex)
delegate?.experimentDataSource(self,
didChange: [.insert([indexPath])],
scrollToIndexPath: indexPath)
}
/// Adds or updates a recording trial.
///
/// - Parameter recordingTrial: A recording trial.
func addOrUpdateRecordingTrial(_ recordingTrial: DisplayTrial) {
let previousCount = recordingTrialItemCount
self.recordingTrial = recordingTrial
guard recordingTrialItemCount >= previousCount else { return }
// The only collection view changes that can occur are for new cells to be inserted, and for the
// cell that was previously the last one to have its bottom border removed by reloading it.
var indexPathToReload: IndexPath?
var indexPathToInsert: IndexPath?
for index in previousCount..<recordingTrialItemCount {
if previousCount > 0 {
indexPathToReload = IndexPath(item: index - 1, section: recordingTrialSectionIndex)
}
indexPathToInsert = IndexPath(item: index, section: recordingTrialSectionIndex)
}
var changes = [CollectionViewChange]()
if let indexPathToReload = indexPathToReload {
changes.append(.reload([indexPathToReload]))
}
if let indexPathToInsert = indexPathToInsert {
changes.append(.insert([indexPathToInsert]))
}
delegate?.experimentDataSource(self, didChange: changes, scrollToIndexPath: indexPathToInsert)
}
/// Removes the recording trial.
func removeRecordingTrial() {
// All recording trial index paths need to removed.
var indexPaths = [IndexPath]()
for index in 0..<recordingTrialItemCount {
indexPaths.append(IndexPath(item: index, section: recordingTrialSectionIndex))
}
recordingTrial = nil
delegate?.experimentDataSource(self,
didChange: [.delete(indexPaths)],
scrollToIndexPath: nil)
}
/// Removes the trial with a given ID.
///
/// - Parameter trialID: A trial ID.
/// - Returns: The index of the removed trial if the removal succeeded.
@discardableResult func removeTrial(withID trialID: String) -> Int? {
guard let index =
experimentItems.firstIndex(where: { $0 is DisplayTrial && $0.ID == trialID }) else {
return nil
}
experimentItems.remove(at: index)
let indexPath = IndexPath(item: index, section: experimentDataSectionIndex)
delegate?.experimentDataSource(self, didChange: [.delete([indexPath])], scrollToIndexPath: nil)
return index
}
/// Updates a matching trial with a new trial.
///
/// - Parameter displayTrial: A display trial.
func updateTrial(_ displayTrial: DisplayTrial) {
guard let index =
experimentItems.firstIndex(where: { $0 is DisplayTrial && $0.ID == displayTrial.ID }) else {
return
}
updateItem(displayTrial, atIndex: index)
}
/// Updates a matching note with a new note.
///
/// - Parameter displayNote: A display note.
func updateNote(_ displayNote: DisplayNote) {
guard let index =
experimentItems.firstIndex(where: { $0 is DisplayNote && $0.ID == displayNote.ID }) else {
return
}
updateItem(displayNote, atIndex: index)
}
/// Removes the note with a given ID.
///
/// - Parameter noteID: A note ID.
func removeNote(withNoteID noteID: String) {
guard let index =
experimentItems.firstIndex(where: { $0 is DisplayNote && $0.ID == noteID }) else {
return
}
experimentItems.remove(at: index)
let indexPath = IndexPath(item: index, section: experimentDataSectionIndex)
delegate?.experimentDataSource(self, didChange: [.delete([indexPath])], scrollToIndexPath: nil)
}
// MARK: - Private
/// Replaces the trial at the given index with a new item.
///
/// - Parameters:
/// - displayItem: A display item.
/// - index: The index to replace.
private func updateItem(_ displayItem: DisplayItem, atIndex index: Int) {
experimentItems.remove(at: index)
experimentItems.insert(displayItem, at: index)
let indexPath = IndexPath(item: index, section: experimentDataSectionIndex)
delegate?.experimentDataSource(self,
didChange: [.reload([indexPath])],
scrollToIndexPath: indexPath)
}
}
| apache-2.0 | c8db4dad0451d99f3ff458e5f8817dd1 | 33.381381 | 100 | 0.67674 | 4.905313 | false | false | false | false |
JerrySir/YCOA | YCOA/Main/Apply/Controller/JobTaskCreatViewController.swift | 1 | 13061 | //
// JobTaskCreatViewController.swift
// YCOA
//
// Created by Jerry on 2016/12/22.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
// 工作任务
import UIKit
class JobTaskCreatViewController: UIViewController {
@IBOutlet weak var selectProjectButton: UIButton! //所属项目
@IBOutlet weak var titleTextFiled: UITextField! //主题
@IBOutlet weak var selectTypeButton: UIButton! //任务类型
@IBOutlet weak var selectLevelButton: UIButton! //任务等级
@IBOutlet weak var selectAssignTaskToButton: UIButton! //分配给
@IBOutlet weak var selectStartTimeButton: UIButton! //开始时间
@IBOutlet weak var selectEndTimeButton: UIButton! //结束时间
@IBOutlet weak var otherInfoTextView: UITextView! //说明
@IBOutlet weak var selectReportToButton: UIButton! //报告给
@IBOutlet weak var submitButton: UIButton! //提交
@IBOutlet weak var backGroundView: UIScrollView! //背景View
//同步的数据
private var jobType: [String] = [] //任务类型
private var jobLevel:[String] = [] //任务级别
private var project: [(id: String, name: String)] = [] //项目
//Private
private var selectedJobType : String? //选择的类型
private var selectedProjectId: String? //选择的项目ID
private var selectedJobLevel : String? //选择的任务等级
private var selectedStartTime: String? //开始时间
private var selectedEndTime : String? //结束时间
private var selectedAssignedIDs : [String] = [] //分配给id
private var selectedAssignedNames : [String] = [] //分配给人名
private var selectedReportIDs : [String] = [] //报告给id
private var selectedReportNames : [String] = [] //报告给人名
override func viewDidLoad() {
super.viewDidLoad()
self.title = "工作任务"
self.UIConfigure()
self.synchroDataFromServer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Action
//从服务器同步数据
private func synchroDataFromServer() {
let parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!]
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=work|appapi&a=getcans&ajaxbool=true", parameters: parameters)
{ (error, returnValue) in
if(error != nil) {
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
guard let data : NSDictionary = (returnValue as! NSDictionary).value(forKey: "data") as? NSDictionary else{
self.navigationController?.view.jrShow(withTitle: "暂无数据")
return
}
self.jobType = []
self.jobLevel = []
self.project = []
let jobType_ = data["type"] as? [NSDictionary]
if(jobType_ != nil && jobType_!.count > 0){
for item in jobType_! {
self.jobType.append(item["name"] as! String)
}
}
let jobLevel_ = data["grade"] as? [NSDictionary]
if(jobLevel_ != nil && jobLevel_!.count > 0){
for item in jobLevel_! {
self.jobLevel.append(item["name"] as! String)
}
}
let project_ = data["project"] as? [NSDictionary]
if(project_ != nil && project_!.count > 0){
for item in project_! {
self.project.append((item["id"] as! String, item["name"] as! String))
}
}
//同步数据之后绑定Action
self.ActionConfigure()
}
}
//绑定控件Action
func ActionConfigure() {
//项目
if(self.project.count <= 0){
self.selectProjectButton.setTitle("无", for: .normal)
}else{
self.selectProjectButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
var projectNames : [String] = []
for item in self.project {
projectNames.append(item.name)
}
UIPickerView.showDidSelectView(SingleColumnDataSource: projectNames, onView: self.navigationController!.view, selectedTap: { (index) in
self.selectedProjectId = self.project[index].id
self.selectProjectButton.setTitle(self.project[index].name, for: .normal)
})
}
}
//任务类型
self.selectTypeButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIPickerView.showDidSelectView(SingleColumnDataSource: self.jobType, onView: self.navigationController!.view, selectedTap: { (index) in
self.selectedJobType = self.jobType[index]
self.selectTypeButton.setTitle(self.selectedJobType!, for: .normal)
})
}
//任务等级
self.selectLevelButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIPickerView.showDidSelectView(SingleColumnDataSource: self.jobLevel, onView: self.navigationController!.view, selectedTap: { (index) in
self.selectedJobLevel = self.jobLevel[index]
self.selectLevelButton.setTitle(self.selectedJobLevel!, for: .normal)
})
}
//分配给
self.selectAssignTaskToButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
let vc = ContactsSelectTableViewController(style: .plain)
//configure
vc.configure(selectedItems: self.selectedAssignedIDs, tap: { (ids, names) in
self.selectedAssignedIDs = ids
self.selectedAssignedNames = names
self.selectAssignTaskToButton.setTitle("\((names as NSArray).componentsJoined(by: ","))", for: .normal)
})
self.navigationController?.pushViewController(vc, animated: true)
}
//开始时间
self.selectStartTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedStartTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectStartTimeButton.setTitle(self.selectedStartTime, for: .normal)
})
}
//结束时间
self.selectEndTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedEndTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectEndTimeButton.setTitle(self.selectedEndTime, for: .normal)
})
}
//报告给
self.selectReportToButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
let vc = ContactsSelectTableViewController(style: .plain)
//configure
vc.configure(selectedItems: self.selectedReportIDs, tap: { (ids, names) in
self.selectedReportIDs = ids
self.selectedReportNames = names
self.selectReportToButton.setTitle("\((names as NSArray).componentsJoined(by: ","))", for: .normal)
})
self.navigationController?.pushViewController(vc, animated: true)
}
//提交
self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
self.didSubmit()
}
//backGroundView
self.backGroundView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer { (sender) in
self.view.endEditing(true)
}
self.backGroundView.addGestureRecognizer(tapGestureRecognizer)
}
//提交
private func didSubmit() {
let title_ = self.titleTextFiled.text
if(!(title_ != nil && title_!.utf8.count > 0)){
self.navigationController?.view.jrShow(withTitle: "请填写主题")
return
}
guard let type_ : String = self.selectedJobType else {
self.navigationController?.view.jrShow(withTitle: "请选择任务类型")
return
}
guard let grade_ : String = self.selectedJobLevel else {
self.navigationController?.view.jrShow(withTitle: "请选择任务等级")
return
}
guard self.selectedAssignedIDs.count > 0 else {
self.navigationController?.view.jrShow(withTitle: "请选择分配人员")
return
}
let distid_ = (self.selectedAssignedIDs as NSArray).componentsJoined(by: ",")
let dist_ = (self.selectedAssignedNames as NSArray).componentsJoined(by: ",")
guard let startdt_ : String = self.selectedStartTime else{
self.navigationController?.view.jrShow(withTitle: "请选择开始时间")
return
}
var parameters : [String : Any] =
["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!,
"title" : title_!,
"type" : type_,
"grade" : grade_,
"distid" : distid_,
"dist" : dist_,
"startdt" : startdt_]
//以下可选
if(self.selectedEndTime != nil){
parameters["enddt"] = self.selectedEndTime!
}
if(self.otherInfoTextView.text.utf8.count > 0){
parameters["explain"] = self.otherInfoTextView.text
}
if(self.selectedReportIDs.count > 0){
parameters["baoid"] = (self.selectedReportIDs as NSArray).componentsJoined(by: ",")
parameters["baoname"] = (self.selectedReportNames as NSArray).componentsJoined(by: ",")
}
if(self.selectedProjectId != nil){
parameters["projectid"] = self.selectedProjectId!
}
//Get
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=work|appapi&a=savework&ajaxbool=true", parameters: parameters)
{ (error, returnValue) in
if(error != nil){
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
self.navigationController?.view.jrShow(withTitle: "提交成功!")
}
}
//MARK: - UI
//配置控件UI
func UIConfigure() {
self.makeTextFieldStyle(sender: self.selectProjectButton)
self.makeTextFieldStyle(sender: self.selectTypeButton)
self.makeTextFieldStyle(sender: self.selectLevelButton)
self.makeTextFieldStyle(sender: self.selectAssignTaskToButton)
self.makeTextFieldStyle(sender: self.selectStartTimeButton)
self.makeTextFieldStyle(sender: self.selectEndTimeButton)
self.makeTextFieldStyle(sender: self.otherInfoTextView)
self.makeTextFieldStyle(sender: self.selectReportToButton)
self.makeTextFieldStyle(sender: self.submitButton)
}
///设置控件成为TextField一样的样式
func makeTextFieldStyle(sender: UIView) {
sender.layer.masksToBounds = true
sender.layer.cornerRadius = 10/2
sender.layer.borderWidth = 0.3
sender.layer.borderColor = UIColor.lightGray.cgColor
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6ea0c1c71173f04e2e26cf090a4614a1 | 38.145511 | 161 | 0.587789 | 4.778534 | false | false | false | false |
lntotherain/huacaizhibo | huacaizhibo/huacaizhibo/Classes/Tools/UIBarButtonItem+Extention.swift | 1 | 1462 | //
// UIBarButtonItem+Extention.swift
// huacaizhibo
//
// Created by mac on 2016/10/29.
// Copyright © 2016年 julia. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/* class func creatItem(imgname: String,highLightImgName: String, size:CGSize) -> UIBarButtonItem{
let img = UIImage(named: imgname)
let imgHighLight = UIImage(named: highLightImgName)
let btn = UIButton()
btn.frame = CGRect(origin: CGPoint.zero, size: size)
btn.setImage(img, for: .normal)
btn.setImage(imgHighLight, for: .highlighted)
let barButtonItem = UIBarButtonItem(customView: btn)
return barButtonItem
}
*/
//便利构造函数
convenience init(imgname: String,highLightImgName: String = "", size:CGSize = CGSize.zero) {
let img = UIImage(named: imgname)
let btn = UIButton()
btn.setImage(img, for: .normal)
if highLightImgName != "" {
let imgHighLight = UIImage(named: highLightImgName)
btn.setImage(imgHighLight, for: .highlighted)
}
if size != CGSize.zero {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView: btn)
}
}
| apache-2.0 | d53008de81ab24bbe21a3579a53e5906 | 25.309091 | 101 | 0.530062 | 4.807309 | false | false | false | false |
maxiwinkler07/pop-the-lock | Pop The Lock!/Pop The Lock!/GameViewController.swift | 1 | 1416 | //
// GameViewController.swift
// Pop The Lock!
//
// Created by Maxi Winkler on 19/9/15.
// Copyright (c) 2015 Informaticamaxi. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 5a1819a777d849a4c1282ba7a4f18e95 | 25.716981 | 94 | 0.603814 | 5.488372 | false | false | false | false |
ashokgelal/AlgorithmsPlayground | InsertionSort.playground/Contents.swift | 1 | 866 | // ### INSERTION SORT ###
import Foundation
func sort(data: [Int]) -> [Int] {
if data.count < 1 {
return data
}
// create a copy to avoid changing original data
var input = NSMutableArray(array: data) as NSArray as! [Int]
for var i = 1; i < input.count; i++ {
var extractedElem = input[i]
var j : Int
for j = i - 1; j >= 0 && extractedElem < input[j]; j-- {
input[j + 1] = input[j]
}
input[j + 1] = extractedElem
}
return input
}
let data = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
let answer = [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
let sorted = sort(data)
sequenceEquals(answer, sorted)
// O(1) extra space (ignoring input copy)
// O(n^2) comparisons and swaps
// ideal when data is nearly sorted or the problem size is small
| mit | c6334aaee286cd38985f029905cdb173 | 25.242424 | 69 | 0.560046 | 3.137681 | false | false | false | false |
paulkite/AlertHandler | AlertHandlerDemo/AlertHandlerDemo/PresentedViewController.swift | 1 | 941 | //
// PresentedViewController.swift
// AlertHandlerDemo
//
// Created by Paul Kite on 4/1/16.
// Copyright © 2016 Voodoo77 Studios, Inc. All rights reserved.
//
import UIKit
import AlertHandler
class PresentedViewController: UIViewController {
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var presentActionSheetButton: UIButton!
@IBOutlet var presentAlertButton: UIButton!
@IBAction func handleButtonTap(sender: AnyObject) {
if sender as? UIButton == self.presentAlertButton {
AlertHandler.displayAlert(title: "Title", message: "Message")
} else if sender as? UIButton == self.presentActionSheetButton {
AlertHandler.displayActionSheet(title: "Title", message: "Message", actions: nil, fromView: sender as? UIView)
} else if sender as? UIBarButtonItem == self.doneButton {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
| mit | 356d985a35c18ceaf828f205aa3333ef | 35.153846 | 122 | 0.705319 | 4.607843 | false | false | false | false |
guidomb/PortalView | Sources/UIKit/PortalTableView.swift | 1 | 6670 | //
// PortalTableView.swift
// PortalView
//
// Created by Guido Marucci Blas on 2/14/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
public final class PortalTableView<MessageType, CustomComponentRendererType: UIKitCustomComponentRenderer>: UITableView, UITableViewDataSource, UITableViewDelegate
where CustomComponentRendererType.MessageType == MessageType {
public typealias CustomComponentRendererFactory = () -> CustomComponentRendererType
public let mailbox = Mailbox<MessageType>()
public var isDebugModeEnabled: Bool = false
fileprivate let rendererFactory: CustomComponentRendererFactory
fileprivate let layoutEngine: LayoutEngine
fileprivate let items: [TableItemProperties<MessageType>]
// Used to cache cell actual height after rendering table
// item component. Caching cell height is usefull when
// cells have dynamic height.
fileprivate var cellHeights: [CGFloat?]
public init(items: [TableItemProperties<MessageType>], layoutEngine: LayoutEngine, rendererFactory: @escaping CustomComponentRendererFactory) {
self.rendererFactory = rendererFactory
self.items = items
self.layoutEngine = layoutEngine
self.cellHeights = Array(repeating: .none, count: items.count)
super.init(frame: .zero, style: .plain)
self.dataSource = self
self.delegate = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
let cellRender = itemRender(at: indexPath)
let cell = dequeueReusableCell(with: cellRender.typeIdentifier)
cell.component = cellRender.component
let componentHeight = cell.component?.layout.height
if componentHeight?.value == .none && componentHeight?.maximum == .none {
// TODO replace this with a logger
print("WARNING: Table item component with identifier '\(cellRender.typeIdentifier)' does not specify layout height! You need to either set layout.height.value or layout.height.maximum")
}
// For some reason the first page loads its cells with smaller bounds.
// This forces the cell to have the width of its parent view.
if let width = self.superview?.bounds.width {
let baseHeight = itemBaseHeight(at: indexPath)
cell.bounds.size.width = width
cell.bounds.size.height = baseHeight
cell.contentView.bounds.size.width = width
cell.contentView.bounds.size.height = baseHeight
}
cell.selectionStyle = item.onTap.map { _ in item.selectionStyle.asUITableViewCellSelectionStyle } ?? .none
cell.isDebugModeEnabled = isDebugModeEnabled
cell.render()
// After rendering the cell, the parent view returned by rendering the
// item component has the actual height calculated after applying layout.
// This height needs to be cached in order to be returned in the
// UITableViewCellDelegate's method tableView(_,heightForRowAt:)
let actualCellHeight = cell.contentView.subviews[0].bounds.height
cellHeights[indexPath.row] = actualCellHeight
cell.bounds.size.height = actualCellHeight
cell.contentView.bounds.size.height = actualCellHeight
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return itemBaseHeight(at: indexPath)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = items[indexPath.row]
item.onTap |> { mailbox.dispatch(message: $0) }
}
}
fileprivate extension PortalTableView {
fileprivate func dequeueReusableCell(with identifier: String) -> PortalTableViewCell<MessageType, CustomComponentRendererType> {
if let cell = dequeueReusableCell(withIdentifier: identifier) as? PortalTableViewCell<MessageType, CustomComponentRendererType> {
return cell
} else {
let cell = PortalTableViewCell<MessageType, CustomComponentRendererType>(
reuseIdentifier: identifier,
layoutEngine: layoutEngine,
rendererFactory: rendererFactory
)
cell.mailbox.forward(to: mailbox)
return cell
}
}
fileprivate func itemRender(at indexPath: IndexPath) -> TableItemRender<MessageType> {
// TODO cache the result of calling renderer. Once the diff algorithm is implemented find a way to only
// replace items that have changed.
// IGListKit uses some library or algorithm to diff array. Maybe that can be used to make the array diff
// more efficient.
//
// https://github.com/Instagram/IGListKit
//
// Check the video of the talk that presents IGListKit to find the array diff algorithm.
// Also there is Dwifft which seems to be based in the same algorithm:
//
// https://github.com/jflinter/Dwifft
//
let item = items[indexPath.row]
return item.renderer(item.height)
}
fileprivate func itemMaxHeight(at indexPath: IndexPath) -> CGFloat {
return CGFloat(items[indexPath.row].height)
}
/// Returns the cached actual height for the item at the given `indexPath`.
/// Actual heights are cached using the `cellHeights` instance variable and
/// are calculated after rending the item component inside the table view cell.
/// This is usefull when cells have dynamic height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: The cached actual item height.
fileprivate func itemActualHeight(at indexPath: IndexPath) -> CGFloat? {
return cellHeights[indexPath.row]
}
/// Returns the item's cached actual height if available. Otherwise it
/// returns the item's max height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: the item's cached actual height or its max height.
fileprivate func itemBaseHeight(at indexPath: IndexPath) -> CGFloat {
return itemActualHeight(at: indexPath) ?? itemMaxHeight(at: indexPath)
}
}
| mit | 4f2b598527c21ee72def774374cba252 | 41.75 | 197 | 0.675514 | 5.326677 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ActiveLabel/ActiveLabel/ActiveBuilder.swift | 4 | 4357 | //
// ActiveBuilder.swift
// ActiveLabel
//
// Created by Pol Quintana on 04/09/16.
// Copyright © 2016 Optonaut. All rights reserved.
//
import Foundation
typealias ActiveFilterPredicate = ((String) -> Bool)
struct ActiveBuilder {
static func createElements(type: ActiveType, from text: String, range: NSRange, filterPredicate: ActiveFilterPredicate?) -> [ElementTuple] {
switch type {
case .mention, .hashtag:
return createElementsIgnoringFirstCharacter(from: text, for: type, range: range, filterPredicate: filterPredicate)
case .url:
return createElements(from: text, for: type, range: range, filterPredicate: filterPredicate)
case .custom:
return createElements(from: text, for: type, range: range, minLength: 1, filterPredicate: filterPredicate)
}
}
static func createURLElements(from text: String, range: NSRange, maximumLenght: Int?) -> ([ElementTuple], String) {
let type = ActiveType.url
var text = text
let matches = RegexParser.getElements(from: text, with: type.pattern, range: range)
let nsstring = text as NSString
var elements: [ElementTuple] = []
for match in matches where match.range.length > 2 {
let word = nsstring.substring(with: match.range)
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
guard let maxLenght = maximumLenght, word.characters.count > maxLenght else {
let range = maximumLenght == nil ? match.range : (text as NSString).range(of: word)
let element = ActiveElement.create(with: type, text: word)
elements.append((range, element, type))
continue
}
let trimmedWord = word.trim(to: maxLenght)
text = text.replacingOccurrences(of: word, with: trimmedWord)
let newRange = (text as NSString).range(of: trimmedWord)
let element = ActiveElement.url(original: word, trimmed: trimmedWord)
elements.append((newRange, element, type))
}
return (elements, text)
}
private static func createElements(from text: String,
for type: ActiveType,
range: NSRange,
minLength: Int = 2,
filterPredicate: ActiveFilterPredicate?) -> [ElementTuple] {
let matches = RegexParser.getElements(from: text, with: type.pattern, range: range)
let nsstring = text as NSString
var elements: [ElementTuple] = []
for match in matches where match.range.length > minLength {
let word = nsstring.substring(with: match.range)
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if filterPredicate?(word) ?? true {
let element = ActiveElement.create(with: type, text: word)
elements.append((match.range, element, type))
}
}
return elements
}
private static func createElementsIgnoringFirstCharacter(from text: String,
for type: ActiveType,
range: NSRange,
filterPredicate: ActiveFilterPredicate?) -> [ElementTuple] {
let matches = RegexParser.getElements(from: text, with: type.pattern, range: range)
let nsstring = text as NSString
var elements: [ElementTuple] = []
for match in matches where match.range.length > 2 {
let range = NSRange(location: match.range.location + 1, length: match.range.length - 1)
var word = nsstring.substring(with: range)
if word.hasPrefix("@") {
word.remove(at: word.startIndex)
}
else if word.hasPrefix("#") {
word.remove(at: word.startIndex)
}
if filterPredicate?(word) ?? true {
let element = ActiveElement.create(with: type, text: word)
elements.append((match.range, element, type))
}
}
return elements
}
}
| mit | c4c1dde429a894deba88c89063a6eeda | 42.56 | 144 | 0.570937 | 5.16726 | false | false | false | false |
tbaranes/SwiftyUtils | Tests/Extensions/Foundation/ReusableFormatters/ReusableFormattersTests.swift | 1 | 2283 | //
// ReusableFormattersTests.swift
// SwiftyUtils
//
// Created by Tom Baranes on 25/04/2020.
// Copyright © 2020 Tom Baranes. All rights reserved.
//
import XCTest
import SwiftyUtils
final class ReusableFormattersTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
// MARK: - Tests
extension UserDefaultsExtensionTests {
func testReuseDateFormatter() {
let formatter = SUDateFormatter.shared
formatter.dateFormat = "YYYY"
XCTAssertEqual(formatter.dateFormat, SUDateFormatter.shared.dateFormat)
}
func testReuseNumberFormatter() {
let formatter = SUNumberFormatter.shared
formatter.formatWidth = 3
XCTAssertEqual(formatter.formatWidth, SUNumberFormatter.shared.formatWidth)
}
func testReuseByteFormatter() {
let formatter = SUByteCountFormatter.shared
formatter.formattingContext = .middleOfSentence
XCTAssertEqual(formatter.formattingContext, SUByteCountFormatter.shared.formattingContext)
}
func testReuseDateComponentsFormatter() {
let formatter = SUDateComponentsFormatter.shared
formatter.allowedUnits = .day
XCTAssertEqual(formatter.allowedUnits, SUDateComponentsFormatter.shared.allowedUnits)
}
func testReuseDateIntervalFormatter() {
let formatter = SUDateIntervalFormatter.shared
formatter.dateStyle = .medium
XCTAssertEqual(formatter.dateStyle, SUDateIntervalFormatter.shared.dateStyle)
}
func testReuseEnergyIntervalFormatter() {
let formatter = SUEnergyFormatter.shared
formatter.isForFoodEnergyUse = true
XCTAssertEqual(formatter.isForFoodEnergyUse, SUEnergyFormatter.shared.isForFoodEnergyUse)
}
func testReuseMassFormatter() {
let formatter = SUMassFormatter.shared
formatter.isForPersonMassUse = true
XCTAssertEqual(formatter.isForPersonMassUse, SUMassFormatter.shared.isForPersonMassUse)
}
func testReuseLengthFormatter() {
let formatter = SULengthFormatter.shared
formatter.isForPersonHeightUse = true
XCTAssertEqual(formatter.isForPersonHeightUse, SULengthFormatter.shared.isForPersonHeightUse)
}
}
| mit | 41ebf219416dc1626b629e5078127930 | 29.426667 | 101 | 0.726117 | 5.233945 | false | true | false | false |
sebastianvarela/iOS-Swift-Helpers | Helpers/Helpers/ArrayExtensions.swift | 2 | 2377 | import Foundation
public extension Sequence {
func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
var categories: [U: [Iterator.Element]] = [:]
for element in self {
let key = key(element)
if case nil = categories[key]?.append(element) {
categories[key] = [element]
}
}
return categories
}
}
public extension Array {
/// Returns an array containing this sequence shuffled
public var shuffled: Array {
var elements = self
return elements.shuffle()
}
/// Shuffles this sequence in place
@discardableResult
public mutating func shuffle() -> Array {
indices.dropLast().forEach {
guard case let index = Int(arc4random_uniform(UInt32(count - $0))) + $0, index != $0 else {
return
}
swapAt($0, index)
}
return self
}
public var randomItem: Element {
return self[Int(arc4random_uniform(UInt32(count)))]
}
public func randomItems(maxItems: Int) -> Array {
return Array(shuffled.prefix(maxItems))
}
public func mapOptionals<U>(_ transform: (Element) -> U?) -> [U]? {
var result: [U] = []
for elem in self {
if let mapped = transform(elem) {
result.append(mapped)
} else {
return nil
}
}
return result
}
public func mapSkipNils<U>(_ transform: (Element) -> U?) -> [U] {
var result: [U] = []
for elem in self {
if let mapped = transform(elem) {
result.append(mapped)
}
}
return result
}
public func element(atIndex index: Int) -> Element? {
if count > index {
return self[index]
}
return nil
}
public func find(_ includedElement: (Element) -> Bool) -> Int? {
for (idx, element) in enumerated() {
if includedElement(element) {
return idx
}
}
return nil
}
public mutating func removeIfFound(_ includedElement: (Element) -> Bool) {
if let i = self.find(includedElement) {
self.remove(at: i)
}
}
}
| mit | 4ba32421f757898c5e5819ff54c33419 | 25.411111 | 103 | 0.505259 | 4.56238 | false | false | false | false |
steamclock/internetmap | iOS/CreditsViewController.swift | 1 | 7187 | //
// CreditsViewController.swift
// Internet Map
//
// Created by Nigel Brooke on 2017-11-08.
// Copyright © 2017 Peer1. All rights reserved.
//
import UIKit
public class CreditsViewController: UIViewController, UIWebViewDelegate {
@objc public var informationType = ""
@objc public var delegate: AnyObject?
private var webView: UIWebView!
private var aboutMoreButton: UIButton?
class func currentSize() -> CGSize {
return CreditsViewController.size(in: UIApplication.shared.statusBarOrientation)
}
class func size(in orientation: UIInterfaceOrientation) -> CGSize {
var size: CGSize = UIScreen.main.bounds.size
if orientation.isLandscape {
size = CGSize(width: size.height, height: size.width)
}
return size
}
override public func viewDidLoad() {
// Background image
var backgroundImage: UIImage?
if UIDevice.current.userInterfaceIdiom == .phone {
backgroundImage = UIImage(named: "iphone-bg.png")
}
else {
backgroundImage = UIImage(named: "ipad-bg.png")
}
let background = UIImageView(image: backgroundImage)
background.isUserInteractionEnabled = true
view = background
// Webview for contents
webView = UIWebView()
var webViewFrame: CGRect = background.frame
if (informationType == "about") {
webViewFrame.size.height = CreditsViewController.currentSize().height - 60
}
else {
webViewFrame.size.height = CreditsViewController.currentSize().height
}
if UIDevice.current.userInterfaceIdiom == .pad {
// webViewFrame.origin.x += 300;
webViewFrame.origin.x = UIScreen.main.bounds.size.width / 2 - 200
webViewFrame.size.width -= 600
webView.scrollView.isScrollEnabled = false
}
else {
webViewFrame.size.width = UIScreen.main.bounds.size.width - 20
}
webView.frame = webViewFrame
var filePath: String
if informationType == "about" {
filePath = Bundle.main.path(forResource: "about", ofType: "html") ?? ""
}
else if informationType == "contact" {
filePath = Bundle.main.path(forResource: "contact", ofType: "html") ?? ""
}
else {
filePath = Bundle.main.path(forResource: "credits", ofType: "html") ?? ""
}
let html = try? String(contentsOfFile: filePath, encoding: .utf8)
if html != nil {
webView.loadHTMLString(html ?? "", baseURL: nil)
}
webView.backgroundColor = UIColor.clear
webView.isOpaque = false
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.indicatorStyle = .white
// Start webview faded out, load happens async, and this way we can fade it in rather
// than popping when the load finishes. Slightly less jarring that way.
webView.alpha = 0.00
webView.delegate = self
view.addSubview(webView)
//Done button
let xImage = UIImage(named: "x-icon")!
let doneButtonWidth = xImage.size.width + 20
let doneButtonHeight = xImage.size.height + 20
let doneButton = UIButton(type: .custom)
doneButton.imageView?.contentMode = .center
doneButton.setImage(xImage, for: .normal)
doneButton.addTarget(self, action: #selector(self.close), for: .touchUpInside)
doneButton.backgroundColor = Theme.primary
doneButton.layer.cornerRadius = doneButtonHeight / 2
view.addSubview(doneButton)
let guide = self.view.safeAreaLayoutGuide
doneButton.translatesAutoresizingMaskIntoConstraints = false
doneButton.topAnchor.constraint(equalTo: guide.topAnchor, constant:10).isActive = true
doneButton.heightAnchor.constraint(equalToConstant: doneButtonHeight).isActive = true
doneButton.widthAnchor.constraint(equalToConstant: doneButtonWidth).isActive = true
doneButton.rightAnchor.constraint(equalTo: guide.rightAnchor, constant: -15).isActive = true
webView.translatesAutoresizingMaskIntoConstraints = false
webView.topAnchor.constraint(equalTo: guide.topAnchor, constant:0).isActive = true
webView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant:0).isActive = true
webView.leftAnchor.constraint(equalTo: guide.leftAnchor, constant:20).isActive = true
webView.rightAnchor.constraint(equalTo: guide.rightAnchor, constant:-20).isActive = true
super.viewDidLoad()
}
func createContactButtonForAbout() {
let aboutMoreButton = UIButton(type: .system)
let aboutMoreButtonHeight: CGFloat = 50
aboutMoreButton.setTitleColor(UIColor.white, for: .normal)
aboutMoreButton.setTitle(NSLocalizedString("Visit cogecopeer1.com", comment: ""), for: .normal)
aboutMoreButton.backgroundColor = Theme.primary
aboutMoreButton.titleLabel?.font = UIFont(name: Theme.fontNameLight, size: 19)!
var contactButtonWidth: CGFloat = UIScreen.main.bounds.size.width
if UIScreen.main.bounds.size.width > 300 {
contactButtonWidth = 300
}
aboutMoreButton.layer.cornerRadius = aboutMoreButton.frame.size.height / 2
aboutMoreButton.addTarget(self, action: #selector(self.aboutMore), for: .touchUpInside)
self.aboutMoreButton = aboutMoreButton
view.addSubview(aboutMoreButton)
aboutMoreButton.translatesAutoresizingMaskIntoConstraints = false
let guide = self.view.safeAreaLayoutGuide
aboutMoreButton.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant:-10).isActive = true
aboutMoreButton.heightAnchor.constraint(equalToConstant: aboutMoreButtonHeight).isActive = true
aboutMoreButton.widthAnchor.constraint(equalToConstant: contactButtonWidth).isActive = true
aboutMoreButton.centerXAnchor.constraint(equalToSystemSpacingAfter: guide.centerXAnchor, multiplier: 1.0).isActive = true
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
UIView.animate(withDuration: 0.25, animations: {() -> Void in
webView.alpha = 1.0
})
webView.scrollView.flashScrollIndicators()
if (informationType == "about") {
createContactButtonForAbout()
}
}
@IBAction func close(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func aboutMore(_ sender: Any) {
dismiss(animated: false)
let sel = #selector(ViewController.moreAboutCogeco)
if delegate?.responds(to: sel) ?? false {
_ = delegate?.perform(sel)
}
}
public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIDevice.current.userInterfaceIdiom == .pad ? .all : .portrait
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
}
| mit | 14d88a910dbc2e8cc335756bb6bc4a9a | 36.821053 | 129 | 0.665878 | 5.049895 | false | false | false | false |
selfzhou/Swift3 | Playground/Swift3-II.playground/Pages/Subscript.xcplaygroundpage/Contents.swift | 1 | 1246 | //: [Previous](@previous)
import Foundation
/*
subscript(index: Int) -> Int {
get {
// 返回一个适当的 Int 类型的值
}
set(newValue) {
// 执行适当的赋值操作
}
}
*/
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
threeTimesTable[6]
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row: row, column: column), "index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row: row, column: column), "index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
| mit | c5ed39c27dcc6135304db558548fda7a | 21.754717 | 86 | 0.563018 | 3.654545 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00161-swift-tupletype-get.swift | 1 | 1104 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
import Foundation
class ed<a>: NSObject {
var o: a
y(o: a) {
r.o = o
b.y()
}
}
protocol dc {
typealias t
func v(t)
}
struct v<l> : dc {
func v(v: v.u) {
}
}
func ^(x: j, s) -> s {
typealias w
typealias m = w
typealias v = w
}
class v<o : k, cb : k n o.dc == cb> : x {
}
class v<o, cb> {
}
protocol k {
typealias dc
}
class x {
typealias v = v
}
enum m<a> {
w cb(a, () -> ())
}
protocol v {
class func m()
}
struct k {
var w: v.u
func m() {
w.m()
}
}
protocol dc {
}
struct t : dc {
}
struct cb<k, p: dc n k.cb == p> {
}
struct w<v : m, dc: m n dc.o == v.o> {
}
protocol m {
q v {
w k
}
}
class dc<a : dc
| apache-2.0 | 921581da2e0965d2538c88b1488d8796 | 15.984615 | 79 | 0.561594 | 2.838046 | false | false | false | false |
finngaida/spotify2applemusic | Pods/Sweeft/Sources/Sweeft/Promises/Promise.swift | 1 | 5091 | //
// Promise.swift
//
// Created by Mathias Quintero on 12/2/16.
//
//
import Foundation
public typealias ResultPromise<R> = Promise<R, AnyError>
enum PromiseState<T, E: Error> {
case waiting
case success(result: T)
case error(error: E)
var isDone: Bool {
switch self {
case .waiting:
return false
default:
return true
}
}
var result: T? {
switch self {
case .success(let result):
return result
default:
return nil
}
}
var error: E? {
switch self {
case .error(let error):
return error
default:
return nil
}
}
}
public protocol PromiseBody {
associatedtype Result
associatedtype ErrorType: Error
func onSuccess<O>(call handler: @escaping (Result) -> (O)) -> PromiseSuccessHandler<O, Result, ErrorType>
func onError<O>(call handler: @escaping (ErrorType) -> (O)) -> PromiseErrorHandler<O, Result, ErrorType>
func nest<V>(to promise: Promise<V, ErrorType>, using mapper: @escaping (Result) -> (V))
func nest<V>(to promise: Promise<V, ErrorType>, using mapper: @escaping (Result) -> ())
}
/// Promise Structs to prevent you from nesting callbacks over and over again
public class Promise<T, E: Error>: PromiseBody {
/// Type of the success
typealias SuccessHandler = (T) -> ()
/// Type of the success
typealias ErrorHandler = (E) -> ()
/// All the handlers
var successHandlers = [SuccessHandler]()
var errorHandlers = [ErrorHandler]()
var state: PromiseState<T, E> = .waiting
let completionQueue: DispatchQueue
/// Initializer
public init(completionQueue: DispatchQueue = .main) {
self.completionQueue = completionQueue
}
/**
Add success handler
- Parameter handler: function that should be called
- Returns: PromiseHandler Object
*/
@discardableResult public func onSuccess<O>(call handler: @escaping (T) -> (O)) -> PromiseSuccessHandler<O, T, E> {
return PromiseSuccessHandler<O, T, E>(promise: self, handler: handler)
}
/// Add an error Handler
@discardableResult public func onError<O>(call handler: @escaping (E) -> (O)) -> PromiseErrorHandler<O, T, E> {
return PromiseErrorHandler<O, T, E>(promise: self, handler: handler)
}
/// Call this when the promise is fulfilled
public func success(with value: T) {
guard !state.isDone else {
return
}
state = .success(result: value)
let count = self.successHandlers.count
completionQueue >>> {
self.successHandlers.array(withFirst: count) => apply(value: value)
}
}
/// Call this when the promise has an error
public func error(with value: E) {
guard !state.isDone else {
return
}
state = .error(error: value)
let count = self.errorHandlers.count
completionQueue >>> {
self.errorHandlers.array(withFirst: count) => apply(value: value)
}
}
/// Will nest a promise inside another one
public func nest<V>(to promise: Promise<V, E>, using mapper: @escaping (T) -> (V)) {
onSuccess(call: mapper >>> promise.success)
onError(call: promise.error)
}
/// Will nest a promise inside another one
public func nest<V>(to promise: Promise<V, E>, using mapper: @escaping (T) -> ()) {
onSuccess(call: mapper)
onError(call: promise.error)
}
/// Will create a Promise that is based on this promise but maps the result
public func nested<V>(_ mapper: @escaping (T) -> V) -> Promise<V, E> {
let promise = Promise<V, E>(completionQueue: completionQueue)
nest(to: promise, using: mapper)
return promise
}
/// Will create a Promise that is based on this promise but maps the result
public func nested<V>(_ mapper: @escaping (T, Promise<V, E>) -> ()) -> Promise<V, E> {
let promise = Promise<V, E>(completionQueue: completionQueue)
nest(to: promise, using: add(trailing: promise) >>> mapper)
return promise
}
public func generalizeError() -> Promise<T, AnyError> {
let promise = Promise<T, AnyError>(completionQueue: completionQueue)
onSuccess(call: promise.success)
onError(call: AnyError.error >>> promise.error)
return promise
}
/**
Turns an asynchrounous handler into a synchrounous one.
Warning! This can result really badly. Be very careful when calling this.
- Returns: Result of your promise
*/
public func wait() throws -> T {
let group = DispatchGroup()
group.enter()
onSuccess { _ in
group.leave()
}
onError { _ in
group.leave()
}
group.wait()
if let result = state.result {
return result
}
throw state.error!
}
}
| mit | 8ca1b9d8c613cd6d8e10ae798616c2cf | 29.12426 | 119 | 0.591043 | 4.403979 | false | false | false | false |
nghiaphunguyen/NKit | NKit/Source/CustomViews/NKGradientView.swift | 1 | 1026 | //
// NKGradientView.swift
//
// Created by Nghia Nguyen on 2/23/16.
//
import UIKit
open class NKGradientView: UIView {
private lazy var gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
self.layer.insertSublayer(layer, at: 0)
return layer
}()
private var cgColors = [CGColor]()
open var colors = [UIColor]() {
didSet {
cgColors.removeAll()
for color in self.colors {
cgColors.append(color.cgColor)
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
self.gradientLayer.frame = rect
self.gradientLayer.colors = self.cgColors
}
}
| mit | 1d7b04bfd12796768d61e207b1e0e92b | 20.829787 | 55 | 0.566277 | 4.56 | false | false | false | false |
HeMet/LSSTools | Sources/ifconvert/Driver.swift | 1 | 735 | //
// Driver.swift
// LSS
//
// Created by Evgeniy Gubin on 05.02.17.
//
//
import Foundation
class Driver {
let fileManager: FileManagerProtocol = FileManager.default;
let converter = ItemFilterConverter()
func run(args: [String]) throws {
guard args.count > 1 else {
print("ifconvert <input file> [output file]")
return;
}
let inputFile = args[1];
let outputFile = (args.count > 2) ? args[2] : inputFile.replacingExtension(with: "lss")
let input = try fileManager.readString(file: inputFile)
let output = try converter.convert(itemFilter: input)
try fileManager.write(string: output, to: outputFile)
}
}
| mit | 4a481e6e1359434965aed8af2fdc0520 | 24.344828 | 95 | 0.602721 | 4.060773 | false | false | false | false |
richmondwatkins/RWCoreDataViewer | RWCoreDataViewer/RWManagedObjectContextExtension.swift | 1 | 3038 | //
// ManagedObjectContextExtension.swift
// DebuggerTester
//
// Created by Watkins, Richmond on 4/15/16.
// Copyright © 2016 Asurion. All rights reserved.
//
import CoreData
public extension NSManagedObjectContext {
public func initDebugView() {
RWCoreDataViewer.initialize(self)
}
public func toJSON() -> String? {
let entities: [String: NSEntityDescription] = self.persistentStoreCoordinator!.managedObjectModel.entitiesByName
let userDictionary: NSMutableDictionary = NSMutableDictionary()
let entityDictionary: NSMutableDictionary = NSMutableDictionary()
userDictionary.setObject(entityDictionary, forKey: "Entities" as NSCopying)
// Loop through and fetch entities
for (entityName, _) in entities {
let entityDescription: NSEntityDescription = NSEntityDescription.entity(forEntityName: entityName, in: self)!
let fetchRequest = NSFetchRequest<NSManagedObject>()
fetchRequest.entity = entityDescription
do {
let results: NSArray = try self.persistentStoreCoordinator!.execute(fetchRequest, with: self) as! NSArray
let resultsMutArray: NSMutableArray = NSMutableArray()
// Loops through each manage object from the fetch above, creates a dictionary out
// of all of its values and keys and then puts it into an array
for result in results as! [NSManagedObject] {
let attrDictionary: NSMutableDictionary = NSMutableDictionary()
let entity: NSEntityDescription = result.entity
let attributes: NSDictionary = entity.attributesByName as NSDictionary
for (attr, _) in attributes as! [String: NSAttributeDescription] {
attrDictionary.setObject("\(result.value(forKey: attr))", forKey: attr as NSCopying)
}
resultsMutArray.add(attrDictionary)
}
// adds array from above to a dictionary that holds all of the values for the entity
// that is currently being looped through
entityDictionary.setObject(resultsMutArray, forKey: entityName as NSCopying)
} catch {
return nil
}
}
do {
let theJSONData = try JSONSerialization.data(
withJSONObject: userDictionary,
options: JSONSerialization.WritingOptions(rawValue: 0))
return NSString(data: theJSONData,
encoding: String.Encoding.ascii.rawValue) as? String
} catch {
return nil
}
}
}
| mit | c70212d3aeffbe54d6ac8392b5f2fb97 | 37.935897 | 121 | 0.560751 | 6.573593 | false | false | false | false |
OscarSwanros/swift | test/Serialization/always_inline.swift | 3 | 1434 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_always_inline.swift
// RUN: llvm-bcanalyzer %t/def_always_inline.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -sil-link-all -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_always_inline
// SIL-LABEL: sil @main
// SIL: [[RAW:%.+]] = global_addr @_T013always_inline3rawSbvp : $*Bool
// SIL: [[FUNC:%.+]] = function_ref @_T017def_always_inline16testAlwaysInlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
// SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
var raw = testAlwaysInline(x: false)
// SIL: [[FUNC2:%.+]] = function_ref @_T017def_always_inline22AlwaysInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct
// SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct
var a = AlwaysInlineInitStruct(x: false)
// SIL-LABEL: [always_inline] @_T017def_always_inline16testAlwaysInlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
// SIL-LABEL: sil public_external [serialized] [always_inline] @_T017def_always_inline22AlwaysInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct {
| apache-2.0 | 762c796e6b0b982e2fbd085198eb42d6 | 56.36 | 215 | 0.700139 | 3.382075 | false | true | false | false |
Mclarenyang/medicine_aid | medicine aid/tabBarViewController.swift | 1 | 2274 | //
// tabBarViewController.swift
// medicine aid
//
// Created by nexuslink mac 2 on 2017/5/11.
// Copyright © 2017年 NMID. All rights reserved.
//
import UIKit
class TabBarViewController: UITabBarController,TabBarDelegate{
weak var customTabBar = TabBar()
override func viewDidLoad() {
super.viewDidLoad()
setupTabbar()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
for child in self.tabBar.subviews {
if child.isKind(of: UIControl.self) {
child.removeFromSuperview()
}
}
}
func setupTabbar() -> Void {
/// 生成
let customTabBar = TabBar.init(frame: self.tabBar.bounds)
customTabBar.tabbarDelegate = self
self.tabBar.addSubview(customTabBar)
self.customTabBar = customTabBar
}
// MARK:TabBarDelegate
func tabbar(_ tabbar: TabBar, formWhichItem: Int, toWhichItem: Int) {
self.selectedIndex = toWhichItem
}
func setupChildVC(_ childVC: UIViewController,title: String,imageName: String,selectImageName: String){
childVC.title = title
childVC.tabBarItem.image = UIImage.init(named: imageName)
// 不再渲染图片
childVC.tabBarItem.selectedImage = UIImage.init(named: selectImageName)?.withRenderingMode(.alwaysOriginal)
let navigationCtrl = UINavigationController(rootViewController: childVC)
self.addChildViewController(navigationCtrl)
// 添加tabbar内部按钮
self.customTabBar!.addTabbarButtonWith(childVC.tabBarItem)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 29a1415607974a2e53d23dcf9994764b | 28.906667 | 115 | 0.647793 | 5.051802 | false | false | false | false |
iandundas/ReactiveKitSwappableDatasource | Example/ReactiveKitSwappableDatasource/ViewController.swift | 1 | 2620 | //
// ViewController.swift
// ReactiveKitSwappableDatasource
//
// Created by Ian Dundas on 05/15/2016.
// Copyright (c) 2016 Ian Dundas. All rights reserved.
//
import UIKit
import ReactiveUIKit
import ReactiveKit
import RealmSwift
import ReactiveKitSwappableDatasource
enum DemoDataSourceType{
case Manual, Realm
var datasource: AnyDataSource<Cat> {
switch self {
case Manual:
let collection = [
Cat(value: ["name" : "Mr Timpy", "miceEaten": 8]),
Cat(value: ["name" : "Tumpy", "miceEaten": 3]),
Cat(value: ["name" : "Whiskers", "miceEaten": 30]),
Cat(value: ["name" : "Meow Now", "miceEaten": 10]), ]
return AnyDataSource(ManualDataSource<Cat>(items: collection))
case .Realm:
let realm = try! RealmSwift.Realm(configuration: RealmSwift.Realm.Configuration(inMemoryIdentifier: "MyInMemoryRealm"))
let result = realm.objects(Cat).sorted("miceEaten")
return AnyDataSource(RealmDataSource(collection: result))
}
}
}
class ViewController: UITableViewController {
let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "MyInMemoryRealm"))
var datasourceContainer:DatasourceContainer<Cat>!
var datasourceType = DemoDataSourceType.Manual
override func viewDidLoad() {
super.viewDidLoad()
let datasource = datasourceType.datasource
datasourceContainer = DatasourceContainer(datasource: datasource)
datasourceContainer.collection.bindTo(tableView) {
(indexPath, items, tableView) -> UITableViewCell in
let item = items[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = item.name
return cell
}.disposeIn(rBag)
}
// MARK: Actions:
// Insert a cat into realm
@IBAction func tappedA(sender: AnyObject) {
let cat = Cat(value: ["name" : "Mr Timpy", "miceEaten": 8])
try! realm.write {
realm.add(cat, update: true)
}
}
// Change to another data source
@IBAction func tappedB(sender: AnyObject) {
switch (datasourceType){
case .Manual:
datasourceType = .Realm
case .Realm:
datasourceType = .Manual
}
datasourceContainer.datasource = datasourceType.datasource
}
}
| mit | ed5e56703132d9e090c1dcff94785202 | 28.111111 | 131 | 0.601145 | 4.878957 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/StringCore.swift | 2 | 23263 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The core implementation of a highly-optimizable String that
/// can store both ASCII and UTF-16, and can wrap native Swift
/// _StringBuffer or NSString instances.
///
/// Usage note: when elements are 8 bits wide, this code may
/// dereference one past the end of the byte array that it owns, so
/// make sure that storage is allocated! You want a null terminator
/// anyway, so it shouldn't be a burden.
//
// Implementation note: We try hard to avoid branches in this code, so
// for example we use integer math to avoid switching on the element
// size with the ternary operator. This is also the cause of the
// extra element requirement for 8 bit elements. See the
// implementation of subscript(Int) -> UTF16.CodeUnit below for details.
@_fixed_layout
public struct _StringCore {
//===--------------------------------------------------------------------===//
// Internals
public var _baseAddress: OpaquePointer?
var _countAndFlags: UInt
public var _owner: AnyObject?
/// (private) create the implementation of a string from its component parts.
init(
baseAddress: OpaquePointer?,
_countAndFlags: UInt,
owner: AnyObject?
) {
self._baseAddress = baseAddress
self._countAndFlags = _countAndFlags
self._owner = owner
_invariantCheck()
}
func _invariantCheck() {
// Note: this code is intentionally #if'ed out. It unconditionally
// accesses lazily initialized globals, and thus it is a performance burden
// in non-checked builds.
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(count >= 0)
if _baseAddress == nil {
#if _runtime(_ObjC)
_sanityCheck(hasCocoaBuffer,
"Only opaque cocoa strings may have a null base pointer")
#endif
_sanityCheck(elementWidth == 2,
"Opaque cocoa strings should have an elementWidth of 2")
}
else if _baseAddress == _emptyStringBase {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(count == 0, "Empty string storage with non-zero count")
_sanityCheck(_owner == nil, "String pointing at empty storage has owner")
}
else if let buffer = nativeBuffer {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(elementWidth == buffer.elementWidth,
"_StringCore elementWidth doesn't match its buffer's")
_sanityCheck(UnsafeMutablePointer(_baseAddress!) >= buffer.start)
_sanityCheck(UnsafeMutablePointer(_baseAddress!) <= buffer.usedEnd)
_sanityCheck(
UnsafeMutablePointer(_pointer(toElementAt: count)) <= buffer.usedEnd)
}
#endif
}
/// Bitmask for the count part of `_countAndFlags`.
var _countMask: UInt {
return UInt.max >> 2
}
/// Bitmask for the flags part of `_countAndFlags`.
var _flagMask: UInt {
return ~_countMask
}
/// Value by which to multiply a 2nd byte fetched in order to
/// assemble a UTF-16 code unit from our contiguous storage. If we
/// store ASCII, this will be zero. Otherwise, it will be 0x100.
var _highByteMultiplier: UTF16.CodeUnit {
return UTF16.CodeUnit(elementShift) << 8
}
/// Returns a pointer to the Nth element of contiguous
/// storage. Caveats: The string must have contiguous storage; the
/// element may be 1 or 2 bytes wide, depending on elementWidth; the
/// result may be null if the string is empty.
func _pointer(toElementAt n: Int) -> OpaquePointer {
_sanityCheck(hasContiguousStorage && n >= 0 && n <= count)
return OpaquePointer(
UnsafeMutablePointer<_RawByte>(_baseAddress!) + (n << elementShift))
}
static func _copyElements(
_ srcStart: OpaquePointer, srcElementWidth: Int,
dstStart: OpaquePointer, dstElementWidth: Int,
count: Int
) {
// Copy the old stuff into the new storage
if _fastPath(srcElementWidth == dstElementWidth) {
// No change in storage width; we can use memcpy
_memcpy(
dest: UnsafeMutablePointer(dstStart),
src: UnsafeMutablePointer(srcStart),
size: UInt(count << (srcElementWidth - 1)))
}
else if (srcElementWidth < dstElementWidth) {
// Widening ASCII to UTF-16; we need to copy the bytes manually
var dest = UnsafeMutablePointer<UTF16.CodeUnit>(dstStart)
var src = UnsafeMutablePointer<UTF8.CodeUnit>(srcStart)
let srcEnd = src + count
while (src != srcEnd) {
dest.pointee = UTF16.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
else {
// Narrowing UTF-16 to ASCII; we need to copy the bytes manually
var dest = UnsafeMutablePointer<UTF8.CodeUnit>(dstStart)
var src = UnsafeMutablePointer<UTF16.CodeUnit>(srcStart)
let srcEnd = src + count
while (src != srcEnd) {
dest.pointee = UTF8.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
}
//===--------------------------------------------------------------------===//
// Initialization
public init(
baseAddress: OpaquePointer?,
count: Int,
elementShift: Int,
hasCocoaBuffer: Bool,
owner: AnyObject?
) {
_sanityCheck(elementShift == 0 || elementShift == 1)
self._baseAddress = baseAddress
self._countAndFlags
= (UInt(elementShift) << (UInt._sizeInBits - 1))
| ((hasCocoaBuffer ? 1 : 0) << (UInt._sizeInBits - 2))
| UInt(count)
self._owner = owner
_sanityCheck(UInt(count) & _flagMask == 0, "String too long to represent")
_invariantCheck()
}
/// Create a _StringCore that covers the entire length of the _StringBuffer.
init(_ buffer: _StringBuffer) {
self = _StringCore(
baseAddress: OpaquePointer(buffer.start),
count: buffer.usedCount,
elementShift: buffer.elementShift,
hasCocoaBuffer: false,
owner: buffer._anyObject
)
}
/// Create the implementation of an empty string.
///
/// - Note: There is no null terminator in an empty string.
public init() {
self._baseAddress = _emptyStringBase
self._countAndFlags = 0
self._owner = nil
_invariantCheck()
}
//===--------------------------------------------------------------------===//
// Properties
/// The number of elements stored
/// - Complexity: O(1).
public var count: Int {
get {
return Int(_countAndFlags & _countMask)
}
set(newValue) {
_sanityCheck(UInt(newValue) & _flagMask == 0)
_countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue)
}
}
/// Left shift amount to apply to an offset N so that when
/// added to a UnsafeMutablePointer<_RawByte>, it traverses N elements.
var elementShift: Int {
return Int(_countAndFlags >> (UInt._sizeInBits - 1))
}
/// The number of bytes per element.
///
/// If the string does not have an ASCII buffer available (including the case
/// when we don't have a utf16 buffer) then it equals 2.
public var elementWidth: Int {
return elementShift &+ 1
}
public var hasContiguousStorage: Bool {
#if _runtime(_ObjC)
return _fastPath(_baseAddress != nil)
#else
return true
#endif
}
/// Are we using an `NSString` for storage?
public var hasCocoaBuffer: Bool {
return Int((_countAndFlags << 1)._value) < 0
}
public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> {
_sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII")
return UnsafeMutablePointer(_baseAddress!)
}
/// True iff a contiguous ASCII buffer available.
public var isASCII: Bool {
return elementWidth == 1
}
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
_sanityCheck(
count == 0 || elementWidth == 2,
"String does not contain contiguous UTF-16")
return UnsafeMutablePointer(_baseAddress!)
}
/// the native _StringBuffer, if any, or `nil`.
public var nativeBuffer: _StringBuffer? {
if !hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, to: _StringBuffer.self)
}
}
return nil
}
#if _runtime(_ObjC)
/// the Cocoa String buffer, if any, or `nil`.
public var cocoaBuffer: _CocoaString? {
if hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, to: _CocoaString.self)
}
}
return nil
}
#endif
//===--------------------------------------------------------------------===//
// slicing
/// Returns the given sub-`_StringCore`.
public subscript(bounds: Range<Int>) -> _StringCore {
_precondition(
bounds.lowerBound >= 0,
"subscript: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"subscript: subrange extends past String end")
let newCount = bounds.upperBound - bounds.lowerBound
_sanityCheck(UInt(newCount) & _flagMask == 0)
if hasContiguousStorage {
return _StringCore(
baseAddress: _pointer(toElementAt: bounds.lowerBound),
_countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount),
owner: _owner)
}
#if _runtime(_ObjC)
return _cocoaStringSlice(self, bounds)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
@_versioned
func _nthContiguous(_ position: Int) -> UTF16.CodeUnit {
let p =
UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue)
// Always dereference two bytes, but when elements are 8 bits we
// multiply the high byte by 0.
// FIXME(performance): use masking instead of multiplication.
return UTF16.CodeUnit(p.pointee)
+ UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier
}
/// Get the Nth UTF-16 Code Unit stored.
public subscript(position: Int) -> UTF16.CodeUnit {
@inline(__always)
get {
_precondition(
position >= 0,
"subscript: index precedes String start")
_precondition(
position <= count,
"subscript: index points past String end")
if _fastPath(_baseAddress != nil) {
return _nthContiguous(position)
}
#if _runtime(_ObjC)
return _cocoaStringSubscript(self, position)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
}
/// Write the string, in the given encoding, to output.
func encode<
Encoding: UnicodeCodec
>(_ encoding: Encoding.Type, output: @noescape (Encoding.CodeUnit) -> Void)
{
if _fastPath(_baseAddress != nil) {
if _fastPath(elementWidth == 1) {
for x in UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(_baseAddress!),
count: count
) {
Encoding.encode(UnicodeScalar(UInt32(x)), sendingOutputTo: output)
}
}
else {
let hadError = transcode(
UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress!),
count: count
).makeIterator(),
from: UTF16.self,
to: encoding,
stoppingOnError: true,
sendingOutputTo: output
)
_sanityCheck(!hadError, "Swift.String with native storage should not have unpaired surrogates")
}
}
else if (hasCocoaBuffer) {
#if _runtime(_ObjC)
_StringCore(
_cocoaStringToContiguous(
source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0)
).encode(encoding, output: output)
#else
_sanityCheckFailure("encode: non-native string without objc runtime")
#endif
}
}
/// Attempt to claim unused capacity in the String's existing
/// native buffer, if any. Return zero and a pointer to the claimed
/// storage if successful. Otherwise, returns a suggested new
/// capacity and a null pointer.
///
/// - Note: If successful, effectively appends garbage to the String
/// until it has newSize UTF-16 code units; you must immediately copy
/// valid UTF-16 into that storage.
///
/// - Note: If unsuccessful because of insufficient space in an
/// existing buffer, the suggested new capacity will at least double
/// the existing buffer's storage.
mutating func _claimCapacity(
_ newSize: Int, minElementWidth: Int) -> (Int, OpaquePointer?) {
if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) {
var buffer = nativeBuffer!
// In order to grow the substring in place, this _StringCore should point
// at the substring at the end of a _StringBuffer. Otherwise, some other
// String is using parts of the buffer beyond our last byte.
let usedStart = _pointer(toElementAt:0)
let usedEnd = _pointer(toElementAt:count)
// Attempt to claim unused capacity in the buffer
if _fastPath(
buffer.grow(
oldBounds: UnsafePointer(usedStart)..<UnsafePointer(usedEnd),
newUsedCount: newSize)
) {
count = newSize
return (0, usedEnd)
}
else if newSize > buffer.capacity {
// Growth failed because of insufficient storage; double the size
return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil)
}
}
return (newSize, nil)
}
/// Ensure that this String references a _StringBuffer having
/// a capacity of at least newSize elements of at least the given width.
/// Effectively appends garbage to the String until it has newSize
/// UTF-16 code units. Returns a pointer to the garbage code units;
/// you must immediately copy valid data into that storage.
mutating func _growBuffer(
_ newSize: Int, minElementWidth: Int
) -> OpaquePointer {
let (newCapacity, existingStorage)
= _claimCapacity(newSize, minElementWidth: minElementWidth)
if _fastPath(existingStorage != nil) {
return existingStorage!
}
let oldCount = count
_copyInPlace(
newSize: newSize,
newCapacity: newCapacity,
minElementWidth: minElementWidth)
return _pointer(toElementAt:oldCount)
}
/// Replace the storage of self with a native _StringBuffer having a
/// capacity of at least newCapacity elements of at least the given
/// width. Effectively appends garbage to the String until it has
/// newSize UTF-16 code units.
mutating func _copyInPlace(
newSize: Int, newCapacity: Int, minElementWidth: Int
) {
_sanityCheck(newCapacity >= newSize)
let oldCount = count
// Allocate storage.
let newElementWidth =
minElementWidth >= elementWidth
? minElementWidth
: isRepresentableAsASCII() ? 1 : 2
let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize,
elementWidth: newElementWidth)
if hasContiguousStorage {
_StringCore._copyElements(
_baseAddress!, srcElementWidth: elementWidth,
dstStart: OpaquePointer(newStorage.start),
dstElementWidth: newElementWidth, count: oldCount)
}
else {
#if _runtime(_ObjC)
// Opaque cocoa buffers might not store ASCII, so assert that
// we've allocated for 2-byte elements.
// FIXME: can we get Cocoa to tell us quickly that an opaque
// string is ASCII? Do we care much about that edge case?
_sanityCheck(newStorage.elementShift == 1)
_cocoaStringReadAll(cocoaBuffer!, UnsafeMutablePointer(newStorage.start))
#else
_sanityCheckFailure("_copyInPlace: non-native string without objc runtime")
#endif
}
self = _StringCore(newStorage)
}
/// Append `c` to `self`.
///
/// - Complexity: O(1) when amortized over repeated appends of equal
/// character values.
mutating func append(_ c: UnicodeScalar) {
let width = UTF16.width(c)
append(
width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value),
width == 2 ? UTF16.trailSurrogate(c) : nil
)
}
/// Append `u` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(_ u: UTF16.CodeUnit) {
append(u, nil)
}
mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) {
_invariantCheck()
let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2
let utf16Width = u1 == nil ? 1 : 2
let destination = _growBuffer(
count + utf16Width, minElementWidth: minBytesPerCodeUnit)
if _fastPath(elementWidth == 1) {
_sanityCheck(
_pointer(toElementAt:count)
== OpaquePointer(UnsafeMutablePointer<_RawByte>(destination) + 1))
UnsafeMutablePointer<UTF8.CodeUnit>(destination)[0] = UTF8.CodeUnit(u0)
}
else {
let destination16
= UnsafeMutablePointer<UTF16.CodeUnit>(destination._rawValue)
destination16[0] = u0
if u1 != nil {
destination16[1] = u1!
}
}
_invariantCheck()
}
@inline(never)
mutating func append(_ rhs: _StringCore) {
_invariantCheck()
let minElementWidth
= elementWidth >= rhs.elementWidth
? elementWidth
: rhs.isRepresentableAsASCII() ? 1 : 2
let destination = _growBuffer(
count + rhs.count, minElementWidth: minElementWidth)
if _fastPath(rhs.hasContiguousStorage) {
_StringCore._copyElements(
rhs._baseAddress!, srcElementWidth: rhs.elementWidth,
dstStart: destination, dstElementWidth:elementWidth, count: rhs.count)
}
else {
#if _runtime(_ObjC)
_sanityCheck(elementWidth == 2)
_cocoaStringReadAll(rhs.cocoaBuffer!, UnsafeMutablePointer(destination))
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
_invariantCheck()
}
/// Returns `true` iff the contents of this string can be
/// represented as pure ASCII.
///
/// - Complexity: O(N) in the worst case.
func isRepresentableAsASCII() -> Bool {
if _slowPath(!hasContiguousStorage) {
return false
}
if _fastPath(elementWidth == 1) {
return true
}
let unsafeBuffer =
UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress),
count: count)
return !unsafeBuffer.contains { $0 > 0x7f }
}
}
extension _StringCore : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
public // @testable
var startIndex: Int {
return 0
}
public // @testable
var endIndex: Int {
return count
}
}
extension _StringCore : RangeReplaceableCollection {
/// Replace the elements within `bounds` with `newElements`.
///
/// - Complexity: O(`bounds.count`) if `bounds.upperBound
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceSubrange<C>(
_ bounds: Range<Int>,
with newElements: C
) where C : Collection, C.Iterator.Element == UTF16.CodeUnit {
_precondition(
bounds.lowerBound >= 0,
"replaceSubrange: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"replaceSubrange: subrange extends past String end")
let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1
let replacementCount = numericCast(newElements.count) as Int
let replacedCount = bounds.count
let tailCount = count - bounds.upperBound
let growth = replacementCount - replacedCount
let newCount = count + growth
// Successfully claiming capacity only ensures that we can modify
// the newly-claimed storage without observably mutating other
// strings, i.e., when we're appending. Already-used characters
// can only be mutated when we have a unique reference to the
// buffer.
let appending = bounds.lowerBound == endIndex
let existingStorage = !hasCocoaBuffer && (
appending || isUniquelyReferencedNonObjC(&_owner)
) ? _claimCapacity(newCount, minElementWidth: width).1 : nil
if _fastPath(existingStorage != nil) {
let rangeStart = UnsafeMutablePointer<UInt8>(
_pointer(toElementAt:bounds.lowerBound))
let tailStart = rangeStart + (replacedCount << elementShift)
if growth > 0 {
(tailStart + (growth << elementShift)).assignBackwardFrom(
tailStart, count: tailCount << elementShift)
}
if _fastPath(elementWidth == 1) {
var dst = rangeStart
for u in newElements {
dst.pointee = UInt8(truncatingBitPattern: u)
dst += 1
}
}
else {
var dst = UnsafeMutablePointer<UTF16.CodeUnit>(rangeStart)
for u in newElements {
dst.pointee = u
dst += 1
}
}
if growth < 0 {
(tailStart + (growth << elementShift)).assignFrom(
tailStart, count: tailCount << elementShift)
}
}
else {
var r = _StringCore(
_StringBuffer(
capacity: newCount,
initialSize: 0,
elementWidth:
width == 1 ? 1
: isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1
: 2
))
r.append(contentsOf: self[0..<bounds.lowerBound])
r.append(contentsOf: newElements)
r.append(contentsOf: self[bounds.upperBound..<count])
self = r
}
}
public mutating func reserveCapacity(_ n: Int) {
if _fastPath(!hasCocoaBuffer) {
if _fastPath(isUniquelyReferencedNonObjC(&_owner)) {
let bounds: Range<UnsafePointer<_RawByte>>
= UnsafePointer(_pointer(toElementAt:0))..<UnsafePointer(_pointer(toElementAt:count))
if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) {
return
}
}
}
_copyInPlace(
newSize: count,
newCapacity: Swift.max(count, n),
minElementWidth: 1)
}
public mutating func append<S : Sequence>(contentsOf s: S)
where S.Iterator.Element == UTF16.CodeUnit {
var width = elementWidth
if width == 1 {
if let hasNonAscii = s._preprocessingPass({
s.contains { $0 > 0x7f }
}) {
width = hasNonAscii ? 2 : 1
}
}
let growth = s.underestimatedCount
var iter = s.makeIterator()
if _fastPath(growth > 0) {
let newSize = count + growth
let destination = _growBuffer(newSize, minElementWidth: width)
if elementWidth == 1 {
let destination8 = UnsafeMutablePointer<UTF8.CodeUnit>(destination)
for i in 0..<growth {
destination8[i] = UTF8.CodeUnit(iter.next()!)
}
}
else {
let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination)
for i in 0..<growth {
destination16[i] = iter.next()!
}
}
}
// Append any remaining elements
for u in IteratorSequence(iter) {
self.append(u)
}
}
}
// Used to support a tighter invariant: all strings with contiguous
// storage have a non-NULL base address.
var _emptyStringStorage: UInt32 = 0
var _emptyStringBase: OpaquePointer {
return OpaquePointer(
UnsafeMutablePointer<UInt16>(Builtin.addressof(&_emptyStringStorage)))
}
| apache-2.0 | e070e8d6366fbbdb1c3d67aa98e09bc2 | 30.910837 | 103 | 0.638955 | 4.629453 | false | false | false | false |
mitsuyoshi-yamazaki/SwarmChemistry | Demo/SwarmRenderView.swift | 1 | 2639 | //
// SwarmRenderView.swift
// SwarmChemistry
//
// Created by Yamazaki Mitsuyoshi on 2017/08/10.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
import SwarmChemistry
final class SwarmRenderView: View {
var cellSize: CGFloat = 16.0
var population = Population.empty() {
didSet {
updateFieldSizeMultiplier()
}
}
fileprivate var fieldSizeMultiplier: CGFloat = 1.0
fileprivate var shouldClear = false
private func updateFieldSizeMultiplier() {
let fieldWidth = CGFloat(population.fieldSize.x)
let fieldHeight = CGFloat(population.fieldSize.y)
fieldSizeMultiplier = min(frame.width / fieldWidth, frame.height / fieldHeight)
}
// MARK: - Draw
#if os(iOS) || os(watchOS) || os(tvOS)
override func layoutSubviews() {
super.layoutSubviews()
updateFieldSizeMultiplier()
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
fatalError("Unexpectedly found nil in UIGraphicsGetCurrentContext()")
}
draw(with: context)
}
#elseif os(macOS)
override func layout() {
super.layout()
updateFieldSizeMultiplier()
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else {
fatalError("Unexpectedly found nil in NSGraphicsContext.current")
}
draw(with: context)
}
#endif
private func draw(with context: CGContext) {
guard shouldClear == false else {
shouldClear = false
context.setFillColor(Color.white.cgColor)
context.fill(bounds)
return
}
context.setFillColor(Color(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).cgColor)
context.fill(bounds)
let fieldWidth = CGFloat(population.fieldSize.x)
let fieldHeight = CGFloat(population.fieldSize.y)
let size = cellSize * fieldSizeMultiplier
context.setFillColor(Color.white.cgColor)
context.fill(.init(x: 0.0, y: 0.0, width: fieldWidth * fieldSizeMultiplier, height: fieldHeight * fieldSizeMultiplier))
for individual in population.population {
individual.genome.color.setFill()
context.fillEllipse(in: CGRect(x: CGFloat(individual.position.x) * fieldSizeMultiplier, y: CGFloat(individual.position.y) * fieldSizeMultiplier, width: size, height: size))
}
}
}
// MARK: - Function
extension SwarmRenderView {
func clear() {
shouldClear = true
setNeedsDisplay(bounds)
}
func convert(_ rect: CGRect) -> Vector2.Rect {
return Vector2.Rect(rect) / Value(fieldSizeMultiplier)
}
}
| mit | 57b89c28625abf9ccd8d31477844f322 | 26.479167 | 178 | 0.698635 | 4.247987 | false | false | false | false |
leuski/Coiffeur | Coiffeur/src/ui/preferences/CoiffeurPreferences.swift | 1 | 4110 | //
// CoiffeurPreferences.swift
// Coiffeur
//
// Created by Anton Leuski on 4/11/15.
// Copyright (c) 2015 Anton Leuski. 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 Foundation
class CoiffeurControllerClass: NSObject {
@objc let controllerClass: CoiffeurController.Type
var documentType: String { return controllerClass.documentType }
init(_ type: CoiffeurController.Type)
{
controllerClass = type
}
func contentsIsValidInString(_ string: String) -> Bool
{
return controllerClass.contentsIsValidInString(string)
}
func createCoiffeur() throws -> CoiffeurController
{
return try controllerClass.createCoiffeur()
}
@objc class func keyPathsForValuesAffectingCurrentExecutableURL() -> NSSet
{
return NSSet(object: "controllerClass.currentExecutableURL")
}
@objc dynamic var currentExecutableURL: URL? {
get {
return controllerClass.currentExecutableURL
}
set (value) {
willChangeValue(forKey: "currentExecutableURL")
controllerClass.currentExecutableURL = value
didChangeValue(forKey: "currentExecutableURL")
}
}
var defaultExecutableURL: URL? {
return controllerClass.defaultExecutableURL
}
@objc var executableDisplayName: String {
return controllerClass.localizedExecutableTitle
}
}
class CoiffeurPreferences: DefaultPreferencePane {
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var constraint: NSLayoutConstraint!
override var toolbarItemImage: NSImage? {
return NSImage(named: NSImage.Name(rawValue: "Locations")) }
@objc let formatters = CoiffeurController.availableTypes.map {
CoiffeurControllerClass($0) }
override func viewDidLoad() {
super.viewDidLoad()
let height = self.tableView.bounds.size.height + 2
let delta = self.tableView.enclosingScrollView?.frame.size.height ?? 0
- height
self.constraint.constant -= delta
self.view.frame.size.height -= delta
}
}
extension CoiffeurPreferences: NSTableViewDelegate {
func tableView(
_ tableView: NSTableView,
rowViewForRow row: Int) -> NSTableRowView?
{
return TransparentTableRowView()
}
}
extension CoiffeurPreferences: NSPathControlDelegate {
func pathControl(_ pathControl: NSPathControl, willPopUp menu: NSMenu)
{
if
let tcv = pathControl.superview as? NSTableCellView,
let ccc = tcv.objectValue as? CoiffeurControllerClass,
let url = ccc.defaultExecutableURL
{
let item = menu.insertItem(
withTitle: String(format: NSLocalizedString("Built-in %@", comment: ""),
url.lastPathComponent),
action: #selector(CoiffeurPreferences.selectURL(_:)),
keyEquivalent: "", at: 0)
item.representedObject = [ "class": ccc, "url": url ]
as [String: AnyObject]
}
}
@objc func selectURL(_ sender: AnyObject)
{
if
let dictionary = sender.representedObject as? [String: AnyObject],
let theClass = dictionary["class"] as? CoiffeurControllerClass
{
theClass.currentExecutableURL = dictionary["url"] as? URL
}
}
}
class TransparentTableView: NSTableView {
override func awakeFromNib()
{
self.enclosingScrollView?.drawsBackground = false
}
override var isOpaque: Bool {
return false
}
override func drawBackground(inClipRect clipRect: NSRect)
{
// don't draw a background rect
}
}
class TransparentTableRowView: NSTableRowView {
override func drawBackground(in dirtyRect: NSRect)
{
}
override var isOpaque: Bool {
return false
}
}
| apache-2.0 | 659f30deb1136a7a637cda2eb61f453d | 26.039474 | 80 | 0.710219 | 4.633596 | false | false | false | false |
GiantForJ/GYGestureUnlock | GYGestureUnlock/Classes/GYCircle.swift | 1 | 8045 | //
// GYCircle.swift
// GYGestureUnlock
//
// Created by zhuguangyang on 16/8/19.
// Copyright © 2016年 Giant. All rights reserved.
//
import UIKit
/**
单个圆的各种状态
- CircleStateNormal: 正常
- CircleStateSelected: 锁定
- CircleStateError: 错误
- CircleStateLastOneSelected: 最后一个锁定
- CircleStateLastOneError: 最后一个错误
*/
public enum CircleState:Int {
case circleStateNormal = 1
case circleStateSelected
case circleStateError
case circleStateLastOneSelected
case circleStateLastOneError
}
/**
圆的用途
- CircleTypeInfo: 正常
- CircleTypeGesture: 手势下的圆
*/
public enum CircleTye:Int {
case circleTypeInfo = 1
case circleTypeGesture
}
public class GYCircle: UIView {
/// 圆所处状态
public var _state: CircleState!
public var state:CircleState?
{
set{
_state = newValue
setNeedsDisplay()
}
get{
return _state
}
}
/// 圆的类型
public var type: CircleTye?
/// 是否带有箭头 默认有
public var isArrow:Bool = true
/// 角度 三角形的方向
public var _angle:CGFloat?
public var angle:CGFloat?
{
set {
_angle = newValue
setNeedsDisplay()
}
get {
return _angle
}
}
/// 外环颜色
public var outCircleColor: UIColor?
{
var color: UIColor?
guard let state_ = self.state else {
return CircleStateNormalOutsideColor
}
switch state_ {
case CircleState.circleStateNormal:
color = CircleStateNormalOutsideColor
case CircleState.circleStateSelected:
color = CircleStateSelectedOutsideColor
case CircleState.circleStateError:
color = CircleStateErrorOutsideColor
case CircleState.circleStateLastOneSelected:
color = CircleStateSelectedOutsideColor
case CircleState.circleStateLastOneError:
color = CircleStateErrorOutsideColor
}
return color
}
/// 实心圆颜色
var inCircleColor: UIColor?
{
var color: UIColor?
guard let state_ = self.state else {
return CircleStateNormalInsideColor
}
switch state_ {
case CircleState.circleStateNormal:
color = CircleStateNormalInsideColor
case CircleState.circleStateSelected:
color = CircleStateSelectedInsideColor
case CircleState.circleStateError:
color = CircleStateErrorInsideColor
case CircleState.circleStateLastOneSelected:
color = CircleStateSelectedInsideColor
case CircleState.circleStateLastOneError:
color = CircleStateErrorInsideColor
}
return color
}
/// 三角形颜色
var trangleColor: UIColor?
{
var color: UIColor?
guard let state_ = self.state else {
return CircleStateNormalTrangleColor
}
switch state_ {
case CircleState.circleStateNormal:
color = CircleStateNormalTrangleColor
case CircleState.circleStateSelected:
color = CircleStateSelectedTrangleColor
case CircleState.circleStateError:
color = CircleStateErrorTrangleColor
case CircleState.circleStateLastOneSelected:
color = CircleStateNormalTrangleColor
case CircleState.circleStateLastOneError:
color = CircleStateNormalTrangleColor
}
return color
}
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = CircleBackgroundColor
angle = 0
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = CircleBackgroundColor
angle = 0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = CircleBackgroundColor
angle = 0
fatalError("init(coder:) has not been implemented")
}
override public func draw(_ rect: CGRect) {
/// 获取画布
let ctx = UIGraphicsGetCurrentContext()
/// 所占圆比例
var radio:CGFloat = 0
let circleRect = CGRect(x: CircleEdgeWidth, y: CircleEdgeWidth, width: rect.size.width - 2 * CircleEdgeWidth, height: rect.size.height - 2 * CircleEdgeWidth)
if self.type == CircleTye.circleTypeGesture {
radio = CircleRadio
} else if self.type == CircleTye.circleTypeInfo {
radio = 1
}
//上下文旋转
transFormCtx(ctx!, rect: rect)
//画圆环
drawEmptyCircleWithContext(ctx!, rect: circleRect, color: self.outCircleColor!)
// 画实心圆
drawSolidCircleWithContext(ctx!, rect: rect, radio: radio, color: self.inCircleColor!)
if self.isArrow {
//画三角形箭头
drawTrangleWithContext(ctx!, point:CGPoint(x: rect.size.width/2, y: 10) , length: kTrangleLength, color: self.trangleColor!)
}
}
//MARK:- 画三角形
/**
上下文旋转
- parameter ctx: 画布
- parameter rect: Rect
*/
private func transFormCtx(_ ctx: CGContext,rect: CGRect) {
let translateXY = rect.size.width * 0.5
//平移
ctx.translateBy(x: translateXY, y: translateXY)
//已解决:- 三角形箭头指向
// angle = 2
guard angle != nil else {
return
}
ctx.rotate(by: angle!)
//再平移回来
ctx.translateBy(x: -translateXY, y: -translateXY)
}
//MARK:- 画外圆环
/**
画外圆环
- parameter ctx: 图形上下文
- parameter rect: 绘图范围
- parameter color: 绘制颜色
*/
private func drawEmptyCircleWithContext(_ ctx: CGContext,rect: CGRect,color: UIColor) {
let circlePath = CGMutablePath()
circlePath.addEllipse(in: rect)
ctx.addPath(circlePath)
color.set()
ctx.setLineWidth(CircleEdgeWidth)
ctx.strokePath()
}
//MARK:- 花实心圆
/**
画实心圆
- parameter ctx: 图形上下文
- parameter rect: 绘制范围
- parameter radio: 占大圆比例
- parameter color: 绘制颜色
*/
private func drawSolidCircleWithContext(_ ctx: CGContext,rect: CGRect, radio: CGFloat, color: UIColor) {
let circlePath = CGMutablePath()
circlePath.addEllipse(in: CGRect(x: rect.size.width / 2 * (1 - radio) + CircleEdgeWidth, y: rect.size.width / 2 * (1 - radio) + CircleEdgeWidth, width: rect.size.width * radio - CircleEdgeWidth * 2, height: rect.size.width * radio - CircleEdgeWidth * 2))
color.set()
ctx.addPath(circlePath)
ctx.fillPath()
ctx.strokePath()
}
//MARK:- 画三角形
private func drawTrangleWithContext(_ ctx: CGContext,point: CGPoint,length: CGFloat,color: UIColor) {
let trianglePathM = CGMutablePath() as CGMutablePath
//3.0+
trianglePathM.move(to: point)
trianglePathM.addLine(to: CGPoint(x: point.x - length/2, y: point.y + length/2))
trianglePathM.addLine(to: CGPoint(x: point.x + length/2, y: point.y + length/2))
ctx.addPath(trianglePathM)
color.set()
ctx.fillPath()
ctx.strokePath()
}
}
| mit | 6aff38bf5e7428b653b29274e3666863 | 24.672241 | 262 | 0.564096 | 4.936334 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Utils/AASwiftlyLRU.swift | 4 | 4605 | //
// Copyright (c) 2014 Justin M Fischer
//
// 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.
//
// Created by JUSTIN M FISCHER on 12/1/14.
// Copyright (c) 2013 Justin M Fischer. All rights reserved.
//
import Foundation
class Node<K, V> {
var next: Node?
var previous: Node?
var key: K
var value: V?
init(key: K, value: V?) {
self.key = key
self.value = value
}
}
class LinkedList<K, V> {
var head: Node<K, V>?
var tail: Node<K, V>?
init() {
}
func addToHead(_ node: Node<K, V>) {
if self.head == nil {
self.head = node
self.tail = node
} else {
let temp = self.head
self.head?.previous = node
self.head = node
self.head?.next = temp
}
}
func remove(_ node: Node<K, V>) {
if node === self.head {
if self.head?.next != nil {
self.head = self.head?.next
self.head?.previous = nil
} else {
self.head = nil
self.tail = nil
}
} else if node.next != nil {
node.previous?.next = node.next
node.next?.previous = node.previous
} else {
node.previous?.next = nil
self.tail = node.previous
}
}
func display() -> String {
var description = ""
var current = self.head
while current != nil {
description += "Key: \(current!.key) Value: \(current?.value) \n"
current = current?.next
}
return description
}
}
class AASwiftlyLRU<K : Hashable, V> : CustomStringConvertible {
let capacity: Int
var length = 0
fileprivate let queue: LinkedList<K, V>
fileprivate var hashtable: [K : Node<K, V>]
/**
Least Recently Used "LRU" Cache, capacity is the number of elements to keep in the Cache.
*/
init(capacity: Int) {
self.capacity = capacity
self.queue = LinkedList()
self.hashtable = [K : Node<K, V>](minimumCapacity: self.capacity)
}
subscript (key: K) -> V? {
get {
if let node = self.hashtable[key] {
self.queue.remove(node)
self.queue.addToHead(node)
return node.value
} else {
return nil
}
}
set(value) {
if let node = self.hashtable[key] {
node.value = value
self.queue.remove(node)
self.queue.addToHead(node)
} else {
let node = Node(key: key, value: value)
if self.length < capacity {
self.queue.addToHead(node)
self.hashtable[key] = node
self.length += 1
} else {
hashtable.removeValue(forKey: self.queue.tail!.key)
self.queue.tail = self.queue.tail?.previous
if let node = self.queue.tail {
node.next = nil
}
self.queue.addToHead(node)
self.hashtable[key] = node
}
}
}
}
var description : String {
return "SwiftlyLRU Cache(\(self.length)) \n" + self.queue.display()
}
}
| agpl-3.0 | e32b123a79821902e613b9aa054cdee2 | 28.902597 | 93 | 0.523561 | 4.505871 | false | false | false | false |
xwu/swift | test/decl/protocol/req/associated_type_inference.swift | 1 | 17173 | // RUN: %target-typecheck-verify-swift
protocol P0 {
associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
// expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
func f0(_: Assoc1)
func g0(_: Assoc1)
}
protocol PSimple { }
extension Int : PSimple { }
extension Double : PSimple { }
struct X0a : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Int) { }
}
struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}}
}
struct X0c : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0d : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Double) { } // viable, but no corresponding f0
func g0(_: Int) { }
}
struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}}
func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { }
func g0(_: Int) { }
}
struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple
func f0(_: Float) { }
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}}
func f0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0h<T : PSimple> : P0 {
func f0(_: T) { }
}
extension X0h {
func g0(_: T) { }
}
struct X0i<T : PSimple> {
}
extension X0i {
func g0(_: T) { }
}
extension X0i : P0 { }
extension X0i {
func f0(_: T) { }
}
// Protocol extension used to infer requirements
protocol P1 {
}
extension P1 {
func f0(_ x: Int) { }
func g0(_ x: Int) { }
}
struct X0j : P0, P1 { }
protocol P2 {
associatedtype P2Assoc
func h0(_ x: P2Assoc)
}
extension P2 where Self.P2Assoc : PSimple {
func f0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0k : P0, P2 {
func h0(_ x: Int) { }
}
struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}}
func h0(_ x: Float) { }
}
// Prefer declarations in the type to those in protocol extensions
struct X0m : P0, P2 {
func f0(_ x: Double) { }
func g0(_ x: Double) { }
func h0(_ x: Double) { }
}
// Inference from properties.
protocol PropertyP0 {
associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}}
var property: Prop { get }
}
struct XProp0a : PropertyP0 { // okay PropType = Int
var property: Int
}
struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}}
var property: Float // expected-note{{candidate would match and infer 'Prop' = 'Float' if 'Float' conformed to 'PSimple'}}
}
// Inference from subscripts
protocol SubscriptP0 {
associatedtype Index
// expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element : PSimple
// expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}}
// expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}}
subscript (i: Index) -> Element { get }
}
struct XSubP0a : SubscriptP0 {
subscript (i: Int) -> Int { get { return i } }
}
struct XSubP0b : SubscriptP0 {
// expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}}
subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{candidate would match and infer 'Element' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct XSubP0c : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}}
subscript (i: Index) -> Element { get { } }
}
struct XSubP0d : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}}
subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } }
}
// Inference from properties and subscripts
protocol CollectionLikeP0 {
associatedtype Index
// expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element
// expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}}
var startIndex: Index { get }
var endIndex: Index { get }
subscript (i: Index) -> Element { get }
}
struct SomeSlice<T> { }
struct XCollectionLikeP0a<T> : CollectionLikeP0 {
var startIndex: Int
var endIndex: Int
subscript (i: Int) -> T { get { fatalError("blah") } }
subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } }
}
struct XCollectionLikeP0b : CollectionLikeP0 {
// expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}}
var startIndex: XCollectionLikeP0b.Index
// There was an error @-1 ("'startIndex' used within its own type"),
// but it disappeared and doesn't seem like much of a loss.
var startElement: XCollectionLikeP0b.Element
}
// rdar://problem/21304164
public protocol Thenable {
associatedtype T // expected-note{{protocol requires nested type 'T'}}
func then(_ success: (_: T) -> T) -> Self
}
public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}}
public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self {
return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}}
return success(t: t, self)
// expected-error@-1 {{extraneous argument label 't:' in call}}
}
}
}
// rdar://problem/21559670
protocol P3 {
associatedtype Assoc = Int
associatedtype Assoc2
func foo(_ x: Assoc2) -> Assoc?
}
protocol P4 : P3 { }
extension P4 {
func foo(_ x: Int) -> Float? { return 0 }
}
extension P3 where Assoc == Int {
func foo(_ x: Int) -> Assoc? { return nil }
}
struct X4 : P4 { }
// rdar://problem/21738889
protocol P5 {
associatedtype A = Int
}
struct X5<T : P5> : P5 {
typealias A = T.A
}
protocol P6 : P5 {
associatedtype A : P5 = X5<Self>
}
extension P6 where A == X5<Self> { }
// rdar://problem/21774092
protocol P7 {
associatedtype A
associatedtype B
func f() -> A
func g() -> B
}
struct X7<T> { }
extension P7 {
func g() -> X7<A> { return X7() }
}
struct Y7<T> : P7 {
func f() -> Int { return 0 }
}
struct MyAnySequence<Element> : MySequence {
typealias SubSequence = MyAnySequence<Element>
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
struct MyAnyIterator<T> : MyIteratorType {
typealias Element = T
}
protocol MyIteratorType {
associatedtype Element
}
protocol MySequence {
associatedtype Iterator : MyIteratorType
associatedtype SubSequence
func foo() -> SubSequence
func makeIterator() -> Iterator
}
extension MySequence {
func foo() -> MyAnySequence<Iterator.Element> {
return MyAnySequence()
}
}
struct SomeStruct<Element> : MySequence {
let element: Element
init(_ element: Element) {
self.element = element
}
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
// rdar://problem/21883828 - ranking of solutions
protocol P8 {
}
protocol P9 : P8 {
}
protocol P10 {
associatedtype A
func foo() -> A
}
struct P8A { }
struct P9A { }
extension P8 {
func foo() -> P8A { return P8A() }
}
extension P9 {
func foo() -> P9A { return P9A() }
}
struct Z10 : P9, P10 {
}
func testZ10() -> Z10.A {
var zA: Z10.A
zA = P9A()
return zA
}
// rdar://problem/21926788
protocol P11 {
associatedtype A
associatedtype B
func foo() -> B
}
extension P11 where A == Int {
func foo() -> Int { return 0 }
}
protocol P12 : P11 {
}
extension P12 {
func foo() -> String { return "" }
}
struct X12 : P12 {
typealias A = String
}
// Infinite recursion -- we would try to use the extension
// initializer's argument type of 'Dough' as a candidate for
// the associated type
protocol Cookie {
associatedtype Dough
// expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}}
init(t: Dough)
}
extension Cookie {
init(t: Dough?) {}
}
struct Thumbprint : Cookie {}
// expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}}
// Looking through typealiases
protocol Vector {
associatedtype Element
typealias Elements = [Element]
func process(elements: Elements)
}
struct Int8Vector : Vector {
func process(elements: [Int8]) { }
}
// SR-4486
protocol P13 {
associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}}
func foo(arg: Arg)
}
struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}}
func foo(arg: inout Int) {}
}
// "Infer" associated type from generic parameter.
protocol P14 {
associatedtype Value
}
struct P14a<Value>: P14 { }
struct P14b<Value> { }
extension P14b: P14 { }
// Associated type defaults in overridden associated types.
struct X15 { }
struct OtherX15 { }
protocol P15a {
associatedtype A = X15
}
protocol P15b : P15a {
associatedtype A
}
protocol P15c : P15b {
associatedtype A
}
protocol P15d {
associatedtype A = X15
}
protocol P15e : P15b, P15d {
associatedtype A
}
protocol P15f {
associatedtype A = OtherX15
}
protocol P15g: P15c, P15f {
associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
}
struct X15a : P15a { }
struct X15b : P15b { }
struct X15c : P15c { }
struct X15d : P15d { }
// Ambiguity.
// FIXME: Better diagnostic here?
struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
// Associated type defaults in overidden associated types that require
// substitution.
struct X16<T> { }
protocol P16 {
associatedtype A = X16<Self>
}
protocol P16a : P16 {
associatedtype A
}
protocol P16b : P16a {
associatedtype A
}
struct X16b : P16b { }
// Refined protocols that tie associated types to a fixed type.
protocol P17 {
associatedtype T
}
protocol Q17 : P17 where T == Int { }
struct S17 : Q17 { }
// Typealiases from protocol extensions should not inhibit associated type
// inference.
protocol P18 {
associatedtype A
}
protocol P19 : P18 {
associatedtype B
}
extension P18 where Self: P19 {
typealias A = B
}
struct X18<A> : P18 { }
// rdar://problem/16316115
protocol HasAssoc {
associatedtype Assoc
}
struct DefaultAssoc {}
protocol RefinesAssocWithDefault: HasAssoc {
associatedtype Assoc = DefaultAssoc
}
struct Foo: RefinesAssocWithDefault {
}
protocol P20 {
associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
typealias TT = T?
}
struct S19 : P20 { // expected-error{{type 'S19' does not conform to protocol 'P20'}}
typealias TT = Int?
}
// rdar://problem/44777661
struct S30<T> where T : P30 {}
protocol P30 {
static func bar()
}
protocol P31 {
associatedtype T : P30
}
extension S30 : P31 where T : P31 {}
extension S30 {
func foo() {
T.bar()
}
}
protocol P32 {
associatedtype A
associatedtype B
associatedtype C
func foo(arg: A) -> C
var bar: B { get }
}
protocol P33 {
associatedtype A
var baz: A { get } // expected-note {{protocol requires property 'baz' with type 'S31<T>.A' (aka 'Never'); do you want to add a stub?}}
}
protocol P34 {
associatedtype A
func boo() -> A // expected-note {{protocol requires function 'boo()' with type '() -> S31<T>.A' (aka '() -> Never'); do you want to add a stub?}}
}
struct S31<T> {}
extension S31: P32 where T == Int {} // OK
extension S31 where T == Int {
func foo(arg: Never) {}
}
extension S31 where T: Equatable {
var bar: Bool { true }
}
extension S31: P33 where T == Never {} // expected-error {{type 'S31<T>' does not conform to protocol 'P33'}}
extension S31 where T == String {
var baz: Bool { true } // expected-note {{candidate has non-matching type 'Bool' [with A = S31<T>.A]}}
}
extension S31: P34 {} // expected-error {{type 'S31<T>' does not conform to protocol 'P34'}}
extension S31 where T: P32 {
func boo() -> Void {} // expected-note {{candidate has non-matching type '<T> () -> Void' [with A = S31<T>.A]}}
}
// SR-12707
class SR_12707_C<T> {}
// Inference in the adoptee
protocol SR_12707_P1 {
associatedtype A
associatedtype B: SR_12707_C<(A, Self)>
func foo(arg: B)
}
struct SR_12707_Conform_P1: SR_12707_P1 {
typealias A = Never
func foo(arg: SR_12707_C<(A, SR_12707_Conform_P1)>) {}
}
// Inference in protocol extension
protocol SR_12707_P2: SR_12707_P1 {}
extension SR_12707_P2 {
func foo(arg: SR_12707_C<(A, Self)>) {}
}
struct SR_12707_Conform_P2: SR_12707_P2 {
typealias A = Never
}
// SR-13172: Inference when witness is an enum case
protocol SR_13172_P1 {
associatedtype Bar
static func bar(_ value: Bar) -> Self
}
enum SR_13172_E1: SR_13172_P1 {
case bar(String) // Okay
}
protocol SR_13172_P2 {
associatedtype Bar
static var bar: Bar { get }
}
enum SR_13172_E2: SR_13172_P2 {
case bar // Okay
}
/** References to type parameters in type witnesses. */
// Circular reference through a fixed type witness.
protocol P35a {
associatedtype A = Array<B> // expected-note {{protocol requires nested type 'A'}}
associatedtype B // expected-note {{protocol requires nested type 'B'}}
}
protocol P35b: P35a where B == A {}
// expected-error@+2 {{type 'S35' does not conform to protocol 'P35a'}}
// expected-error@+1 {{type 'S35' does not conform to protocol 'P35b'}}
struct S35: P35b {}
// Circular reference through a value witness.
protocol P36a {
associatedtype A // expected-note {{protocol requires nested type 'A'}}
func foo(arg: A)
}
protocol P36b: P36a {
associatedtype B = (Self) -> A // expected-note {{protocol requires nested type 'B'}}
}
// expected-error@+2 {{type 'S36' does not conform to protocol 'P36a'}}
// expected-error@+1 {{type 'S36' does not conform to protocol 'P36b'}}
struct S36: P36b {
func foo(arg: Array<B>) {}
}
// Test that we can resolve abstract type witnesses that reference
// other abstract type witnesses.
protocol P37 {
associatedtype A = Array<B>
associatedtype B: Equatable = Never
}
struct S37: P37 {}
protocol P38a {
associatedtype A = Never
associatedtype B: Equatable
}
protocol P38b: P38a where B == Array<A> {}
struct S38: P38b {}
protocol P39 where A: Sequence {
associatedtype A = Array<B>
associatedtype B
}
struct S39<B>: P39 {}
// Test that we can handle an analogous complex case involving all kinds of
// type witness resolution.
//
// FIXME: Except there's too much circularity here, and this really can't
// work. The problem is that S40 conforms to P40c, and we can't check the
// conformance without computing the requirement signature of P40c, but the
// requirement signature computation depends on the conformance, via the
// 'D == S40<Never>' requirement.
protocol P40a {
associatedtype A
associatedtype B: P40a
func foo(arg: A)
}
protocol P40b: P40a {
associatedtype C = (A, B.A, D.D, E) -> Self // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
associatedtype D: P40b // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
associatedtype E: Equatable // expected-note {{protocol requires nested type 'E'; do you want to add it?}}
}
protocol P40c: P40b where D == S40<Never> {}
struct S40<E: Equatable>: P40c {
// expected-error@-1 {{type 'S40<E>' does not conform to protocol 'P40b'}}
// expected-error@-2 {{type 'S40<E>' does not conform to protocol 'P40c'}}
func foo(arg: Never) {}
typealias B = Self
}
// Fails to find the fixed type witness B == FIXME_S1<A>.
protocol FIXME_P1a {
associatedtype A: Equatable = Never // expected-note {{protocol requires nested type 'A'}}
associatedtype B: FIXME_P1a // expected-note {{protocol requires nested type 'B'}}
}
protocol FIXME_P1b: FIXME_P1a where B == FIXME_S1<A> {}
// expected-error@+2 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1a'}}
// expected-error@+1 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1b'}}
struct FIXME_S1<T: Equatable>: FIXME_P1b {}
| apache-2.0 | 639e759292e945b87022ffa6f0831e71 | 23.709353 | 167 | 0.668899 | 3.276665 | false | false | false | false |
gneken/HackingWithSwift | project33/Project33/RecordWhistleViewController.swift | 24 | 6199 | //
// RecordWhistleViewController.swift
// Project33
//
// Created by Hudzilla on 19/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import AVFoundation
import UIKit
class RecordWhistleViewController: UIViewController, AVAudioRecorderDelegate {
var stackView: UIStackView!
var recordButton: UIButton!
var playButton: UIButton!
var recordingSession: AVAudioSession!
var whistleRecorder: AVAudioRecorder!
var whistlePlayer: AVAudioPlayer!
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.grayColor()
stackView = UIStackView()
stackView.spacing = 30
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.distribution = UIStackViewDistribution.FillEqually
stackView.alignment = UIStackViewAlignment.Center
stackView.axis = .Vertical
view.addSubview(stackView)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
view.addConstraint(NSLayoutConstraint(item: stackView, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant:0))
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Record your whistle"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Record", style: .Plain, target: nil, action: nil)
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { [unowned self] (allowed: Bool) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if allowed {
self.loadRecordingUI()
} else {
self.loadFailUI()
}
}
}
} catch {
self.loadFailUI()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadRecordingUI() {
recordButton = UIButton()
recordButton.translatesAutoresizingMaskIntoConstraints = false
recordButton.setTitle("Tap to Record", forState: .Normal)
recordButton.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleTitle1)
recordButton.addTarget(self, action: "recordTapped", forControlEvents: .TouchUpInside)
stackView.addArrangedSubview(recordButton)
playButton = UIButton()
playButton.translatesAutoresizingMaskIntoConstraints = false
playButton.setTitle("Tap to Play", forState: .Normal)
playButton.hidden = true
playButton.alpha = 0
playButton.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleTitle1)
playButton.addTarget(self, action: "playTapped", forControlEvents: .TouchUpInside)
stackView.addArrangedSubview(playButton)
}
func loadFailUI() {
let failLabel = UILabel()
failLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
failLabel.text = "Recording failed: please ensure the app has access to your microphone."
failLabel.numberOfLines = 0
stackView.addArrangedSubview(failLabel)
}
class func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
let documentsDirectory = paths[0]
return documentsDirectory
}
class func getWhistleURL() -> NSURL {
let audioFilename = getDocumentsDirectory().stringByAppendingPathComponent("whistle.m4a")
let audioURL = NSURL(fileURLWithPath: audioFilename)
return audioURL
}
func startRecording() {
// 1
view.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1)
// 2
recordButton.setTitle("Tap to Stop", forState: .Normal)
// 3
let audioURL = RecordWhistleViewController.getWhistleURL()
print(audioURL.absoluteString)
// 4
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000.0,
AVNumberOfChannelsKey: 1 as NSNumber,
AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]
do {
// 5
whistleRecorder = try AVAudioRecorder(URL: audioURL, settings: settings)
whistleRecorder.delegate = self
whistleRecorder.record()
} catch {
finishRecording(success: false)
}
}
func finishRecording(success success: Bool) {
view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1)
whistleRecorder.stop()
whistleRecorder = nil
if success {
recordButton.setTitle("Tap to Re-record", forState: .Normal)
if playButton.hidden {
UIView.animateWithDuration(0.35) { [unowned self] in
self.playButton.hidden = false
self.playButton.alpha = 1
}
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: "nextTapped")
} else {
recordButton.setTitle("Tap to Record", forState: .Normal)
let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
func recordTapped() {
if whistleRecorder == nil {
startRecording()
if !playButton.hidden {
UIView.animateWithDuration(0.35) { [unowned self] in
self.playButton.hidden = true
self.playButton.alpha = 0
}
}
} else {
finishRecording(success: true)
}
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
finishRecording(success: false)
}
}
func playTapped() {
let audioURL = RecordWhistleViewController.getWhistleURL()
do {
whistlePlayer = try AVAudioPlayer(contentsOfURL: audioURL)
whistlePlayer.play()
} catch {
let ac = UIAlertController(title: "Playback failed", message: "There was a problem playing your whistle; please try re-recording.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
func nextTapped() {
let vc = SelectGenreViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
| unlicense | dab580742add6d8b0be69f39bd513875 | 29.683168 | 183 | 0.743304 | 4.154155 | false | false | false | false |
carat-project/carat | app/ios/Classes/IosDeviceNames.swift | 1 | 3923 | // IosDeviceNames.swift
// Gets the device name of the current device based on modelIdentifier
// from a periodically fetched list stored at carat-web / ios-devices.csv.
//
// Created by Lagerspetz, Eemil H on 29/01/2018.
// Copyright © 2018 University of Helsinki. All rights reserved.
//
import Foundation
class IosDeviceNames: NSObject {
//MARK: Class Properties
// Singleton access
static let sharedInstance = IosDeviceNames()
// How often to re-fetch the list
static let THRESH = UInt64(3600*24)
// List file location
static let url = "http://carat.cs.helsinki.fi/ios-devices.csv"
//MARK: Instance Properties
// Need a separate data model class because the last fetch time also needs to come from disk.
var cache:DeviceCache? = nil
//MARK: Initialization
override init() {
super.init()
self.cache = loadCache()
// If it's too old, schedule a fetch
fetchDeviceListAsync()
}
// Fetch device list asynchronously to not block main thread.
func fetchDeviceListAsync() {
DispatchQueue.main.async {
self.fetchDeviceListIfNeeded()
}
}
// Fetch and store device list on disk.
private func fetchDeviceList() {
let list = try? String(contentsOf: URL(string: IosDeviceNames.url)!)
print("Got list", list ?? "nil")
if let gotList = list { // Compare with scala: val list = Some(Seq("a;c", "b;d")); list.map{gotList => ... }
let lines = gotList.split(separator: "\n")
print("Got lines ",lines)
var deviceMap = [String: String]()
for line in lines {
let parts = line.split(separator: ";")
if parts.count > 1 {
print("Line ", parts[0], " -> ", parts[1])
deviceMap[String(parts[0])] = String(parts[1])
}
}
cache = DeviceCache(deviceMap:deviceMap, lastUpdated:UInt64(NSDate().timeIntervalSince1970))
saveCache()
}
}
// If the list in cache is nil,
// or too long since last list update,
// update the list.
private func fetchDeviceListIfNeeded() {
if let gotCache = self.cache {
// If it's too old, schedule a fetch
if gotCache.lastUpdated + IosDeviceNames.THRESH < UInt64(NSDate().timeIntervalSince1970) {
print("Cache updated more than",IosDeviceNames.THRESH,"seconds ago, fetching now.")
fetchDeviceList()
}
// else new enough, do nothing
} else {
// No cache at all, fetch
print("Cache nil, fetching device list over the network.")
fetchDeviceList()
}
}
// Get the device name matching the given platform.
func getDeviceName(platform: String) -> String {
print("Platform is ", platform)
fetchDeviceListIfNeeded()
let deviceName = cache?.get(platform: platform)
if let gotDevice = deviceName {
return gotDevice
} else {
return platform
}
}
//MARK: Private methods
private func saveCache() {
if let gotCache = cache {
// What is the right way here? Cache may be null, in which case save should not be called at all...
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(gotCache, toFile: DeviceCache.ArchiveURL.path)
if isSuccessfulSave {
print("Cached Devices successfully saved.")
} else {
print("Failed to save cached devices.")
}
}
}
private func loadCache() -> DeviceCache? {
let c = NSKeyedUnarchiver.unarchiveObject(withFile: DeviceCache.ArchiveURL.path) as? DeviceCache
print("Loaded cache from disk: ", c ?? "nil")
return c
}
}
| bsd-2-clause | aec4a9a98028e5587a3caffc8963117a | 33.707965 | 116 | 0.58975 | 4.674613 | false | false | false | false |
ascode/jif-audiorecord | jif-audiorecord/ViewController.swift | 1 | 5604 | //
// ViewController.swift
// jif-audiorecord
//
// Created by 金飞 on 15/12/26.
// Copyright © 2015年 Fei Jin. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avRec : AVAudioRecorder!
var avUrl : NSURL!
var avPlayer : AVAudioPlayer!
@IBOutlet var lblASRResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
avUrl = (NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.AllDomainsMask)[0] as NSURL).URLByAppendingPathComponent("rec")
//压缩格式支持:pcm(不压缩)、wav、opus、speex、amr、x-flac
let recordSettings:[String : AnyObject] = [
AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatLinearPCM ),
AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
AVEncoderBitRateKey : 8000,
AVNumberOfChannelsKey: 1
]
do{
avRec = try AVAudioRecorder(URL: avUrl , settings: recordSettings)
avRec.prepareToRecord()
} catch let err as NSError{
avRec = nil
print(err.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnASRPressed(sender: AnyObject) {
var recdata = NSData(contentsOfURL: avUrl)//获取语音文件
// let paths : NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
// print(paths)
// let documentsDirectory : NSString = paths.objectAtIndex(0) as! NSString
// let appFile : NSString = documentsDirectory.stringByAppendingPathComponent("example_localRecord")
//
// let recdata : NSData = NSData(contentsOfFile: "example_localRecord.pcm")!
//
// print(NSBundle.mainBundle().pathForResource("example_localRecord", ofType: "pcm")!)
// let recdata = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("example_localRecord.pcm", ofType: "pcm")!)
print(recdata)
//print(NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil))
print(NSBundle.mainBundle().URLForResource("少女时代-TaeTiSeo - Twinkle", withExtension: "mp3")!)
print(NSBundle.mainBundle().URLForResource("tt.mp3", withExtension: nil))
print(NSBundle.mainBundle().URLForResource("aa.pcm", withExtension: nil))
let base64Data = recdata!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed) //将语音数据转换成base64编码数据
let urlForAccessToken = NSURL(string: "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=tvSQAmNW3ka2IFlkDCYlbCMG&client_secret=2c289b2656bc5859d0100fd27f5a8762")
if let theurl = urlForAccessToken {
//从网络请求access_token
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: theurl) , queue: NSOperationQueue()) { (res:NSURLResponse?, data:NSData?, err:NSError?) -> Void in
let arrdata:AnyObject?
do{
try arrdata = NSJSONSerialization.JSONObjectWithData(NSData(data: data!), options: NSJSONReadingOptions.AllowFragments)
let access_token = arrdata?.objectForKey("access_token")! as! String //得到access_token
let urlRequest = NSMutableURLRequest(URL: NSURL(string: "http://vop.baidu.com/server_api?lan=zh&token=\(access_token)&cuid=jinfei")!)//配置url和控制信息
urlRequest.HTTPMethod = "POST"
urlRequest.setValue("audio/pcm;rate=8000", forHTTPHeaderField: "Content-Type")//设置语音格式和采样率
print(recdata!.length)
//print(base64Data)
urlRequest.setValue("\(recdata!.length)", forHTTPHeaderField: "Content-length")//设置原始语音长度
urlRequest.HTTPBody = base64Data //设置传送的语音数据
NSURLConnection.sendAsynchronousRequest(urlRequest , queue: NSOperationQueue()) { (res:NSURLResponse?, data:NSData?, err:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblASRResult.text = String(NSString(data: data!, encoding: NSUTF8StringEncoding))
})
print("语音解析结果:\(String(NSString(data: data!, encoding: NSUTF8StringEncoding)))")
}
}catch{
print("没有获取到网络数据")
}
}
}
}
@IBAction func btnStartRecordPressed(sender: AnyObject) {
avRec.record()
}
@IBAction func btnStopRecordPressed(sender: AnyObject) {
avRec.stop()
}
@IBAction func btnPlayRecordPressed(sender: AnyObject) {
do{
avPlayer = try AVAudioPlayer(contentsOfURL: avUrl)
avPlayer.prepareToPlay()
avPlayer.play()
}catch let err as NSError{
avPlayer = nil
print(err.localizedDescription)
}
}
}
| mit | 1cfca31f76aba8e9cdb92da92c9cd223 | 42.604839 | 203 | 0.622711 | 4.942413 | false | false | false | false |
yoonapps/QPXExpressWrapper | QPXExpressWrapper/Classes/TripsData.swift | 1 | 1770 | //
// TripsData.swift
// Flights
//
// Created by Kyle Yoon on 2/14/16.
// Copyright © 2016 Kyle Yoon. All rights reserved.
//
import Foundation
import Gloss
public struct TripsData: Decodable {
public let kind: String?
public let airport: [TripsDataAirport]?
public let city: [TripsDataCity]?
public let aircraft: [TripsDataAircraft]?
public let tax: [TripsDataTax]?
public let carrier: [TripsDataCarrier]?
public init?(json: JSON) {
guard let kind: String = "kind" <~~ json else {
return nil
}
self.kind = kind
if let airportJSON = json["airport"] as? [JSON],
let airport = [TripsDataAirport].from(jsonArray: airportJSON) {
self.airport = airport
}
else {
self.airport = nil
}
if let cityJSON = json["city"] as? [JSON],
let city = [TripsDataCity].from(jsonArray: cityJSON) {
self.city = city
}
else {
self.city = nil
}
if let aircraftJSON = json["aircraft"] as? [JSON],
let aircraft = [TripsDataAircraft].from(jsonArray: aircraftJSON) {
self.aircraft = aircraft
}
else {
self.aircraft = nil
}
if let taxJSON = json["tax"] as? [JSON],
let tax = [TripsDataTax].from(jsonArray: taxJSON) {
self.tax = tax
}
else {
self.tax = nil
}
if let carrierJSON = json["carrier"] as? [JSON],
let carrier = [TripsDataCarrier].from(jsonArray: carrierJSON) {
self.carrier = carrier
}
else {
self.carrier = nil
}
}
}
| mit | 82dd086bc1c59798062cef6077895ad7 | 25.014706 | 78 | 0.521764 | 4.325183 | false | false | false | false |
fabnoe/FNInsetBlurModalSeque | Pod/Classes/FNInsetBlurSegue.swift | 1 | 3753 | //
// InsetBlurSegue.swift
// InsetBlurSegue
//
// Created by Fabian Nöthe on 01.07.14.
// Copyright (c) 2014 fabiannoethe. All rights reserved.
//
import UIKit
@objc protocol FNInsetBlurModalSequeProtocol {
func getBackgroundImage() -> UIImage
}
@objc(FNInsetBlurModalSeque) class FNInsetBlurModalSeque: UIStoryboardSegue {
override func perform() {
var sourceViewController = self.sourceViewController as UIViewController
let destinationViewController = self.destinationViewController as UIViewController
// Make sure the background is ransparent
destinationViewController.view.backgroundColor = UIColor.clearColor()
var image:UIImage!
if let backVC = sourceViewController as? InsetBlurModalSequeProtocol {
println("InsetBlurModalSeque: Found backgroundView")
// Use predefined background
image = backVC.getBackgroundImage()
}
else {
println("InsetBlurModalSeque: Background NOT found")
// Take screenshot from source VC
UIGraphicsBeginImageContext(sourceViewController.view.bounds.size)
sourceViewController.view.drawViewHierarchyInRect(sourceViewController.view.frame, afterScreenUpdates:true)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
// Blur screenshot
var blurredImage:UIImage = image.applyBlurWithRadius(5, tintColor: UIColor(white: 1.0, alpha: 0.0), saturationDeltaFactor: 1.3, maskImage: nil)
// Crop screenshot, add to view and send to back
let blurredBackgroundImageView : UIImageView = UIImageView(image:blurredImage)
blurredBackgroundImageView.clipsToBounds = true;
blurredBackgroundImageView.contentMode = UIViewContentMode.Center
let insets:UIEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
blurredBackgroundImageView.frame = UIEdgeInsetsInsetRect(blurredBackgroundImageView.frame, insets)
destinationViewController.view.addSubview(blurredBackgroundImageView)
destinationViewController.view.sendSubviewToBack(blurredBackgroundImageView)
// Add original screenshot behind blurred image
let backgroundImageView : UIImageView = UIImageView(image:image)
destinationViewController.view.addSubview(backgroundImageView)
destinationViewController.view.sendSubviewToBack(backgroundImageView)
// Add the destination view as a subview, temporarily – we need this do to the animation
sourceViewController.view.addSubview(destinationViewController.view)
// Set initial state of animation
destinationViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
blurredBackgroundImageView.alpha = 0.0;
backgroundImageView.alpha = 0.0;
// Animate
UIView.animateWithDuration(0.5,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.0,
options: UIViewAnimationOptions.CurveLinear,
animations: {
destinationViewController.view.transform = CGAffineTransformIdentity
blurredBackgroundImageView.alpha = 1.0
backgroundImageView.alpha = 1.0;
},
completion: { (fininshed: Bool) -> () in
// Remove from temp super view
destinationViewController.view.removeFromSuperview()
sourceViewController.presentViewController(destinationViewController, animated: false, completion: nil)
}
)
}
} | mit | e81144b220915a45fe8e53f6514d774f | 38.904255 | 151 | 0.681333 | 6.229236 | false | false | false | false |
adib/Core-ML-Playgrounds | Photo-Explorations/EnlargeImages.playground/Sources/CGImage+Crop.swift | 1 | 2033 | //
// UIImage+Crop.swift
// waifu2x-ios
//
// Created by xieyi on 2017/9/14.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import AppKit
extension CGImage {
public func getCropRects() -> ([CGRect]) {
let width = Int(self.width)
let height = Int(self.height)
let num_w = width / block_size
let num_h = height / block_size
let ex_w = width % block_size
let ex_h = height % block_size
var rects: [CGRect] = []
for i in 0..<num_w {
for j in 0..<num_h {
let x = i * block_size
let y = j * block_size
let rect = CGRect(x: x, y: y, width: block_size, height: block_size)
rects.append(rect)
}
}
if ex_w > 0 {
let x = width - block_size
for i in 0..<num_h {
let y = i * block_size
let rect = CGRect(x: x, y: y, width: block_size, height: block_size)
rects.append(rect)
}
}
if ex_h > 0 {
let y = height - block_size
for i in 0..<num_w {
let x = i * block_size
let rect = CGRect(x: x, y: y, width: block_size, height: block_size)
rects.append(rect)
}
}
if ex_w > 0 && ex_h > 0 {
let x = width - block_size
let y = height - block_size
let rect = CGRect(x: x, y: y, width: block_size, height: block_size)
rects.append(rect)
}
return rects
}
public func crop(rects: [CGRect]) -> [CGImage] {
var result: [CGImage] = []
for rect in rects {
result.append(crop(rect: rect))
}
return result
}
public func crop(rect: CGRect) -> CGImage {
// let cgimg = cgImage?.cropping(to: rect)
// return NSImage(cgImage: cgimg!)
let cgimg = self.cropping(to: rect)
return cgimg!
}
}
| bsd-3-clause | 572ab47610188be1ae88e391ed5d882d | 28 | 84 | 0.476847 | 3.724771 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift | 5-Tree/5-Tree/BinaryTreePath.swift | 1 | 3504 | //
// BinaryTreePath.swift
// 5-Tree
//
// Created by keso on 2016/12/15.
// Copyright © 2016年 FlyElephant. All rights reserved.
//
import Foundation
class BinaryTreePath {
// 二叉树中和为某一值的路径
// 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
var path:[String] = []
var listPath:[[String]] = []
func findTreePath(rootNode:TreeNode?,targert:Int)->[[String]]? {
if rootNode == nil {
return nil
}
path.append((rootNode?.data)!)
let value:Int = Int((rootNode?.data)!)!
var temp = targert
temp -= value
if temp == 0 && rootNode?.leftChild == nil && rootNode?.rightChild == nil {
listPath.append(path) // 路径添加
}
if rootNode?.leftChild != nil {// 递归遍历左子树
_ = findTreePath(rootNode: rootNode?.leftChild, targert: temp)
}
if rootNode?.rightChild != nil { // 递归遍历右子树
_ = findTreePath(rootNode: rootNode?.rightChild, targert: temp)
}
path.remove(at: path.count-1) // 回溯到父节点
return listPath
}
func treeMaxDepth(rootNode:TreeNode?) -> Int {
if rootNode == nil {
return 0
}
let leftDepth:Int = treeMaxDepth(rootNode: rootNode?.leftChild)
let rightDepth:Int = treeMaxDepth(rootNode: rootNode?.rightChild)
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1
}
func treeMinDepth(rootNode:TreeNode?) -> Int {
if rootNode == nil {
return 0
}
let leftDepth:Int = treeMinDepth(rootNode: rootNode?.leftChild)
let rightDepth:Int = treeMinDepth(rootNode: rootNode?.rightChild)
if leftDepth == 0 {
return rightDepth + 1
}
if rightDepth == 0 {
return leftDepth + 1
}
return leftDepth < rightDepth ? leftDepth + 1 : rightDepth + 1
}
func isBalanceTree(rootNode:TreeNode?) -> Bool {
if rootNode == nil {
return true
}
let leftDepth:Int = treeMaxDepth(rootNode: rootNode?.leftChild)
let rightDepth:Int = treeMaxDepth(rootNode: rootNode?.rightChild)
let diff:Int = leftDepth - rightDepth
if diff > 1 || diff < -1 {
return false
}
return isBalanceTree(rootNode: rootNode?.leftChild) && isBalanceTree(rootNode: rootNode?.rightChild)
}
func isBalanceTreeOnce(rootNode:TreeNode?,depth:inout Int) -> Bool {
if rootNode == nil {
depth = 0
return true
}
var leftDepth:Int = 0
var rightDepth:Int = 0
if isBalanceTreeOnce(rootNode: rootNode?.leftChild, depth: &leftDepth) && isBalanceTreeOnce(rootNode: rootNode?.rightChild, depth: &rightDepth) {
let diff:Int = leftDepth - rightDepth
if diff <= 1 && diff >= -1 {
depth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1
return true
}
}
return false
}
func isBalancedTree(rootNode:TreeNode?) -> Bool {
var depth:Int = 0
return isBalanceTreeOnce(rootNode: rootNode, depth: &depth)
}
}
| mit | c647dfbccf44f178d65afc9a02659602 | 29.738318 | 153 | 0.563393 | 4.438596 | false | false | false | false |
ahayman/RxStream | RxStream/Streams/Promise.swift | 1 | 7688 | //
// Promise.swift
// RxStream
//
// Created by Aaron Hayman on 3/14/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
public typealias PromiseTask<T> = (_ terminated: Observable<StreamState>, _ completion: @escaping (Result<T>) -> Void) -> Void
extension Promise : Cancelable { }
extension Promise : Retriable { }
public class Promise<T> : Stream<T> {
override var streamType: StreamType { return .promise }
/// The current task for the promise. If there's no task, there should be a parent with a task.
let task: PromiseTask<T>?
/// The parent to handle cancellations
weak var cancelParent: Cancelable?
/// Parent, retriable stream. Note: This creates a retain cycle. The parent must release the child in order to unravel the cycle. This is done with the `prune` command when the child is no longer viable.
var retryParent: Retriable?
/// Marked as false while auto replay is pending to prevent multiple replays
private var autoReplayable: Bool = true
/// The promise needed to pass into the promise task.
lazy private var stateObservable: ObservableInput<StreamState> = ObservableInput(self.state)
/// Override and observe didSet to update the observable
override public var state: StreamState {
didSet { stateObservable.set(state) }
}
/// Once completed, the promise shouldn't accept or process any more f
private(set) fileprivate var complete: Bool = false
private var isCancelled: Bool {
guard case .terminated(.cancelled) = state else { return false }
return true
}
/// If true, then a retry will be filled with the last completed value from this stream if it's available
private var reuse: Bool = false
/// We should only prune if the stream is complete (or no longer active), and has no down stream promises.
override var shouldPrune: Bool {
guard isActive else { return true }
guard complete else { return false }
// We need to prune if there are no active down stream _promises_. Since a promise emits only one value that can be retried, we can't prune until those streams complete.
let active = downStreams.reduce(0) { (count, processor) -> Int in
guard !processor.stream.shouldPrune else { return count }
guard processor.stream.streamType == .promise else { return count }
return count + 1
}
return active < 1
}
/// The number of downStreams that are promises. Used to determine if the stream should terminate after a value has been pushed.
private var downStreamPromises: Int {
return downStreams.reduce(0) { (count, processor) -> Int in
guard processor.stream.streamType == .promise else { return count }
return count + 1
}
}
/**
A Promise is initialized with the task.
The task should call the completions handler with the result when it's done.
The task will also be passed an observable that indicates the current stream state.
If the stream is terminated, the task should cancel whatever it's doing (if possible).
After a stream has been terminated, calling the completion handler will do nothing.
- parameter task: The task that should complete the Promise
- parameter dispatch: (Optional) set the dispatch the task is to run on.
- returns: A new Promise
*/
public init(dispatch: Dispatch? = nil, task: @escaping PromiseTask<T>) {
self.task = task
super.init(op: "Task")
self.dispatch = dispatch
persist()
run(task: task)
}
/// Internal init for creating down stream promises
override init(op: String) {
task = nil
super.init(op: op)
}
/// Overridden to auto replay the Promise stream result when a new stream is added
override func didAttachStream<U>(stream: Stream<U>) {
if !isActive && autoReplayable {
autoReplayable = false
Dispatch.after(delay: 0.01, on: .main).execute {
self.autoReplayable = true
self.replay()
}
}
}
/// Overridden to update the complete variable
override func preProcess<U>(event: Event<U>) -> Event<U>? {
guard !complete else { return nil }
complete = true
return event
}
/// Added logic will terminate the stream if it's not already terminated and we've received a value the stream is complete
override func postProcess<U>(event: Event<U>, producedSignal signal: OpSignal<T>) {
if case .merging = signal {
complete = false
}
guard self.downStreamPromises == 0 else { return }
switch signal {
case .push where self.shouldPrune:
terminate(reason: .completed, andPrune: .upStream, pushDownstreamTo: StreamType.all().removing([.promise, .future]))
case .error(let error) where self.shouldPrune:
terminate(reason: .error(error), andPrune: .upStream, pushDownstreamTo: StreamType.all().removing([.promise, .future]))
case .terminate(_, let reason):
terminate(reason: reason, andPrune: .upStream, pushDownstreamTo: StreamType.all().removing([.promise, .future]))
default: break
}
}
/// Used to run the task and process the value the task returns.
private func run(task: @escaping PromiseTask<T>) {
let work = {
var complete = false
task(self.stateObservable) { [weak self] completion in
guard let me = self, !complete, me.isActive else { return }
complete = true
completion
.onFailure{ me.process(event: .error($0)) }
.onSuccess{ me.process(event: .next($0)) }
}
}
if let dispatch = self.dispatch {
dispatch.execute(work)
} else {
work()
}
}
/// Cancel the task, if we have one, otherwise, pass the request to the parent.
func cancelTask() {
guard isActive else { return }
guard task == nil else { return process(event: .terminate(reason: .cancelled)) }
guard let parent = cancelParent else { return process(event: .terminate(reason: .cancelled)) }
parent.cancelTask()
}
/// A Retry will propagate up the chain, re-enabling the the parent stream(s), until it find a task to retry, where it will retry that task.
func retry() {
// There's two states we can retry on: error and completed. If the state is active, then the task we want to retry is already pending. If the state is cancelled then someone cancelled the stream and no retry is possible.
guard !isCancelled else { return }
// If complete is false, then a task is in progress and a retry is not necessary
guard complete else { return }
self.complete = false
if reuse, let values = self.current {
for value in values {
self.process(event: .next(value))
}
} else if let task = self.task {
self.run(task: task)
} else {
self.retryParent?.retry()
}
}
/// This will cancel the promise, including any task associated with it. If the stream is not active, this does nothing.
public func cancel() {
self.cancelTask()
}
/**
This will cause the promise to automatically reuse a valid value when retrying, if any, instead of re-running the task or pushing the retry further up the chain.
This allows you to prevent a retry from re-running the task for an error that might have been generated down stream.
- note: If there is no completed value, then the Promise's task will be re-run or, if there's no task, the retry pushed up the chain.
- parameter reuse: If `true`, completed values are used to fill a retry request instead of re-running the Promise's task (or it's parent).
- returns: Self, for chaining
*/
public func reuse(_ reuse: Bool = true) -> Self {
self.reuse = reuse
return self
}
}
| mit | 850606512966e567cadd725405eaf585 | 36.866995 | 226 | 0.683492 | 4.256368 | false | false | false | false |
Ezfen/iOS.Apprentice.1-4 | Checklists/Checklists/ChecklistItem.swift | 1 | 2801 | //
// ChecklistItem.swift
// Checklists
//
// Created by ezfen on 16/8/5.
// Copyright © 2016年 Ezfen Inc. All rights reserved.
//
import Foundation
import UIKit
class ChecklistItem: NSObject, NSCoding {
var text: String = ""
var checked = false
var dueDate = NSDate()
var shouldRemind = false
var itemID: Int
override init() {
itemID = DataModel.nextChecklistItemID()
super.init()
}
required init?(coder aDecoder: NSCoder) {
text = aDecoder.decodeObjectForKey("Text") as! String
checked = aDecoder.decodeBoolForKey("Checked")
dueDate = aDecoder.decodeObjectForKey("DueDate") as! NSDate
shouldRemind = aDecoder.decodeBoolForKey("ShouldRemind")
itemID = aDecoder.decodeIntegerForKey("ItemID")
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(text, forKey: "Text")
aCoder.encodeBool(checked, forKey: "Checked")
aCoder.encodeObject(dueDate, forKey: "DueDate")
aCoder.encodeBool(shouldRemind, forKey: "ShouldRemind")
aCoder.encodeInteger(itemID, forKey: "ItemID")
}
func toggleChecked() {
checked = !checked
}
func scheduleNotification() {
let existingNotification = notificationForThisItem()
if let notification = existingNotification {
print("Found an existing notification \(notification)")
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
if shouldRemind && dueDate.compare(NSDate()) != .OrderedAscending {
let localNotification = UILocalNotification()
localNotification.fireDate = dueDate
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.alertBody = text
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = ["ItemID": itemID]
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
print("Scheduled notification \(localNotification) for itemID \(itemID)")
}
}
func notificationForThisItem() -> UILocalNotification? {
let allNotifications = UIApplication.sharedApplication().scheduledLocalNotifications!
for notification in allNotifications {
if let number = notification.userInfo?["ItemID"] as? Int where number == itemID {
return notification
}
}
return nil
}
deinit {
if let notification = notificationForThisItem() {
print("Removing existing notification \(notification)")
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
}
} | mit | 62f54ea4e51f4db1135f3112d0b468c0 | 34.43038 | 93 | 0.653681 | 5.698574 | false | false | false | false |
duliodenis/fruitycrush | Fruity Crush/Fruity Crush/Swap.swift | 1 | 827 | //
// Swap.swift
// Fruity Crush
//
// Created by Dulio Denis on 1/24/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
struct Swap: CustomStringConvertible, Hashable {
let fruitA: Fruit
let fruitB: Fruit
// Conform to Hashable Protocol
var hashValue: Int {
// exclusive-or combination
return fruitA.hashValue ^ fruitB.hashValue
}
init(fruitA: Fruit, fruitB: Fruit) {
self.fruitA = fruitA
self.fruitB = fruitB
}
var description: String {
return "swap \(fruitA) with \(fruitB)"
}
}
// Since Swap is Hashable conform to the Equatable Protocol
func ==(lhs: Swap, rhs: Swap) -> Bool {
return (lhs.fruitA == rhs.fruitA && lhs.fruitB == rhs.fruitB) ||
(lhs.fruitB == rhs.fruitA && lhs.fruitA == rhs.fruitB)
} | mit | e3f83daef3abd3af6e55b39e0fb4dabb | 23.323529 | 68 | 0.61138 | 3.84186 | false | false | false | false |
fjbelchi/SwiftLayout | SwiftLayout/src/NSLayoutConstraint.swift | 1 | 1142 | //
// NSLayoutConstraint.swift
// SwiftLayout
//
// Created by Fran_DEV on 12/06/15.
// Copyright (c) 2015 FJBelchi. All rights reserved.
//
import Foundation
public extension NSLayoutConstraint {
public func offset(offset:Float) -> NSLayoutConstraint {
self.constant = CGFloat(offset)
return self
}
public func sl_add() -> NSLayoutConstraint {
if let view = self.firstItem as? UIView {
view.autolayoutConstraints.append(self)
}
return self
}
public func sl_install() -> NSLayoutConstraint {
// refactor with guard
if let firstView = self.firstItem as? UIView {
// check if constraint is unary = secondItem = nil
if let secondView = self.secondItem as? UIView,
let view = firstView.sl_nearestCommonViewAncestor(secondView) {
view.addConstraint(self)
} else {
firstView.addConstraint(self)
return self
}
} else {
return self;
}
return self
}
} | mit | 3e5a1aa15caf8a3b7a645268ed286415 | 24.977273 | 79 | 0.556042 | 4.965217 | false | false | false | false |
blue42u/swift-t | stc/tests/375-arrayostruct-1.swift | 4 | 519 | // parser can't handle struct refs yet
type mystruct {
int a;
int b;
}
(int ret) f (int recs) {
if (recs) {
ret = f(recs - 1);
} else {
ret = 0;
}
}
main {
mystruct bigarray[];
mystruct tmp1;
tmp1.a = 1;
tmp1.b = 2;
bigarray[0] = tmp1;
mystruct tmp2;
tmp2.a = 1;
// forgot to assign b - may cause warning but not error
// UNSET-VARIABLE-EXPECTED
bigarray[1] = tmp2;
trace(bigarray[f(2)].a, bigarray[0].b, bigarray[f(2)+1].a);
}
| apache-2.0 | c9859ecfdb74d4bc9e3c2b706eb34ad4 | 15.21875 | 63 | 0.527938 | 2.899441 | false | false | false | false |
xxxAIRINxxx/Cmg | Sources/Range.swift | 1 | 1381 | //
// Range.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public struct Range {
public let minimumValue: Float
public let maximumValue: Float
public let initialValue: Float
public init(_ minimumValue: Float, _ maximumValue: Float, _ initialValue: Float) {
self.minimumValue = minimumValue
self.maximumValue = maximumValue
self.initialValue = initialValue
}
public func convertValue(_ currentValue: Float) -> Float {
if currentValue > self.maximumValue { return self.maximumValue }
if currentValue < self.minimumValue { return self.minimumValue }
return currentValue
}
static func generateFromFilterAttributes(_ key: String, filter: CIFilter) -> Range {
let attributes = filter.attributes[key] as? [String : AnyObject]
let min = attributes?["CIAttributeSliderMin"] as? NSNumber ?? attributes?["CIAttributeMin"] as? NSNumber
let max = attributes?["CIAttributeSliderMax"] as? NSNumber ?? attributes?["CIAttributeMax"] as? NSNumber
let def = attributes?["CIAttributeDefault"] as? NSNumber ?? min
return Range(min?.floatValue ?? Float(0), max?.floatValue ?? Float(0), def?.floatValue ?? Float(0))
}
}
| mit | d909c5aa880902f4971fbe6689b0c1b4 | 33.5 | 112 | 0.668116 | 4.859155 | false | false | false | false |
uasys/swift | stdlib/public/SDK/Intents/INRideOption.swift | 4 | 1498 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
// Simply extending the INRideOption type doesn't work due to:
// <rdar://problem/29447066>
// Compiler incorrectly handles combinations of availability declarations on
// independent axes.
public protocol _INRideOptionMeteredFare {
var __usesMeteredFare: NSNumber? { get set }
}
extension _INRideOptionMeteredFare {
@available(swift, obsoleted: 4)
@nonobjc
public final var usesMeteredFare: NSNumber? {
get {
return __usesMeteredFare
}
set(newUsesMeteredFare) {
__usesMeteredFare = newUsesMeteredFare
}
}
@available(swift, introduced: 4.0)
@nonobjc
public var usesMeteredFare: Bool? {
get {
return __usesMeteredFare?.boolValue
}
set(newUsesMeteredFare) {
__usesMeteredFare = newUsesMeteredFare.map { NSNumber(value: $0) }
}
}
}
@available(iOS 10.0, watchOS 3.2, *)
extension INRideOption : _INRideOptionMeteredFare {
}
#endif
| apache-2.0 | 70f5727508127b2c82c2beac122f8773 | 26.740741 | 80 | 0.636182 | 4.471642 | false | false | false | false |
rsrose21/MemeMe | MemeMe/MemeMe/MemeEditorView.swift | 1 | 7950 | //
// ViewController.swift
// MemeMe
//
// Created by Ryan Rose on 5/17/15.
// Copyright (c) 2015 GE. All rights reserved.
//
import UIKit
class MemeEditorView: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var topText: UITextField!
@IBOutlet weak var bottomText: UITextField!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var albumButton: UIBarButtonItem!
@IBOutlet weak var imagePickerView: UIImageView!
@IBOutlet weak var topToolbar: UIToolbar!
@IBOutlet weak var bottomToolbar: UIToolbar!
@IBOutlet weak var actionButton: UIBarButtonItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
self.topText.delegate = self
self.bottomText.delegate = self
//default text properties
let memeTextAttributes = [
NSStrokeColorAttributeName : UIColor.blackColor(),
NSForegroundColorAttributeName : UIColor(red:1, green:1, blue:1, alpha:1),
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : -2.0
]
//apply text attributes
self.topText.defaultTextAttributes = memeTextAttributes
self.bottomText.defaultTextAttributes = memeTextAttributes
//center text
self.topText.textAlignment = NSTextAlignment.Center;
self.bottomText.textAlignment = NSTextAlignment.Center;
//disable actionButton until we have a Meme
self.actionButton.enabled = false
//maintain proportions for image display in UIImageView
self.imagePickerView.contentMode = UIViewContentMode.ScaleAspectFill
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//disable camera button if device does not support it
self.cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
// Subscribe to keyboard notifications to allow the view to raise when necessary
self.subscribeToKeyboardNotifications()
}
// MARK: Unsubscribe
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unsubscribeFromKeyboardNotifications()
}
// MARK: ImagePicker delegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
//set selected image and fill size
self.imagePickerView.image = image
self.actionButton.enabled = true
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
//helper method to open imagePicker
func pickAnImage(type: NSString) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
if type == "camera" {
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
} else {
//use photo library as source if camera disabled, album selected or the type is unknown
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
self.presentViewController(imagePicker, animated: true, completion: nil)
}
// MARK: toolbar button actions
@IBAction func pickAnImageFromCamera(sender: UIBarButtonItem) {
self.pickAnImage("camera")
}
@IBAction func pickAnImageFromAlbum(sender: UIBarButtonItem) {
self.pickAnImage("album")
}
// MARK: text field actions
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
//helper method to get the keyboard height from the notification’s userInfo dictionary
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.CGRectValue().height
}
//shift view when keyboard displays so we don't obscure the text field
func keyboardWillShow(notification: NSNotification) {
if bottomText.isFirstResponder() {
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
}
//return view to original position when keyboard is dismissed
func keyboardWillHide(notification: NSNotification) {
if bottomText.isFirstResponder() {
self.view.frame.origin.y += getKeyboardHeight(notification)
}
}
// MARK: Meme methods
@IBAction func shareMeme(sender: AnyObject) {
let memeImage = generateMemedImage()
self.saveMeme(memeImage)
let activityViewController = UIActivityViewController(activityItems: [memeImage], applicationActivities: nil)
// When finished, go to the tab bar controller
activityViewController.completionWithItemsHandler = {
(s: String!, ok: Bool, items: [AnyObject]!, err:NSError!) -> Void in
self.navToTabBarController()
}
self.presentViewController(activityViewController, animated: true) {
() -> Void in
}
}
func saveMeme(memedImage: UIImage)
{
var newMeme = Meme(topText: self.topText.text!, bottomText: self.bottomText.text!, image: self.imagePickerView.image!, memedImage: memedImage)
//save generated Meme to shared model
(UIApplication.sharedApplication().delegate as! AppDelegate).memes.append(newMeme)
}
// Create a UIImage that combines the Image View and the Textfields
func generateMemedImage() -> UIImage
{
// Hide toolbars
self.topToolbar.hidden = true
self.bottomToolbar.hidden = true
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawViewHierarchyInRect(self.view.frame, afterScreenUpdates: true)
let memedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Show toolbars
self.topToolbar.hidden = false
self.bottomToolbar.hidden = false
return memedImage
}
// Navigate the user to the Tab Bar Controller (TableView and CollectionView)
func navToTabBarController() {
var tbc:UITabBarController
tbc = self.storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController
//dismiss Meme Editor so we don't have multiple instances of modal existing
self.dismissViewControllerAnimated(true, completion: nil)
presentViewController(tbc, animated: true, completion: nil)
}
@IBAction func cancelEdit(sender: AnyObject) {
//cancel button pressed, dismiss Meme Editor
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 99bff9fbaef9120866fdf3ea93d93978 | 39.141414 | 150 | 0.692627 | 5.814192 | false | false | false | false |
hgl888/firefox-ios | Client/Frontend/Browser/URLBarView.swift | 1 | 34267 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SnapKit
struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
static let URLBarCurveOffsetLeft: CGFloat = -10
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
func urlBarDisplayTextForURL(url: NSURL?) -> String?
}
class URLBarView: UIView {
// Additional UIAppearance-configurable properties
dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor {
didSet {
if !inOverlayMode {
locationContainer.layer.borderColor = locationBorderColor.CGColor
}
}
}
dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor {
didSet {
if inOverlayMode {
locationContainer.layer.borderColor = locationActiveBorderColor.CGColor
}
}
}
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
var toolbarIsShowing = false
private var locationTextField: ToolbarTextField?
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: BrowserLocationView = {
let locationView = BrowserLocationView()
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = self.locationBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton()
tabsButton.titleLabel.text = "0"
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = URLBarViewUX.ProgressTintColor
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: TabsButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
locationContainer.addSubview(locationView)
addSubview(locationContainer)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
backButton.snp_makeConstraints { make in
make.left.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp_makeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
stopReloadButton.snp_makeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
bookmarkButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp_trailing)
make.trailing.equalTo(self.shareButton.snp_leading)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
func createLocationTextField() {
guard locationTextField == nil else { return }
locationTextField = ToolbarTextField()
guard let locationTextField = locationTextField else { return }
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.font = UIConstants.DefaultMediumFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
locationContainer.addSubview(locationTextField)
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
func removeLocationTextField() {
locationTextField?.removeFromSuperview()
locationTextField = nil
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.forEach { $0.alpha = alpha }
}
func updateTabCount(count: Int, animated: Bool = true) {
let currentCount = self.tabsButton.titleLabel.text
// only animate a tab count change if the tab count has actually changed
if currentCount != count.description {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
self.tabsButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = self.tabsButton.clone() as! TabsButton
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.titleLabel.text = count.description
newTabsButton.accessibilityValue = count.description
addSubview(newTabsButton)
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
let frame = tabsButton.insideButton.frame
let halfTitleHeight = CGRectGetHeight(frame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.insideButton.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.insideButton.layer.transform = CATransform3DIdentity
self.tabsButton.insideButton.layer.transform = oldFlipTransform
self.tabsButton.insideButton.layer.opacity = 0
}
let completion: (Bool) -> Void = { finished in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.insideButton.layer.opacity = 1
self.tabsButton.insideButton.layer.transform = CATransform3DIdentity
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
if finished {
self.tabsButton.titleLabel.text = count.description
self.tabsButton.accessibilityValue = count.description
}
}
if animated {
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: !isTransitioning)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if self.progressBar.alpha < 1.0 {
self.progressBar.alpha = 1.0
}
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning)
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField?.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
createLocationTextField()
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField?.text = ""
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField?.becomeFirstResponder()
self.locationTextField?.text = locationText
}
} else {
// Copy the current URL to the editable text field, then activate it.
self.locationTextField?.text = locationText
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField?.becomeFirstResponder()
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField?.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.bringSubviewToFront(self.locationContainer)
self.cancelButton.hidden = false
self.progressBar.hidden = false
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay(didCancel: Bool = false) {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
self.shareButton.alpha = inOverlayMode ? 0 : 1
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField?.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField?.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
if !overlay {
removeLocationTextField()
}
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode(didCancel: true)
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
helper?.updateReloadStatus(isLoading)
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(isWebPage isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]? {
get {
if inOverlayMode {
guard let locationTextField = locationTextField else { return nil }
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
let locationText = delegate?.urlBarDisplayTextForURL(locationView.url)
enterOverlayMode(locationText, pasted: false)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField?.text else { return true }
delegate?.urlBar(self, didSubmitText: text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
// MARK: UIAppearance
extension URLBarView {
dynamic var progressBarTint: UIColor? {
get { return progressBar.progressTintColor }
set { progressBar.progressTintColor = newValue }
}
dynamic var cancelTextColor: UIColor? {
get { return cancelButton.titleColorForState(UIControlState.Normal) }
set { return cancelButton.setTitleColor(newValue, forState: UIControlState.Normal) }
}
dynamic var actionButtonTintColor: UIColor? {
get { return helper?.buttonTintColor }
set {
guard let value = newValue else { return }
helper?.buttonTintColor = value
}
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextRestoreGState(context)
}
}
class ToolbarTextField: AutocompleteTextField {
dynamic var clearButtonTintColor: UIColor? {
didSet {
// Clear previous tinted image that's cache and ask for a relayout
tintedClearImage = nil
setNeedsLayout()
}
}
private var tintedClearImage: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Since we're unable to change the tint color of the clear image, we need to iterate through the
// subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip:
// http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield
for view in subviews as [UIView] {
if let button = view as? UIButton {
if let image = button.imageForState(.Normal) {
if tintedClearImage == nil {
tintedClearImage = tintImage(image, color: clearButtonTintColor)
}
if button.imageView?.image != tintedClearImage {
button.setImage(tintedClearImage, forState: .Normal)
}
}
}
}
}
private func tintImage(image: UIImage, color: UIColor?) -> UIImage {
guard let color = color else { return image }
let size = image.size
UIGraphicsBeginImageContextWithOptions(size, false, 2)
let context = UIGraphicsGetCurrentContext()
image.drawAtPoint(CGPointZero, blendMode: CGBlendMode.Normal, alpha: 1.0)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetBlendMode(context, CGBlendMode.SourceIn)
CGContextSetAlpha(context, 1.0)
let rect = CGRectMake(
CGPointZero.x,
CGPointZero.y,
image.size.width,
image.size.height)
CGContextFillRect(UIGraphicsGetCurrentContext(), rect)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}
| mpl-2.0 | 6090fa5b18cff1dc2e1a33dc20dee773 | 39.219484 | 207 | 0.671112 | 5.537654 | false | false | false | false |
vector-im/vector-ios | DesignKit/Source/ColorsSwiftUI.swift | 1 | 1922 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import SwiftUI
/**
Struct for holding colors for use in SwiftUI.
*/
@available(iOS 14.0, *)
public struct ColorSwiftUI: Colors {
public let accent: Color
public let alert: Color
public let primaryContent: Color
public let secondaryContent: Color
public let tertiaryContent: Color
public let quarterlyContent: Color
public let quinaryContent: Color
public let separator: Color
public var system: Color
public let tile: Color
public let navigation: Color
public let background: Color
public let namesAndAvatars: [Color]
init(values: ColorValues) {
accent = Color(values.accent)
alert = Color(values.alert)
primaryContent = Color(values.primaryContent)
secondaryContent = Color(values.secondaryContent)
tertiaryContent = Color(values.tertiaryContent)
quarterlyContent = Color(values.quarterlyContent)
quinaryContent = Color(values.quinaryContent)
separator = Color(values.separator)
system = Color(values.system)
tile = Color(values.tile)
navigation = Color(values.navigation)
background = Color(values.background)
namesAndAvatars = values.namesAndAvatars.map({ Color($0) })
}
}
| apache-2.0 | face0b77e4c8a3437c5c693f4a34ee3f | 27.686567 | 75 | 0.687825 | 4.543735 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Renderers/ChartXAxisRenderer.swift | 7 | 14718 | //
// ChartXAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartXAxisRenderer: ChartAxisRendererBase
{
public var xAxis: ChartXAxis?
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer)
self.xAxis = xAxis
}
public func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
guard let xAxis = xAxis else { return }
var a = ""
let max = Int(round(xValAverageLength + Double(xAxis.spaceBetweenLabels)))
for _ in 0 ..< max
{
a += "h"
}
let widthText = a as NSString
let labelSize = widthText.sizeWithAttributes([NSFontAttributeName: xAxis.labelFont])
let labelWidth = labelSize.width
let labelHeight = labelSize.height
let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(labelSize, degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = labelRotatedSize.width
xAxis.labelRotatedHeight = labelRotatedSize.height
xAxis.values = xValues
}
public override func renderAxisLabels(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled)
{
return
}
let yOffset = xAxis.yOffset
if (xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if (xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentTop + yOffset + xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if (xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
else if (xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom - yOffset - xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 0.0))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, xAxis.axisLineWidth)
if (xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.axisLineDashPhase, xAxis.axisLineDashLengths, xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (xAxis.labelPosition == .Top
|| xAxis.labelPosition == .TopInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (xAxis.labelPosition == .Bottom
|| xAxis.labelPosition == .BottomInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
/// draws the x-labels on the specified y-position
public func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard let xAxis = xAxis else { return }
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
NSForegroundColorAttributeName: xAxis.labelTextColor,
NSParagraphStyleAttributeName: paraStyle]
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
var labelMaxSize = CGSize()
if (xAxis.isWordWrapEnabled)
{
labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
}
for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus)
{
let label = xAxis.values[i]
if (label == nil)
{
continue
}
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (viewPortHandler.isInBoundsX(position.x))
{
let labelns = label! as NSString
if (xAxis.isAvoidFirstLastClippingEnabled)
{
// avoid clipping of the last
if (i == xAxis.values.count - 1 && xAxis.values.count > 1)
{
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
if (width > viewPortHandler.offsetRight * 2.0
&& position.x + width > viewPortHandler.chartWidth)
{
position.x -= width / 2.0
}
}
else if (i == 0)
{ // avoid clipping of the first
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
position.x += width / 2.0
}
}
drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, attributes: labelAttrs, constrainedToSize: labelMaxSize, anchor: anchor, angleRadians: labelRotationAngleRadians)
}
}
}
public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
guard let xAxis = xAxis else { return }
let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label
ChartUtils.drawMultilineText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians)
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isDrawGridLinesEnabled || !xAxis.isEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetShouldAntialias(context, xAxis.gridAntialiasEnabled)
CGContextSetStrokeColorWithColor(context, xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, xAxis.gridLineWidth)
CGContextSetLineCap(context, xAxis.gridLineCap)
if (xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.gridLineDashPhase, xAxis.gridLineDashLengths, xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in self.minX.stride(to: self.maxX, by: xAxis.axisLabelModulus)
{
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (position.x >= viewPortHandler.offsetLeft
&& position.x <= viewPortHandler.chartWidth)
{
_gridLineSegmentsBuffer[0].x = position.x
_gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_gridLineSegmentsBuffer[1].x = position.x
_gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
public override func renderLimitLines(context context: CGContext)
{
guard let xAxis = xAxis else { return }
var limitLines = xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
position.x = CGFloat(l.limit)
position.y = 0.0
position = CGPointApplyAffineTransform(position, trans)
renderLimitLineLine(context: context, limitLine: l, position: position)
renderLimitLineLabel(context: context, limitLine: l, position: position, yOffset: 2.0 + l.yOffset)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public func renderLimitLineLine(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint)
{
_limitLineSegmentsBuffer[0].x = position.x
_limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_limitLineSegmentsBuffer[1].x = position.x
_limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextSetStrokeColorWithColor(context, limitLine.lineColor.CGColor)
CGContextSetLineWidth(context, limitLine.lineWidth)
if (limitLine.lineDashLengths != nil)
{
CGContextSetLineDash(context, limitLine.lineDashPhase, limitLine.lineDashLengths!, limitLine.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
}
public func renderLimitLineLabel(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint, yOffset: CGFloat)
{
let label = limitLine.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = limitLine.valueFont.lineHeight
let xOffset: CGFloat = limitLine.lineWidth + limitLine.xOffset
if (limitLine.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if (limitLine.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if (limitLine.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
}
}
}
| apache-2.0 | c9e90640b0d3bbcd2a0371dceb0b84e6 | 37.328125 | 210 | 0.587376 | 5.711292 | false | false | false | false |
zmeyc/GRDB.swift | GRDB/Record/RowConvertible.swift | 1 | 9534 | /// Types that adopt RowConvertible can be initialized from a database Row.
///
/// let row = try Row.fetchOne(db, "SELECT ...")!
/// let person = Person(row)
///
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single records:
///
/// try Person.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<Person>
/// try Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
/// try Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// try Person.fetchCursor(statement, arguments:...) // DatabaseCursor<Person>
/// try Person.fetchAll(statement, arguments:...) // [Person]
/// try Person.fetchOne(statement, arguments:...) // Person?
///
/// RowConvertible is adopted by Record.
public protocol RowConvertible {
/// Initializes a record from `row`.
///
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
/// make sure to store a copy: `self.row = row.copy()`.
init(row: Row)
/// Do not call this method directly.
///
/// This method is called in an arbitrary dispatch queue, after a record
/// has been fetched from the database.
///
/// Types that adopt RowConvertible have an opportunity to complete their
/// initialization.
mutating func awakeFromFetch(row: Row)
}
extension RowConvertible {
/// Default implementation, which does nothing.
public func awakeFromFetch(row: Row) { }
// MARK: Fetching From SelectStatement
/// A cursor over records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = try Person.fetchCursor(statement) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// Reuse a single mutable row for performance.
// It is the record's responsibility to copy the row if needed.
// See Record.awakeFromFetch(), for example.
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.cursor(arguments: arguments, next: {
var record = self.init(row: row)
record.awakeFromFetch(row: row)
return record
})
}
/// Returns an array of records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = try Person.fetchAll(statement) // [Person]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let person = try Person.fetchOne(statement) // Person?
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
}
extension RowConvertible {
// MARK: Fetching From Request
/// Returns a cursor over records fetched from a fetch request.
///
/// let nameColumn = Column("firstName")
/// let request = Person.order(nameColumn)
/// let identities = try Identity.fetchCursor(db, request) // DatabaseCursor<Identity>
/// while let identity = try identities.next() { // Identity
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of records fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.order(nameColumn)
/// let identities = try Identity.fetchAll(db, request) // [Identity]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single record fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.order(nameColumn)
/// let identity = try Identity.fetchOne(db, request) // Identity?
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension RowConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over records fetched from an SQL query.
///
/// let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of records fetched from an SQL query.
///
/// let persons = try Person.fetchAll(db, "SELECT * FROM persons") // [Person]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from an SQL query.
///
/// let person = try Person.fetchOne(db, "SELECT * FROM persons") // Person?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
| mit | 17d28abc0857977093af9b58469cd657 | 42.534247 | 164 | 0.6266 | 4.641675 | false | false | false | false |
tjw/swift | stdlib/public/core/EmptyCollection.swift | 2 | 5602 | //===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// A collection whose element type is `Element` but that is always empty.
@_fixed_layout // FIXME(sil-serialize-all)
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@inlinable // FIXME(sil-serialize-all)
public init() {}
}
extension EmptyCollection {
/// An iterator that never produces an element.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator {
// no properties
/// Creates an instance.
@inlinable // FIXME(sil-serialize-all)
public init() {}
}
}
extension EmptyCollection.Iterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
return nil
}
}
extension EmptyCollection: Sequence {
/// Returns an empty iterator.
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator()
}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@inlinable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> SubSequence {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@inlinable // FIXME(sil-serialize-all)
public var count: Int {
return 0
}
@inlinable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@inlinable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@inlinable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@inlinable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
@inlinable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == indices, "invalid range for an empty collection")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
}
extension EmptyCollection : Equatable {
@inlinable // FIXME(sil-serialize-all)
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
// @available(*, deprecated, renamed: "EmptyCollection.Iterator")
public typealias EmptyIterator<T> = EmptyCollection<T>.Iterator
| apache-2.0 | 729184785ccc00411eb7ef10c3f4d939 | 30.649718 | 83 | 0.661549 | 4.362928 | false | false | false | false |
wookay/Look | samples/LookSample/Pods/C4/C4/Core/C4Path.swift | 3 | 10536 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import QuartzCore
/// Rules for determining the region of a path that gets filled with color.
public enum FillRule {
/// Specifies the non-zero winding rule. Count each left-to-right path as +1 and each right-to-left path as -1. If the
/// sum of all crossings is 0, the point is outside the path. If the sum is nonzero, the point is inside the path and
/// the region containing it is filled.
case NonZero
/// Specifies the even-odd winding rule. Count the total number of path crossings. If the number of crossings is even,
/// the point is outside the path. If the number of crossings is odd, the point is inside the path and the region
/// containing it should be filled.
case EvenOdd
}
/// A C4Path is a sequence of geometric segments which can be straight lines or curves.
@IBDesignable
public class C4Path: Equatable {
internal var internalPath: CGMutablePathRef = CGPathCreateMutable()
/// Initializes an empty C4Path.
public init() {
internalPath = CGPathCreateMutable()
CGPathMoveToPoint(internalPath, nil, 0, 0)
}
/// Initializes a new C4Path from an existing CGPathRef.
///
/// - parameter path: a previously initialized CGPathRef
public init(path: CGPathRef) {
internalPath = CGPathCreateMutableCopy(path)!
}
/// Determine if the path is empty
public func isEmpty() -> Bool {
return CGPathIsEmpty(internalPath)
}
/// Return the path bounding box. The path bounding box is the smallest rectangle completely enclosing all points
/// in the path, *not* including control points for Bézier cubic and quadratic curves. If the path is empty, then
/// return `CGRectNull`.
public func boundingBox() -> C4Rect {
return C4Rect(CGPathGetPathBoundingBox(internalPath))
}
/// Return true if `point` is contained in `path`; false otherwise. A point is contained in a path if it is inside the
/// painted region when the path is filled; if `fillRule` is `EvenOdd`, then the even-odd fill rule is used to evaluate
/// the painted region of the path, otherwise, the winding-number fill rule is used.
public func containsPoint(point: C4Point, fillRule: FillRule = .NonZero) -> Bool {
return CGPathContainsPoint(internalPath, nil, CGPoint(point), fillRule == .EvenOdd)
}
/// Create a copy of the path
public func copy() -> C4Path {
return C4Path(path: CGPathCreateMutableCopy(internalPath)!)
}
/// A CGPathRef representation of the receiver's path.
public var CGPath: CGPathRef {
get {
return internalPath
}
}
}
/// Determine if two paths are equal
public func == (left: C4Path, right: C4Path) -> Bool {
return CGPathEqualToPath(left.internalPath, right.internalPath)
}
extension C4Path {
/// Return the current point of the current subpath.
public var currentPoint: C4Point {
get {
return C4Point(CGPathGetCurrentPoint(internalPath))
}
set(point) {
moveToPoint(point)
}
}
/// Move the current point of the current subpath.
public func moveToPoint(point: C4Point) {
CGPathMoveToPoint(internalPath, nil, CGFloat(point.x), CGFloat(point.y))
}
/// Append a straight-line segment fron the current point to `point` and move the current point to `point`.
public func addLineToPoint(point: C4Point) {
CGPathAddLineToPoint(internalPath, nil, CGFloat(point.x), CGFloat(point.y))
}
/// Append a quadratic curve from the current point to `point` with control point `control` and move the current
/// point to `point`.
public func addQuadCurveToPoint(control control: C4Point, point: C4Point) {
CGPathAddQuadCurveToPoint(internalPath, nil, CGFloat(control.x), CGFloat(control.y), CGFloat(point.x), CGFloat(point.y))
}
/// Append a cubic Bézier curve from the current point to `point` with control points `control1` and `control2`
/// and move the current point to `point`.
public func addCurveToPoint(control1: C4Point, control2: C4Point, point: C4Point) {
CGPathAddCurveToPoint(internalPath, nil, CGFloat(control1.x), CGFloat(control1.y), CGFloat(control2.x), CGFloat(control2.y), CGFloat(point.x), CGFloat(point.y))
}
/// Append a line from the current point to the starting point of the current subpath and end the subpath.
public func closeSubpath() {
CGPathCloseSubpath(internalPath)
}
/// Add a rectangle to the path.
public func addRect(rect: C4Rect) {
CGPathAddRect(internalPath, nil, CGRect(rect))
}
/// Add a rounded rectangle to the path. The rounded rectangle coincides with the edges of `rect`. Each corner consists
/// of one-quarter of an ellipse with axes equal to `cornerWidth` and `cornerHeight`. The rounded rectangle forms a
/// complete subpath of the path --- that is, it begins with a "move to" and ends with a "close subpath" --- oriented
/// in the clockwise direction.
public func addRoundedRect(rect: C4Rect, cornerWidth: Double, cornerHeight: Double) {
CGPathAddRoundedRect(internalPath, nil, CGRect(rect), CGFloat(cornerWidth), CGFloat(cornerHeight))
}
/// Add an ellipse (an oval) inside `rect`. The ellipse is approximated by a sequence of Bézier curves. The center of
/// the ellipse is the midpoint of `rect`. If `rect` is square, then the ellipse will be circular with radius equal to
/// one-half the width (equivalently, one-half the height) of `rect`. If `rect` is rectangular, then the major- and
/// minor-axes will be the width and height of `rect`. The ellipse forms a complete subpath --- that is, it begins with
/// a "move to" and ends with a "close subpath" --- oriented in the clockwise direction.
public func addEllipse(rect: C4Rect) {
CGPathAddEllipseInRect(internalPath, nil, CGRect(rect))
}
/// Add an arc of a circle, possibly preceded by a straight line segment. The arc is approximated by a sequence of
/// Bézier curves.
///
/// - parameter center: The center of the arc.
/// - parameter radius: The radius of the arc.
/// - parameter startAngle: The angle in radians to the first endpoint of the arc, measured counter-clockwise from the positive
/// x-axis.
/// - parameter delta: The angle between `startAngle` and the second endpoint of the arc, in radians. If `delta' is positive,
/// then the arc is drawn counter-clockwise; if negative, clockwise.
public func addRelativeArc(center: C4Point, radius: Double, startAngle: Double, delta: Double) {
CGPathAddRelativeArc(internalPath, nil, CGFloat(center.x), CGFloat(center.y), CGFloat(radius), CGFloat(startAngle), CGFloat(delta))
}
/// Add an arc of a circle, possibly preceded by a straight line segment. The arc is approximated by a sequence of
/// Bézier curves.
///
/// Note that using values very near 2π can be problematic. For example, setting `startAngle` to 0, `endAngle` to 2π,
/// and `clockwise` to true will draw nothing. (It's easy to see this by considering, instead of 0 and 2π, the values
/// ε and 2π - ε, where ε is very small.) Due to round-off error, however, it's possible that passing the value
/// `2 * M_PI` to approximate 2π will numerically equal to 2π + δ, for some small δ; this will cause a full circle to
/// be drawn.
///
/// If you want a full circle to be drawn clockwise, you should set `startAngle` to 2π, `endAngle` to 0, and
/// `clockwise` to true. This avoids the instability problems discussed above.
///
/// - parameter center: The center of the arc.
/// - parameter radius: The radius of the arc.
/// - parameter startAngle: The angle to the first endpoint of the arc in radians.
/// - parameter endAngle: The angle to the second endpoint of the arc.
/// - parameter clockwise: If true the arc is drawn clockwise.
public func addArc(center: C4Point, radius: Double, startAngle: Double, endAngle: Double, clockwise: Bool) {
CGPathAddArc(internalPath, nil, CGFloat(center.x), CGFloat(center.y), CGFloat(radius), CGFloat(startAngle), CGFloat(endAngle), clockwise)
}
/// Add an arc of a circle, possibly preceded by a straight line segment. The arc is approximated by a sequence of
/// Bézier curves. The resulting arc is tangent to the line from the current point to `point1`, and the line from
/// `point1` to `point2`.
public func addArcToPoint(point1: C4Point, point2: C4Point, radius: Double) {
CGPathAddArcToPoint(internalPath, nil, CGFloat(point1.x), CGFloat(point1.y), CGFloat(point2.x), CGFloat(point2.y), CGFloat(radius))
}
/// Append a path.
///
/// - parameter path: A new C4Path that is added to the end of the receiver.
public func addPath(path: C4Path) {
CGPathAddPath(internalPath, nil, path.internalPath)
}
/// Transform a path.
///
/// - parameter transform: A C4Transform to be applied to the receiver.
public func transform(transform: C4Transform) {
var t = transform.affineTransform
internalPath = CGPathCreateMutableCopyByTransformingPath(internalPath, &t)!
}
}
| mit | 4e842046620eaa272ca35bf38d7b84dd | 49.5625 | 168 | 0.688504 | 4.405949 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/ViewControllers/Utils/MessageRecipientStatusUtils.swift | 1 | 8075 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalServiceKit
import SignalMessaging
@objc public enum MessageReceiptStatus: Int {
case uploading
case sending
case sent
case delivered
case read
case failed
case skipped
}
@objc
public class MessageRecipientStatusUtils: NSObject {
// MARK: Initializers
@available(*, unavailable, message:"do not instantiate this class.")
private override init() {
}
// This method is per-recipient.
@objc
public class func recipientStatus(outgoingMessage: TSOutgoingMessage,
recipientState: TSOutgoingMessageRecipientState) -> MessageReceiptStatus {
let (messageReceiptStatus, _, _) = recipientStatusAndStatusMessage(outgoingMessage: outgoingMessage,
recipientState: recipientState)
return messageReceiptStatus
}
// This method is per-recipient.
@objc
public class func shortStatusMessage(outgoingMessage: TSOutgoingMessage,
recipientState: TSOutgoingMessageRecipientState) -> String {
let (_, shortStatusMessage, _) = recipientStatusAndStatusMessage(outgoingMessage: outgoingMessage,
recipientState: recipientState)
return shortStatusMessage
}
// This method is per-recipient.
@objc
public class func longStatusMessage(outgoingMessage: TSOutgoingMessage,
recipientState: TSOutgoingMessageRecipientState) -> String {
let (_, _, longStatusMessage) = recipientStatusAndStatusMessage(outgoingMessage: outgoingMessage,
recipientState: recipientState)
return longStatusMessage
}
// This method is per-recipient.
class func recipientStatusAndStatusMessage(outgoingMessage: TSOutgoingMessage,
recipientState: TSOutgoingMessageRecipientState) -> (status: MessageReceiptStatus, shortStatusMessage: String, longStatusMessage: String) {
switch recipientState.state {
case .failed:
let shortStatusMessage = NSLocalizedString("MESSAGE_STATUS_FAILED_SHORT", comment: "status message for failed messages")
let longStatusMessage = NSLocalizedString("MESSAGE_STATUS_FAILED", comment: "status message for failed messages")
return (status:.failed, shortStatusMessage:shortStatusMessage, longStatusMessage:longStatusMessage)
case .sending:
if outgoingMessage.hasAttachments() {
assert(outgoingMessage.messageState == .sending)
let statusMessage = NSLocalizedString("MESSAGE_STATUS_UPLOADING",
comment: "status message while attachment is uploading")
return (status:.uploading, shortStatusMessage:statusMessage, longStatusMessage:statusMessage)
} else {
assert(outgoingMessage.messageState == .sending)
let statusMessage = NSLocalizedString("MESSAGE_STATUS_SENDING",
comment: "message status while message is sending.")
return (status:.sending, shortStatusMessage:statusMessage, longStatusMessage:statusMessage)
}
case .sent:
if let readTimestamp = recipientState.readTimestamp {
let timestampString = DateUtil.formatPastTimestampRelativeToNow(readTimestamp.uint64Value)
let shortStatusMessage = timestampString
let longStatusMessage = NSLocalizedString("MESSAGE_STATUS_READ", comment: "status message for read messages") + " " + timestampString
return (status:.read, shortStatusMessage:shortStatusMessage, longStatusMessage:longStatusMessage)
}
if let deliveryTimestamp = recipientState.deliveryTimestamp {
let timestampString = DateUtil.formatPastTimestampRelativeToNow(deliveryTimestamp.uint64Value)
let shortStatusMessage = timestampString
let longStatusMessage = NSLocalizedString("MESSAGE_STATUS_DELIVERED",
comment: "message status for message delivered to their recipient.") + " " + timestampString
return (status:.delivered, shortStatusMessage:shortStatusMessage, longStatusMessage:longStatusMessage)
}
let statusMessage =
NSLocalizedString("MESSAGE_STATUS_SENT",
comment: "status message for sent messages")
return (status:.sent, shortStatusMessage:statusMessage, longStatusMessage:statusMessage)
case .skipped:
let statusMessage = NSLocalizedString("MESSAGE_STATUS_RECIPIENT_SKIPPED",
comment: "message status if message delivery to a recipient is skipped. We skip delivering group messages to users who have left the group or unregistered their Signal account.")
return (status:.skipped, shortStatusMessage:statusMessage, longStatusMessage:statusMessage)
}
}
// This method is per-message.
internal class func receiptStatusAndMessage(outgoingMessage: TSOutgoingMessage) -> (status: MessageReceiptStatus, message: String) {
switch outgoingMessage.messageState {
case .failed:
// Use the "long" version of this message here.
return (.failed, NSLocalizedString("MESSAGE_STATUS_FAILED", comment: "status message for failed messages"))
case .sending:
if outgoingMessage.hasAttachments() {
return (.uploading, NSLocalizedString("MESSAGE_STATUS_UPLOADING",
comment: "status message while attachment is uploading"))
} else {
return (.sending, NSLocalizedString("MESSAGE_STATUS_SENDING",
comment: "message status while message is sending."))
}
case .sent:
if outgoingMessage.readRecipientAddresses().count > 0 {
return (.read, NSLocalizedString("MESSAGE_STATUS_READ", comment: "status message for read messages"))
}
if outgoingMessage.wasDeliveredToAnyRecipient {
return (.delivered, NSLocalizedString("MESSAGE_STATUS_DELIVERED",
comment: "message status for message delivered to their recipient."))
}
return (.sent, NSLocalizedString("MESSAGE_STATUS_SENT",
comment: "status message for sent messages"))
default:
owsFailDebug("Message has unexpected status: \(outgoingMessage.messageState).")
return (.sent, NSLocalizedString("MESSAGE_STATUS_SENT",
comment: "status message for sent messages"))
}
}
// This method is per-message.
@objc
public class func receiptMessage(outgoingMessage: TSOutgoingMessage) -> String {
let (_, message ) = receiptStatusAndMessage(outgoingMessage: outgoingMessage)
return message
}
// This method is per-message.
@objc
public class func recipientStatus(outgoingMessage: TSOutgoingMessage) -> MessageReceiptStatus {
let (status, _ ) = receiptStatusAndMessage(outgoingMessage: outgoingMessage)
return status
}
@objc
public class func description(forMessageReceiptStatus value: MessageReceiptStatus) -> String {
switch(value) {
case .read:
return "read"
case .uploading:
return "uploading"
case .delivered:
return "delivered"
case .sent:
return "sent"
case .sending:
return "sending"
case .failed:
return "failed"
case .skipped:
return "skipped"
}
}
}
| gpl-3.0 | cc0b7f0b47cc02762e3e9ef50f63909d | 47.353293 | 228 | 0.629598 | 6.393508 | false | false | false | false |
novi/mysql-swift | Sources/MySQL/Sync.swift | 1 | 1104 | //
// Sync.swift
// MySQL
//
// Created by Yusuke Ito on 1/12/16.
// Copyright © 2016 Yusuke Ito. All rights reserved.
//
#if os(Linux)
import Glibc
#elseif os(OSX)
import Darwin.C
#endif
fileprivate final class Mutex {
private var mutex = pthread_mutex_t()
init() {
pthread_mutex_init(&mutex, nil)
}
func lock() {
pthread_mutex_lock(&mutex)
}
func unlock() {
pthread_mutex_unlock(&mutex)
}
deinit {
pthread_mutex_destroy(&mutex)
}
}
internal struct Atomic<T> {
private var value: T
private let mutex = Mutex()
init(_ value: T) {
self.value = value
}
mutating func syncWriting<R>( _ block: (inout T) throws -> R) rethrows -> R {
mutex.lock()
defer {
mutex.unlock()
}
let result = try block(&value)
return result
}
func sync<R>( _ block: (T) throws -> R) rethrows -> R {
mutex.lock()
defer {
mutex.unlock()
}
let result = try block(value)
return result
}
}
| mit | 2c26544004deb6d5bb1c506b216cb9aa | 18.350877 | 81 | 0.527652 | 3.764505 | false | false | false | false |
crisisGriega/swift-simple-tree-drawer | TreeStructure/ViewController.swift | 1 | 1694 | //
// ViewController.swift
// TreeStructure
//
// Created by Gerardo Garrido on 13/07/16.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let root = Node.init(name: "1");
let node2 = Node.init(name: "2");
let node3 = Node.init(name: "3");
let node4 = Node.init(name: "4");
root.insertChildren([node2, node3, node4]);
let node5 = Node.init(name: "5");
let node6 = Node.init(name: "6");
let node7 = Node.init(name: "7");
let node8 = Node.init(name: "8");
node2.insertChildren([node5, node6, node7, node8]);
print(node2.neededSize());
let node9 = Node.init(name: "9");
let node10 = Node.init(name: "10");
node3.insertChildren([node9, node10]);
let node11 = Node.init(name: "11");
node5.insertChild(node11);
let node12 = Node.init(name: "12");
let node13 = Node.init(name: "13");
node7.insertChildren([node12, node13]);
let node14 = Node.init(name: "14");
let node15 = Node.init(name: "15");
let node16 = Node.init(name: "16");
let node17 = Node.init(name: "17");
node11.insertChildren([node14, node15, node16, node17]);
let rootView = NodeView.initFromXib(with: root);
rootView.drawChildrenNodes();
self.view.addSubview(rootView);
rootView.frame.origin.y = 50;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 5d743b78cc6e55555cf5c98e7aa7faaf | 27.711864 | 64 | 0.561983 | 3.739514 | false | false | false | false |
RxSwiftCommunity/RxMKMapView | Example/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift | 1 | 8505 | //
// URLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// RxCocoa URL errors.
public enum RxCocoaURLError
: Swift.Error {
/// Unknown error occurred.
case unknown
/// Response is not NSHTTPURLResponse
case nonHTTPResponse(response: URLResponse)
/// Response is not successful. (not in `200 ..< 300` range)
case httpRequestFailed(response: HTTPURLResponse, data: Data?)
/// Deserialization error.
case deserializationError(error: Swift.Error)
}
extension RxCocoaURLError
: CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error has occurred."
case let .nonHTTPResponse(response):
return "Response is not NSHTTPURLResponse `\(response)`."
case let .httpRequestFailed(response, _):
return "HTTP request failed with `\(response.statusCode)`."
case let .deserializationError(error):
return "Error during deserialization of the response: \(error)"
}
}
}
private func escapeTerminalString(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil)
}
private func convertURLRequestToCurlCommand(_ request: URLRequest) -> String {
let method = request.httpMethod ?? "GET"
var returnValue = "curl -X \(method) "
if let httpBody = request.httpBody, request.httpMethod == "POST" || request.httpMethod == "PUT" {
let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8)
if let body = maybeBody {
returnValue += "-d \"\(escapeTerminalString(body))\" "
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString(key as String)
let escapedValue = escapeTerminalString(value as String)
returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.url?.absoluteString ?? "<unknown url>"
returnValue += "\n\"\(escapeTerminalString(URLString))\""
returnValue += " -i -v"
return returnValue
}
private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? HTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Canceled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension Reactive where Base: URLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
return Observable.create { observer in
// smart compiler should be able to optimize this out
let d: Date?
if URLSession.rx.shouldLogRequest(request) {
d = Date()
}
else {
d = nil
}
let task = self.base.dataTask(with: request) { data, response, error in
if URLSession.rx.shouldLogRequest(request) {
let interval = Date().timeIntervalSince(d ?? Date())
print(convertURLRequestToCurlCommand(request))
#if os(Linux)
print(convertResponseToString(response, error.flatMap { $0 as NSError }, interval))
#else
print(convertResponseToString(response, error.map { $0 as NSError }, interval))
#endif
}
guard let response = response, let data = data else {
observer.on(.error(error ?? RxCocoaURLError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response)))
return
}
observer.on(.next((httpResponse, data)))
observer.on(.completed)
}
task.resume()
return Disposables.create(with: task.cancel)
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
public func data(request: URLRequest) -> Observable<Data> {
return self.response(request: request).map { pair -> Data in
if 200 ..< 300 ~= pair.0.statusCode {
return pair.1
}
else {
throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1)
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable<Any> {
return self.data(request: request).map { data -> Any in
do {
return try JSONSerialization.jsonObject(with: data, options: options)
} catch let error {
throw RxCocoaURLError.deserializationError(error: error)
}
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter url: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
public func json(url: Foundation.URL) -> Observable<Any> {
self.json(request: URLRequest(url: url))
}
}
extension Reactive where Base == URLSession {
/// Log URL requests to standard output in curl format.
public static var shouldLogRequest: (URLRequest) -> Bool = { _ in
#if DEBUG
return true
#else
return false
#endif
}
}
| mit | 256cb8c48b87e0d7d51bfe89060bfc97 | 34.433333 | 119 | 0.627705 | 5.246144 | false | false | false | false |
yar1vn/Swiftilities | Swiftilities/Swiftilities/WebViewController.swift | 1 | 1585 | //
// WebViewController.swift
// Swiftilities
//
// Created by Yariv on 1/29/15.
// Copyright (c) 2015 Yariv. All rights reserved.
//
import UIKit
class WebViewController: UIViewController {
@IBOutlet weak var webView: UIWebView?
private let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
var url: NSURL? {
didSet {
loadURL()
}
}
func loadURL() {
if let url = url {
webView?.loadRequest(NSURLRequest(URL: url))
}
}
override func viewDidLoad() {
super.viewDidLoad()
webView?.scalesPageToFit = true
if webView?.request == nil {
loadURL()
}
}
}
// MARK:- UIWebViewDelegate
extension WebViewController: UIWebViewDelegate {
func webViewDidStartLoad(webView: UIWebView) {
navigationItem.titleView = activityIndicator
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) {
navigationItem.titleView = nil
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
navigationItem.titleView = nil
presentAlertController(title: "Cannot Load Page", message: "Please try again")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .Other:
return true
case .LinkClicked:
if let url = request.mainDocumentURL {
if url.canOpen() {
url.launchInSafari()
}
}
fallthrough
default:
return false
}
}
} | mit | 14ac721aba091f8baa0e044be345b198 | 21.027778 | 135 | 0.670032 | 4.876923 | false | false | false | false |
Adlai-Holler/Flux.swift | Examples/TodoMVC/TodoMVC/TodoItem.swift | 1 | 2556 | //
// TodoItem.swift
// TodoMVC
//
// Created by Adlai Holler on 2/6/16.
// Copyright © 2016 Adlai Holler. All rights reserved.
//
import CoreData
typealias TodoItemID = Int64
struct TodoItem {
static let entityName = "TodoItem"
enum Property: String {
case title
case id
case completed
case softDeleted
}
var id: TodoItemID
/// This is nil if the object was not created from an NSManagedObject.
let objectID: NSManagedObjectID?
var title: String?
var completed: Bool
var softDeleted: Bool
init(id: TodoItemID, title: String?, completed: Bool) {
self.id = id
self.objectID = nil
self.title = title
self.completed = completed
self.softDeleted = false
}
init(object: NSManagedObject) {
assert(object.entity.name == TodoItem.entityName)
title = object.valueForKey(Property.title.rawValue) as! String?
completed = object.valueForKey(Property.completed.rawValue) as! Bool
id = (object.valueForKey(Property.id.rawValue) as! NSNumber).longLongValue
softDeleted = object.valueForKey(Property.softDeleted.rawValue) as! Bool
objectID = object.objectID
}
func apply(object: NSManagedObject) {
guard object.entity.name == TodoItem.entityName else {
assertionFailure()
return
}
let idObj = NSNumber(longLong: id)
if object.valueForKey(Property.id.rawValue) as! NSNumber? != idObj {
object.setValue(idObj, forKey: Property.id.rawValue)
}
if object.valueForKey(Property.title.rawValue) as! String? != title {
object.setValue(title, forKey: Property.title.rawValue)
}
if object.valueForKey(Property.completed.rawValue) as! Bool != completed {
object.setValue(completed, forKey: Property.completed.rawValue)
}
if object.valueForKey(Property.softDeleted.rawValue) as! Bool != softDeleted {
object.setValue(softDeleted, forKey: Property.softDeleted.rawValue)
}
}
}
extension TodoItem {
static var maxId: TodoItemID {
let storedValue = TodoItemID(NSUserDefaults.standardUserDefaults().integerForKey("TodoItemMaxID"))
return storedValue == 0 ? 1 : storedValue
}
static func incrementMaxID() {
let newValue = maxId + 1
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(Int(newValue), forKey: "TodoItemMaxID")
defaults.synchronize()
}
} | mit | eb4be74bfb29194a59c707cea5a40dcf | 30.555556 | 106 | 0.651272 | 4.5625 | false | false | false | false |
lukejmann/FBLA2017 | FBLA2017/ItemsCollectionView.swift | 1 | 24490 | import UIKit
import NVActivityIndicatorView
import Firebase
import FirebaseDatabase
import FirebaseStorage
import CoreLocation
import QuiltView
import Hero
import Device
import PermissionScope
import ChameleonFramework
import DZNEmptyDataSet
import PopoverPicker
import Instructions
//This class is the collection view in the browse section of the app
class ImageCollectionViewController: UICollectionViewController {
fileprivate let reuseIdentifier = "ItemCell"
fileprivate let sectionInsets = UIEdgeInsets(top: 2, left: 2, bottom: 5, right: 2)
private typealias imageAndIndex = (Int, UIImage)
var coverImages = [UIImage?]()
var itemKeys=[String]()
var coverImageKeys=[String]()
var categories = [String]()
fileprivate let itemsPerRow: CGFloat = 3
let walkthroughController = CoachMarksController()
var nextItemDelegate: NextItemDelegate?
var refresher = UIRefreshControl()
var activityIndicator: NVActivityIndicatorView?
var readyToLoad = true
var loadingImages = true
@IBOutlet weak var filterButton: UIButton!
var originalImages = [UIImage?]()
var originalItemKeys=[String]()
var originalCoverImageKeys = [String]()
override func viewDidLoad() {
super.viewDidLoad()
currentUser.loadGroup()
collectionView?.emptyDataSetSource = self
collectionView?.emptyDataSetDelegate = self
if let _ = self.filterButton {
self.filterButton.titleLabel?.textAlignment = .right
}
self.walkthroughController.dataSource = self
activityIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.view)
self.refresher.addTarget(self, action: #selector(ImageCollectionViewController.refresh), for: .valueChanged)
self.collectionView?.refreshControl = refresher
currentView = self.view
let layout = self.collectionView?.collectionViewLayout as! QuiltView
layout.scrollDirection = UICollectionViewScrollDirection.vertical
switch Device.size() {
case .screen4_7Inch:layout.itemBlockSize = CGSize(width: 62, height: 62)
case .screen5_5Inch: layout.itemBlockSize = CGSize(width: 67, height: 67)
default: layout.itemBlockSize = CGSize(width: 67, height: 67)
}
currentUser.setupUser(id: (FIRAuth.auth()?.currentUser?.uid)!, isLoggedIn: true)
loadCoverImages()
}
override func viewDidAppear(_ animated: Bool) {
if !UserDefaults.standard.bool(forKey: "BrowseWalkthroughHasLoaded") {
self.walkthroughController.startOn(self)
UserDefaults.standard.set(true, forKey: "BrowseWalkthroughHasLoaded")
}
if !UserDefaults.standard.bool(forKey: "hasAskedPermissions") {
UserDefaults.standard.set(true, forKey: "hasAskedPermissions")
let permissionView = PermissionScope()
permissionView.buttonFont = Fonts.bold.get(size: 15)
permissionView.labelFont = Fonts.bold.get(size: 15)
permissionView.headerLabel.text = "First, permissions"
permissionView.bodyLabel.text = "Just tap a button below to get started"
permissionView.bodyLabel.font = Fonts.regular.get(size: 16)
permissionView.headerLabel.font = Fonts.bold.get(size: 21)
permissionView.permissionLabelColor = UIColor.flatNavyBlueDark
permissionView.permissionButtonTextColor = UIColor.flatNavyBlueDark
permissionView.permissionButtonBorderColor = UIColor.flatNavyBlueDark
permissionView.closeButton.setTitle("", for: .normal)
permissionView.authorizedButtonColor = UIColor.flatNavyBlueDark
permissionView.addPermission(LocationWhileInUsePermission(),
message: "We use this to show item location")
permissionView.addPermission(CameraPermission(),
message: "We use this to take pictures of items as well as set profile images")
permissionView.addPermission(PhotosPermission(),
message: "We use this to find pictures of items and find profile images")
permissionView.show()
}
}
var itemIndex = 0
var currentView: UIView?
var currentVC: UIViewController?
var firstDetailVC: UIViewController?
// MARK: - Filter items
@IBAction func filterButtonPressed() {
let popoverView = PickerDialog.getPicker()
let pickerData = [
["value": "Any", "display": "Any"],
["value": "School Supplies", "display": "School Supplies"],
["value": "Electronics", "display": "Electronics"],
["value": "Home and Garden", "display": "Home and Garden"],
["value": "Clothing", "display": "Clothing"],
["value": "Sports and Games", "display": "Sports and Games"],
["value": "Other", "display": "Other"],
]
popoverView.show("Select Category", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", options: pickerData, selected: "Any") {
(value) -> Void in
self.filterButton.setTitle(value, for: .normal)
self.filterItems(category: value)
}
}
func filterItems(category: String) {
coverImages = originalImages
itemKeys = originalItemKeys
coverImageKeys = originalCoverImageKeys
if category == "Any" || category == "Filter"{
collectionView?.reloadData()
return
}
if !loadingImages {
var i = 0
for cat in categories {
if cat != category {
if i<coverImages.count {
coverImages[i]=nil
coverImageKeys[i]="❌"
itemKeys[i]="❌"
}
}
i += 1
}
}
coverImages = coverImages.filter { $0 != nil }.map { $0! }
coverImageKeys = coverImageKeys.filter { $0 != "❌" }.map { $0 }
itemKeys = itemKeys.filter { $0 != "❌" }.map { $0 }
collectionView?.reloadData()
}
func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int {
return 1
}
}
extension ImageCollectionViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
}
// MARK: - Data Source
extension ImageCollectionViewController {
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return coverImages.count
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return coverImages.count
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! PhotoCell
cell.imageView.image = coverImages[indexPath.row]
cell.delegate = self
if indexPath.row < itemKeys.count {
cell.keyString = itemKeys[indexPath.row]
cell.coverImageKeyString = coverImageKeys[indexPath.row]
}
return cell
}
func refresh() {
loadingImages = true
self.collectionView?.reloadData()
itemIndex = 0
activityIndicator?.startAnimating()
coverImages.removeAll()
itemKeys.removeAll()
coverImageKeys.removeAll()
currentView = nil
firstDetailVC = nil
loadCoverImages()
}
}
//MARK:- Setup quilt view
extension ImageCollectionViewController : QuiltViewDelegate {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, blockSizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
let photo = coverImages[indexPath.row]
let height = photo?.size.height
let width = photo?.size.width
let dynamicHeightRatio = height! / width!
print(widthPerItem * dynamicHeightRatio)
return CGSize(width: 2, height: 2 * dynamicHeightRatio)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetsForItemAtIndexPath indexPath: IndexPath) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
}
//MARK :- Manage when category changed
extension ImageCollectionViewController:CategoryLoadedDelegate {
func loaded(category: ItemCategory) {
categories[category.index!] = category.category!
}
}
//MARK:- Load cover images
extension ImageCollectionViewController {
func loadCoverImages() {
let ref = FIRDatabase.database().reference().child(currentGroup).child("coverImagePaths")
let storage = FIRStorage.storage()
ref.observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
var i = 0
for snapshot in snapshots {
if let path = snapshot.value as? String {
let coverImagePath = storage.reference(forURL: path)
coverImagePath.data(withMaxSize: 1 * 1_024 * 1_024) { data, error in
if error != nil {
// Might want to add this back but gets error when making item
// ErrorGenerator.presentError(view: self, type: "Cover Images", error: error!)
} else {
let image = UIImage(data: data!)
self.coverImages.append(image!)
if let extractedKey: String = path.substring(start: 44, end: 64) {
self.itemKeys.append(extractedKey)
Item.getCategory(key: extractedKey, index: i, delegate: self)
self.coverImageKeys.append((snapshot.key as? String)!)
}
i += 1
if i == snapshots.count {
self.originalImages = self.coverImages
self.originalItemKeys = self.itemKeys
self.originalCoverImageKeys = self.coverImageKeys
self.activityIndicator?.stopAnimating()
self.refresher.endRefreshing()
self.loadingImages = false
self.filterItems(category: (self.filterButton.titleLabel?.text)!)
}
}
}
}
}
self.categories = [String](repeating: "", count:snapshots.count)
if snapshots.count == 0 {
self.activityIndicator?.stopAnimating()
self.refresher.endRefreshing()
self.loadingImages = false
self.collectionView?.reloadData()
}
}
})
}
}
//MARK:- Manage PhotoCell Loading and presenting
extension ImageCollectionViewController: PhotoCellDelegate {
func buttonPressed(keyString: String, coverImageKeyString: String ) {
if readyToLoad {
readyToLoad = false
generateImages(keyString: keyString, inImageView: false, coverImageKey: coverImageKeyString)
let index = itemKeys.index(of: keyString)
itemIndex = index!
}
}
//This functoin generages item information when an item is selected
func generateImages(keyString: String, inImageView: Bool, coverImageKey: String) {
let activityIndicator: NVActivityIndicatorView
if (self.currentView != nil) {
activityIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.currentView!)
} else {
activityIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.view)
}
var name: String?=nil
var about: String?=nil
var categorey: String?=nil
var latitudeString: String?=nil
var longitudeString: String?=nil
var addressString: String?=nil
var cents: Int?=nil
var condition: Int?=nil
var userID: String?=nil
let ref = FIRDatabase.database().reference().child(currentGroup).child("items").child(keyString)
let user = User()
let item = Item()
ref.observe(.value, with: {(snapshot) in
let value = snapshot.value as? NSDictionary
name = value?["title"] as? String ?? ""
about = value?["about"] as? String ?? ""
categorey = value?["category"] as? String ?? ""
latitudeString = value?["locationLatitude"] as? String ?? ""
longitudeString = value?["locationLongitude"] as? String ?? ""
addressString = value?["locationString"] as? String ?? ""
condition = value?["condition"] as? Int ?? 0
cents = value?["cents"] as? Int ?? 0
userID = value?["userID"] as? String ?? ""
user.setupUser(id: userID!, isLoggedIn: false)
})
let storage = FIRStorage.storage()
let middle = storyboard?.instantiateViewController(withIdentifier: "pulley") as! FirstContainerViewController
user.delegate = middle
ref.child("imagePaths").observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
var i = 0
var images=[UIImage?]()
for snapshot in snapshots {
images.append(nil)
if let path = snapshot.value as? String {
let imagePath = storage.reference(forURL: path)
imagePath.data(withMaxSize: 1 * 6_000 * 6_000) { data, error in
if let error = error {
ErrorGenerator.presentError(view: self, type: "Item Images", error: error)
} else {
let image = UIImage(data: data!)
images[Int(snapshot.key)!] = image
print(i)
i += 1
if i == snapshots.count {
activityIndicator.stopAnimating()
item.categorey = categorey
item.name = name
item.about = about
item.latitudeString = latitudeString
item.longitudeString = longitudeString
item.addressString = addressString
item.cents = cents
item.condition = condition
item.images = images as? [UIImage]
item.keyString = keyString
item.coverImagePath = path
item.user = user
middle.nextItemDelegate = self
middle.dismissDelegate = self
user.delegate = middle
middle.item = item
FIRDatabase.database().reference().child(currentGroup).child("coverImagePaths").child(coverImageKey).observe(.value, with: { (snapshot) in
if let path = snapshot.value as? String {
item.coverImagePath = path
if inImageView {
if let vc = self.currentVC as? FirstContainerViewController {
vc.present(middle, animated: true)
middle.vcToDismiss = vc
}
} else {
self.present(middle, animated: true, completion: nil)
self.firstDetailVC = middle
}
self.currentView = middle.view
self.currentVC = middle
}
})
self.readyToLoad = true
}
}
}
}
}
}
})
let ref2 = FIRDatabase.database().reference().child(currentGroup).child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("likedCoverImages")
ref2.observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snapshot in snapshots {
if let path = snapshot.key as? String {
print("Local path\(keyString)")
print(path)
if path == keyString {
item.hasLiked = true
}
}
}
}
})
}
}
//MARK:- Item view dismissed
extension ImageCollectionViewController:NextItemDelegate, DismissDelgate {
func goToNextItem() {
if itemIndex + 1 < itemKeys.count {
itemIndex += 1
generateImages(keyString: itemKeys[itemIndex], inImageView: true, coverImageKey: coverImageKeys[itemIndex])
} else {
itemIndex = 0
generateImages(keyString: itemKeys[itemIndex], inImageView: true, coverImageKey: coverImageKeys[itemIndex])
itemIndex += 1
}
}
func switchCurrentVC(shouldReload: Bool) {
currentVC = nil
currentView = self.view
firstDetailVC?.dismiss(animated: false, completion: nil)
if shouldReload {
coverImages.removeAll()
itemKeys.removeAll()
coverImageKeys.removeAll()
currentView = nil
firstDetailVC = nil
}
}
}
extension ImageCollectionViewController:UploadFinishedDelegate {
func reload() {
refresh()
}
}
//MARK:- Empty Data Set
extension ImageCollectionViewController:DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
if !loadingImages {
return NSAttributedString(string: "Huh", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
if !loadingImages {
return NSAttributedString(string: "It doesn't look like there are any items here", attributes: [NSFontAttributeName: Fonts.regular.get(size: 17) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! {
if !loadingImages {
return NSAttributedString(string: "Press Here To Refresh", attributes: [NSFontAttributeName: Fonts.bold.get(size: 25) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) {
refresh()
}
}
//MARK:- Walkthrough
extension ImageCollectionViewController: CoachMarksControllerDataSource, CoachMarksControllerDelegate {
func coachMarksController(_ coachMarksController: CoachMarksController,
coachMarkAt index: Int) -> CoachMark {
return coachMarksController.helper.makeCoachMark(for: self.filterButton)
}
func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkViewsAt index: Int, madeFrom coachMark: CoachMark) -> (bodyView: CoachMarkBodyView, arrowView: CoachMarkArrowView?) {
let view = coachMarksController.helper.makeDefaultCoachViews(withArrow: true, arrowOrientation: coachMark.arrowOrientation)
view.bodyView.hintLabel.text = "Tap this button to filter items"
view.bodyView.hintLabel.font = Fonts.bold.get(size: 16)
view.bodyView.nextLabel.font = Fonts.bold.get(size: 16)
view.bodyView.nextLabel.text = "Ok!"
return (bodyView: view.bodyView, arrowView: view.arrowView)
}
override func viewWillDisappear(_ animated: Bool) {
self.walkthroughController.stop(immediately: true)
}
}
// inspired by http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift
extension String {
func substring(start: Int, end: Int) -> String {
if (start < 0 || start > self.characters.count) {
return ""
} else if end < 0 || end > self.characters.count {
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: end)
let range = startIndex..<endIndex
return self.substring(with: range)
}}
// From: http://stackoverflow.com/questions/32612760/resize-image-without-losing-quality
struct CommonUtils {
static func imageWithImage(image: UIImage, scaleToSize newSize: CGSize, isAspectRation aspect: Bool) -> UIImage {
let originRatio = image.size.width / image.size.height;//CGFloat
let newRatio = newSize.width / newSize.height
var sz: CGSize = CGSize.zero
if (!aspect) {
sz = newSize
} else {
if (originRatio < newRatio) {
sz.height = newSize.height
sz.width = newSize.height * originRatio
} else {
sz.width = newSize.width
sz.height = newSize.width / originRatio
}
}
let scale: CGFloat = 1.0
sz.width /= scale
sz.height /= scale
UIGraphicsBeginImageContextWithOptions(sz, false, scale)
image.draw(in: CGRect(x: 0, y: 0, width: sz.width, height: sz.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| mit | 41248601a02fe6536ae8ba2eea0d1208 | 41.210345 | 202 | 0.551916 | 5.854137 | false | false | false | false |
zxpLearnios/MyProject | test_projectDemo1/GuideVC/Voice&&vedio/MyLoadProgressView.swift | 1 | 700 | //
// MyLoadProgressView.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/6/24.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
//
import UIKit
class MyLoadProgressView: UIView {
var startPoint:CGPoint = CGPoint.zero
var stopPoint:CGPoint = CGPoint.zero
override func draw(_ rect: CGRect) {
super.draw(rect)
// 缓冲条
let beziPath = UIBezierPath.init()
//
beziPath.move(to: startPoint)
beziPath.addLine(to: stopPoint)
beziPath.lineWidth = 6
beziPath.lineJoinStyle = .round
UIColor.red.setStroke()
beziPath.stroke()
}
}
| mit | fdcca2c7e8dc671d098a64d4d6e6101a | 18.742857 | 57 | 0.589001 | 4.213415 | false | false | false | false |
ctinnell/ct-playgrounds | HackerRank/hackerrank7.playground/Contents.swift | 1 | 862 | import Darwin
func numSquares(startNumber: Int, endNumber: Int) -> Int {
let squareRootStart = sqrt(Double(startNumber))
let squareRootEnd = sqrt(Double(endNumber))
let startRoot = floor(squareRootStart)
let endRoot = (ceil(squareRootEnd))
// print("square root start = \(sqrt(Double(startNumber)))")
// print("square root end = \(sqrt(Double(endNumber)))")
// print("startRoot = \(startRoot)")
// print("endRoot = \(endRoot)")
var numsquares = ((endRoot-1) - startRoot)
if squareRootStart == startRoot {
numsquares = numsquares + 1
}
if squareRootEnd == endRoot {
numsquares = numsquares + 1
}
return Int(numsquares)
}
var inputs = [465868129,988379794]
//inputs = [17,24]
//inputs = [3,9]
let numberOfSquares = numSquares(inputs[0], endNumber: inputs[1])
print(numberOfSquares)
| mit | 5ee091364eb1c728f24c733a457f871c | 27.733333 | 65 | 0.653132 | 3.621849 | false | false | false | false |
auth0/native-mobile-samples | iOS/profile-sample-swift/ProfileSample/AppDelegate.swift | 1 | 4481 | // AppDelegate.swift
//
// Copyright (c) 2014 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Lock
import SimpleKeychain
enum SessionNotification: String {
case Start = "StartSession"
case Finish = "FinishSession"
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.makeKeyAndVisible()
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoadingController")
self.window?.rootViewController = controller
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "finishSessionNotification:", name: SessionNotification.Finish.rawValue, object: nil)
notificationCenter.addObserver(self, selector: "startSessionNotification:", name: SessionNotification.Start.rawValue, object: nil)
let storage = Application.sharedInstance.storage
let lock = Application.sharedInstance.lock
lock.applicationLaunchedWithOptions(launchOptions)
lock.refreshIdTokenFromStorage(storage) { (error, token) -> () in
if error != nil {
self.showLock(false)
return;
}
storage.idToken = token
self.showMainRoot()
}
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return Application.sharedInstance.lock.handleURL(url, sourceApplication: sourceApplication)
}
func startSessionNotification(notification: NSNotification) {
self.showMainRoot()
}
func finishSessionNotification(notification: NSNotification) {
Application.sharedInstance.storage.clear()
self.showLock(true)
}
private func showMainRoot() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateInitialViewController()
self.window?.rootViewController = controller
UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionFlipFromLeft, animations: { }, completion: nil)
}
private func showLock(animated: Bool = false) {
let storage = Application.sharedInstance.storage
storage.clear()
let lock = Application.sharedInstance.lock.newLockViewController()
lock.onAuthenticationBlock = { (profile, token) in
switch(profile, token) {
case let (.Some(profile), .Some(token)):
storage.save(token: token, profile: profile)
NSNotificationCenter.defaultCenter().postNotificationName(SessionNotification.Start.rawValue, object: nil)
default:
print("Either auth0 token or profile of the user was nil, please check your Auth0 Lock config")
}
}
self.window?.rootViewController = lock
if animated {
UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionFlipFromLeft, animations: { }, completion: nil)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | a373463c6b3ff65c506f9e303de4dd3b | 42.086538 | 140 | 0.704753 | 5.086266 | false | false | false | false |
AssistoLab/FloatingLabel | FloatingLabel/src/input/InputType.swift | 2 | 5025 | //
// FloatingFieldInput.swift
// FloatingLabel
//
// Created by Kevin Hirsch on 4/08/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
internal protocol InputType {
//HACK: doesn't work without the leadings "__". It's a weird compilator bug.
var __text: String? { get set }
var __placeholder: String? { get set }
var __editing: Bool { get }
var __isEmpty: Bool { get }
var __inputView: UIView? { get set }
var __font: UIFont! { get set }
var __textColor: UIColor! { get set }
var __tintColor: UIColor! { get set }
var __textAlignment: NSTextAlignment { get set }
var __autocapitalizationType: UITextAutocapitalizationType { get set }
var __autocorrectionType: UITextAutocorrectionType { get set }
var __spellCheckingType: UITextSpellCheckingType { get set }
var __keyboardType: UIKeyboardType { get set }
var __keyboardAppearance: UIKeyboardAppearance { get set }
var __returnKeyType: UIReturnKeyType { get set }
var __enablesReturnKeyAutomatically: Bool { get set }
var __secureTextEntry: Bool { get set }
func viewForBaselineLayout() -> UIView
func intrinsicContentSize() -> CGSize
func invalidateIntrinsicContentSize()
func sizeToFit()
func canBecomeFirstResponder() -> Bool
func becomeFirstResponder() -> Bool
func resignFirstResponder() -> Bool
func isFirstResponder() -> Bool
func canResignFirstResponder() -> Bool
}
extension FloatingFieldTextField: InputType {
var __text: String? {
get { return text }
set { text = newValue }
}
var __placeholder: String? {
get { return placeholder }
set { placeholder = newValue }
}
var __editing: Bool {
return editing
}
var __isEmpty: Bool {
return text?.isEmpty ?? false
}
var __inputView: UIView? {
get { return inputView }
set { inputView = newValue }
}
var __font: UIFont! {
get { return font }
set { font = newValue }
}
var __textColor: UIColor! {
get { return textColor }
set { textColor = newValue }
}
var __tintColor: UIColor! {
get { return tintColor }
set { tintColor = newValue }
}
var __textAlignment: NSTextAlignment {
get { return textAlignment }
set { textAlignment = newValue }
}
var __autocapitalizationType: UITextAutocapitalizationType {
get { return autocapitalizationType }
set { autocapitalizationType = newValue }
}
var __autocorrectionType: UITextAutocorrectionType {
get { return autocorrectionType }
set { autocorrectionType = newValue }
}
var __spellCheckingType: UITextSpellCheckingType {
get { return spellCheckingType }
set { spellCheckingType = newValue }
}
var __keyboardType: UIKeyboardType {
get { return keyboardType }
set { keyboardType = newValue }
}
var __keyboardAppearance: UIKeyboardAppearance {
get { return keyboardAppearance }
set { keyboardAppearance = newValue }
}
var __returnKeyType: UIReturnKeyType {
get { return returnKeyType }
set { returnKeyType = newValue }
}
var __enablesReturnKeyAutomatically: Bool {
get { return enablesReturnKeyAutomatically }
set { enablesReturnKeyAutomatically = newValue }
}
var __secureTextEntry: Bool {
get { return secureTextEntry }
set { secureTextEntry = newValue }
}
}
extension FloatingFieldTextView: InputType {
var __text: String? {
get { return text }
set { text = newValue }
}
var __placeholder: String? {
get { return placeholder }
set { placeholder = newValue }
}
var __editing: Bool {
return isFirstResponder()
}
var __isEmpty: Bool {
return text?.isEmpty ?? false
}
var __inputView: UIView? {
get { return inputView }
set { inputView = newValue }
}
var __font: UIFont! {
get { return font }
set { font = newValue }
}
var __textColor: UIColor! {
get { return textColor }
set { textColor = newValue }
}
var __tintColor: UIColor! {
get { return tintColor }
set { tintColor = newValue }
}
var __textAlignment: NSTextAlignment {
get { return textAlignment }
set { textAlignment = newValue }
}
var __autocapitalizationType: UITextAutocapitalizationType {
get { return autocapitalizationType }
set { autocapitalizationType = newValue }
}
var __autocorrectionType: UITextAutocorrectionType {
get { return autocorrectionType }
set { autocorrectionType = newValue }
}
var __spellCheckingType: UITextSpellCheckingType {
get { return spellCheckingType }
set { spellCheckingType = newValue }
}
var __keyboardType: UIKeyboardType {
get { return keyboardType }
set { keyboardType = newValue }
}
var __keyboardAppearance: UIKeyboardAppearance {
get { return keyboardAppearance }
set { keyboardAppearance = newValue }
}
var __returnKeyType: UIReturnKeyType {
get { return returnKeyType }
set { returnKeyType = newValue }
}
var __enablesReturnKeyAutomatically: Bool {
get { return enablesReturnKeyAutomatically }
set { enablesReturnKeyAutomatically = newValue }
}
var __secureTextEntry: Bool {
get { return secureTextEntry }
set { secureTextEntry = newValue }
}
} | mit | d9eb9fa5de3058d72557d5e66b21f999 | 22.055046 | 77 | 0.695323 | 4.118852 | false | false | false | false |
southfox/jfwindguru | JFWindguru/Classes/Model/Forecast.swift | 1 | 6175 | //
// Forecast.swift
// Xoshem-watch
//
// Created by Javier Fuchs on 10/7/15.
// Copyright © 2015 Fuchs. All rights reserved.
//
import Foundation
/*
* Forecast
*
* Discussion:
* Model object representing forecast information, temperature, cloud cover (total, high,
* middle and lower), relative humidity, wind gusts, sea level pressure, feezing level,
* precipitations, wind (speed and direction)
*
* {
* "initstamp": 1444197600,
* "TMP": { },
* "TCDC": { },
* "HCDC": { },
* "MCDC": { },
* "LCDC": { },
* "RH": { },
* "GUST": { },
* "SLP": { },
* "FLHGT": { },
* "APCP": { },
* "WINDSPD": { },
* "WINDDIR": { },
* "WINDIRNAME": { },
* "TMPE": { },
* "initdate": "2015-10-07 06:00:00",
* "model_name": "GFS 27 km"
* }
*/
public class Forecast: Object, Mappable {
var initStamp : Int = 0
var TMP: TimeWeather? // temperature
var TCDC: TimeWeather? // Cloud cover (%) Total
var HCDC: TimeWeather? // Cloud cover (%) High
var MCDC: TimeWeather? // Cloud cover (%) Mid
var LCDC: TimeWeather? // Cloud cover (%) Low
var RH: TimeWeather? // Relative humidity: relative humidity in percent
var GUST: TimeWeather? // Wind gusts (knots)
var SLP: TimeWeather? // sea level pressure
var FLHGT: TimeWeather? // Freezing Level height in meters (0 degree isoterm)
var APCP: TimeWeather? // Precip. (mm/3h)
var WINDSPD: TimeWeather? // Wind speed (knots)
var WINDDIR: TimeWeather? // Wind direction
var WINDIRNAME: TimeWeather? // wind direction (name)
var TMPE: TimeWeather? // temperature in 2 meters above ground with correction to real altitude of the spot.
var initdate: String?
var model_name: String?
required public convenience init(map: [String:Any]) {
self.init()
mapping(map: map)
}
public func mapping(map: [String:Any]) {
initStamp = map["initstamp"] as? Int ?? 0
initdate = map["initdate"] as? String
model_name = map["model_name"] as? String
for (k, v) in map {
if let dict = v as? [String:Any] {
let tw = TimeWeather.init(map: dict)
switch k {
case "TMP": TMP = tw; break
case "TCDC": TCDC = tw; break
case "HCDC": HCDC = tw; break
case "MCDC": MCDC = tw; break
case "LCDC": LCDC = tw; break
case "RH": RH = tw; break
case "GUST": GUST = tw; break
case "SLP": SLP = tw; break
case "FLHGT": FLHGT = tw; break
case "APCP": APCP = tw; break
case "WINDSPD": WINDSPD = tw; break
case "WINDDIR": WINDDIR = tw; break
case "WINDIRNAME": WINDIRNAME = tw; break
case "TMPE": TMPE = tw; break
default:
break
}
}
}
}
public var description : String {
var aux : String = "\(type(of:self)): \n"
aux += "initStamp: \(initStamp)\n"
if let TCDC = TCDC {
aux += "Cloud cover Total: \(TCDC.description)\n"
}
if let HCDC = HCDC {
aux += "High: \(HCDC.description)\n"
}
if let MCDC = MCDC {
aux += "Mid: \(MCDC.description)\n"
}
if let LCDC = LCDC {
aux += "Low: \(LCDC.description)\n"
}
if let RH = RH {
aux += "Humidity: \(RH.description)\n"
}
if let SLP = SLP {
aux += "Sea Level pressure: \(SLP.description)\n"
}
if let FLHGT = FLHGT {
aux += "Freezing level: \(FLHGT.description)\n"
}
if let APCP = APCP {
aux += "Precipitation: \(APCP.description)\n"
}
if let GUST = GUST {
aux += "Wind gust: \(GUST.description)\n"
}
if let WINDSPD = WINDSPD {
aux += "Wind speed: \(WINDSPD.description)\n"
}
if let WINDDIR = WINDDIR {
aux += "Wind direccion: \(WINDDIR.description)\n"
}
if let WINDIRNAME = WINDIRNAME {
aux += "Wind name: \(WINDIRNAME.description)\n"
}
if let TMP = TMP {
aux += "Temp: \(TMP.description)\n"
}
if let TMPE = TMPE {
aux += "Temp real: \(TMPE.description)\n"
}
if let initdate = initdate {
aux += "initdate: \(initdate), "
}
if let model_name = model_name {
aux += "model_name: \(model_name).\n"
}
return aux
}
}
extension Forecast {
public func windDirectionName(hh: String?) -> String? {
return valueForKey(key : WINDIRNAME, hh: hh) as? String
}
public func windDirection(hh: String?) -> Float? {
return valueForKey(key : WINDDIR, hh: hh) as? Float
}
public func windSpeed(hh: String?) -> Float? {
return valueForKey(key : WINDSPD, hh: hh) as? Float
}
public func temperatureReal(hh: String?) -> Float? {
return valueForKey(key : TMPE, hh: hh) as? Float
}
public func cloudCoverTotal(hh: String?) -> Int? {
return valueForKey(key : TCDC, hh: hh) as? Int
}
public func precipitation(hh: String?) -> Float? {
return valueForKey(key : APCP, hh: hh) as? Float
}
//
// Private parts
//
private func valueForKey(key : TimeWeather?, hh: String?) -> AnyObject?
{
guard let key = key,
let hhString = hh else { return nil }
for k in key.keys {
if k == hhString {
guard let index = key.keys.index(of: k) else { continue }
if key.strings.count >= 0 && index < key.strings.count {
return key.strings[index] as AnyObject
}
else if key.floats.count >= 0 && index < key.floats.count{
return key.floats[index] as AnyObject
}
}
}
return nil
}
}
| mit | 4499d88b4ef77706127eedf03b3c191f | 30.025126 | 113 | 0.508098 | 3.792383 | false | false | false | false |
SuperAwesomeLTD/sa-kws-app-demo-ios | KWSDemo/GetAppDataController.swift | 1 | 3056 | //
// AppDataGetControllerViewController.swift
// KWSDemo
//
// Created by Gabriel Coman on 01/09/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import KWSiOSSDKObjC
import SAUtils
class GetAppDataController: KWSBaseController {
// outlets
@IBOutlet weak var appDataTable: UITableView!
@IBOutlet weak var addButton: KWSRedButton!
@IBOutlet weak var titleText: UILabel!
// data source
private var dataSource: RxDataSource?
override func viewDidLoad() {
super.viewDidLoad()
titleText.text = "page_getappdata_title".localized
addButton.setTitle("page_getappdata_button_add".localized.uppercased(), for: .normal)
// button tap
addButton.rx
.tap
.subscribe(onNext: { (Void) in
self.performSegue(withIdentifier: "GetAppDataToSetAppDataSegue", sender: self)
})
.addDisposableTo(disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set data source
RxKWS.getAppData()
.map { (appData: KWSAppData) -> GetAppDataViewModel in
return GetAppDataViewModel (appData.name, appData.value)
}
.toArray()
.subscribe(onNext: { (models: [GetAppDataViewModel]) in
self.dataSource = RxDataSource
.bindTable(self.appDataTable)
.customiseRow(cellIdentifier: "GetAppDataRowId",
cellType: GetAppDataViewModel.self,
cellHeight: 44)
{ (model, cell) in
let cell = cell as? GetAppDataRow
let model = model as? GetAppDataViewModel
cell?.nameLabel.text = model?.name
cell?.valueLabel.text = model?.value
}
self.dataSource?.update(models)
}, onError: { (error) in
self.networkError()
})
.addDisposableTo(disposeBag)
}
func networkError () {
SAAlert.getInstance().show(withTitle: "page_getappdata_popup_error_network_title".localized,
andMessage: "page_getappdata_popup_error_network_message".localized,
andOKTitle: "page_getappdata_popup_error_network_ok_button".localized,
andNOKTitle: nil,
andTextField: false,
andKeyboardTyle: .decimalPad,
andPressed: nil)
}
@IBAction func backAction(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
}
| gpl-3.0 | fa0085020e3d752c9cb4985fe53bd62b | 32.944444 | 105 | 0.523077 | 5.53442 | false | false | false | false |
mzaks/EntitasKit | Sources/Index.swift | 1 | 2626 | //
// Index.swift
// Entitas-Swift
//
// Created by Maxim Zaks on 18.06.17.
// Copyright © 2017 Maxim Zaks. All rights reserved.
//
import Foundation
public final class Index<T : Hashable, C: Component> {
fileprivate var entities: [T: Set<Entity>]
fileprivate weak var group: Group?
fileprivate let keyBuilder: (C) -> T
init(ctx: Context, paused: Bool = false, keyBuilder: @escaping (C) -> T) {
self.group = ctx.group(C.matcher)
self.entities = [:]
self.keyBuilder = keyBuilder
self.isPaused = paused
if isPaused == false {
refillIndex()
}
group?.observer(add: self)
}
public subscript(key: T) -> Set<Entity> {
return entities[key] ?? []
}
public var isPaused : Bool {
didSet {
if isPaused {
entities.removeAll()
} else {
refillIndex()
}
}
}
private func refillIndex() {
if let group = group {
for e in group {
if let c: C = e.get() {
insert(c, e)
}
}
}
}
fileprivate func insert(_ c: C, _ entity: Entity) {
let key = keyBuilder(c)
var set: Set<Entity> = entities[key] ?? []
set.insert(entity)
entities[key] = set
}
fileprivate func remove(_ prevC: C, _ entity: Entity) {
let prevKey = keyBuilder(prevC)
var prevSet: Set<Entity> = entities[prevKey] ?? []
prevSet.remove(entity)
entities[prevKey] = prevSet
}
}
extension Index: GroupObserver {
public func added(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) {
guard let c = newComponent as? C else {
return
}
guard isPaused == false else {
return
}
insert(c, entity)
}
public func updated(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) {
guard let c = newComponent as? C,
let prevC = oldComponent as? C else {
return
}
guard isPaused == false else {
return
}
remove(prevC, entity)
insert(c, entity)
}
public func removed(entity: Entity, oldComponent: Component?, newComponent: Component?, in group: Group) {
guard let prevC = oldComponent as? C else {
return
}
guard isPaused == false else {
return
}
remove(prevC, entity)
}
}
| mit | ad0bfcb669da92a69d87c249d17d6fa3 | 25.515152 | 110 | 0.524571 | 4.382304 | false | false | false | false |
loudnate/LoopKit | LoopKit/HealthKitSampleStore.swift | 1 | 13832 | //
// HealthKitSampleStore.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
import os.log
extension Notification.Name {
public static let StoreAuthorizationStatusDidChange = Notification.Name(rawValue: "com.loudnate.LoopKit.AuthorizationStatusDidChangeNotification")
}
public enum HealthKitSampleStoreResult<T> {
case success(T)
case failure(HealthKitSampleStore.StoreError)
}
public class HealthKitSampleStore {
/// Describes the source of an update notification. Value is of type `UpdateSource.RawValue`
public static let notificationUpdateSourceKey = "com.loopkit.UpdateSource"
public enum StoreError: Error {
case authorizationDenied
case healthKitError(HKError)
}
/// The sample type managed by this store
public let sampleType: HKSampleType
/// The health store used for underlying queries
public let healthStore: HKHealthStore
/// Whether the store is observing changes to types
public let observationEnabled: Bool
/// For unit testing only.
internal var testQueryStore: HKSampleQueryTestable?
/// Allows for controlling uses of the system date in unit testing
internal var test_currentDate: Date?
internal func currentDate(timeIntervalSinceNow: TimeInterval = 0) -> Date {
let date = test_currentDate ?? Date()
return date.addingTimeInterval(timeIntervalSinceNow)
}
private let log: OSLog
public init(
healthStore: HKHealthStore,
type: HKSampleType,
observationStart: Date,
observationEnabled: Bool,
test_currentDate: Date? = nil
) {
self.healthStore = healthStore
self.sampleType = type
self.observationStart = observationStart
self.observationEnabled = observationEnabled
self.test_currentDate = test_currentDate
self.log = OSLog(category: String(describing: Swift.type(of: self)))
if !authorizationRequired {
createQuery()
}
}
deinit {
if let query = observerQuery {
healthStore.stop(query)
}
observerQuery = nil
}
// MARK: - Authorization
/// Requests authorization from HealthKit to share and read the sample type.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - Parameters:
/// - toShare: Whether to request write authorization. Defaults to true.
/// - completion: A closure called after the authorization is completed
/// - result: The authorization result
public func authorize(toShare: Bool = true, _ completion: @escaping (_ result: HealthKitSampleStoreResult<Bool>) -> Void) {
healthStore.requestAuthorization(toShare: toShare ? [sampleType] : [], read: [sampleType]) { (completed, error) -> Void in
if completed && !self.sharingDenied {
self.createQuery()
completion(.success(true))
} else {
let authError: StoreError
if let error = error {
authError = .healthKitError(HKError(_nsError: error as NSError))
} else {
authError = .authorizationDenied
}
completion(.failure(authError))
}
NotificationCenter.default.post(name: .StoreAuthorizationStatusDidChange, object: self)
}
}
// MARK: - Query support
/// The active observer query
private var observerQuery: HKObserverQuery? {
didSet {
if let query = oldValue {
healthStore.stop(query)
}
if let query = observerQuery {
healthStore.execute(query)
}
}
}
/// The earliest sample date for which additions and deletions are observed
public internal(set) var observationStart: Date {
didSet {
// If we are now looking farther back, then reset the query
if oldValue > observationStart {
createQuery()
}
}
}
/// The last-retreived anchor from an anchored object query
private var queryAnchor: HKQueryAnchor?
/// Called in response to an update by the observer query
///
/// - Parameters:
/// - query: The query which triggered the update
/// - error: An error during the update, if one occurred
internal func observeUpdates(to query: HKObserverQuery, error: Error?) {
guard error == nil else {
log.error("%@ notified with changes with error: %{public}@", query, String(describing: error))
return
}
let anchoredObjectQuery = HKAnchoredObjectQuery(
type: self.sampleType,
predicate: query.predicate,
anchor: self.queryAnchor,
limit: HKObjectQueryNoLimit
) { (query, newSamples, deletedSamples, anchor, error) in
self.log.debug("%@: new: %d deleted: %d anchor: %@ error: %@", #function, newSamples?.count ?? 0, deletedSamples?.count ?? 0, String(describing: anchor), String(describing: error))
if let error = error {
self.log.error("%@: error executing anchoredObjectQuery: %@", String(describing: type(of: self)), error.localizedDescription)
}
self.processResults(from: query, added: newSamples ?? [], deleted: deletedSamples ?? [], error: error)
self.queryAnchor = anchor
}
healthStore.execute(anchoredObjectQuery)
}
/// Called in response to new results from an anchored object query
///
/// - Parameters:
/// - query: The executed query
/// - added: An array of samples added
/// - deleted: An array of samples deleted
/// - error: An error from the query, if one occurred
internal func processResults(from query: HKAnchoredObjectQuery, added: [HKSample], deleted: [HKDeletedObject], error: Error?) {
// To be overridden
}
/// The preferred unit for the sample type
///
/// The unit may be nil if the health store times out while fetching or the sample type is unsupported
public var preferredUnit: HKUnit? {
let identifier = HKQuantityTypeIdentifier(rawValue: sampleType.identifier)
return HealthStoreUnitCache.unitCache(for: healthStore).preferredUnit(for: identifier)
}
}
// MARK: - Unit Test Support
extension HealthKitSampleStore: HKSampleQueryTestable {
func executeSampleQuery(
for type: HKSampleType,
matching predicate: NSPredicate,
limit: Int = HKObjectQueryNoLimit,
sortDescriptors: [NSSortDescriptor]? = nil,
resultsHandler: @escaping (HKSampleQuery, [HKSample]?, Error?) -> Void
) {
if let tester = testQueryStore {
tester.executeSampleQuery(for: type, matching: predicate, limit: limit, sortDescriptors: sortDescriptors, resultsHandler: resultsHandler)
} else {
let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: limit, sortDescriptors: sortDescriptors, resultsHandler: resultsHandler)
healthStore.execute(query)
}
}
}
// MARK: - Observation
extension HealthKitSampleStore {
private func createQuery() {
log.debug("%@ [observationEnabled: %d]", #function, observationEnabled)
guard observationEnabled else {
return
}
let predicate = HKQuery.predicateForSamples(withStart: observationStart, end: nil)
observerQuery = HKObserverQuery(sampleType: sampleType, predicate: predicate) { [weak self] (query, completionHandler, error) in
self?.observeUpdates(to: query, error: error)
completionHandler()
}
enableBackgroundDelivery { (result) in
switch result {
case .failure(let error):
self.log.error("Error enabling background delivery: %@", error.localizedDescription)
case .success:
self.log.debug("Enabled background delivery for %@", self.sampleType)
}
}
}
/// Enables the immediate background delivery of updates to samples from HealthKit.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - Parameter completion: A closure called after the request is completed
/// - Parameter result: A boolean indicating the new background delivery state
private func enableBackgroundDelivery(_ completion: @escaping (_ result: HealthKitSampleStoreResult<Bool>) -> Void) {
#if os(iOS)
healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (enabled, error) in
if let error = error {
completion(.failure(.healthKitError(HKError(_nsError: error as NSError))))
} else if enabled {
completion(.success(true))
} else {
assertionFailure()
}
}
#endif
}
/// Disables the immediate background delivery of updates to samples from HealthKit.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - Parameter completion: A closure called after the request is completed
/// - Parameter result: A boolean indicating the new background delivery state
private func disableBackgroundDelivery(_ completion: @escaping (_ result: HealthKitSampleStoreResult<Bool>) -> Void) {
#if os(iOS)
healthStore.disableBackgroundDelivery(for: sampleType) { (disabled, error) in
if let error = error {
completion(.failure(.healthKitError(HKError(_nsError: error as NSError))))
} else if disabled {
completion(.success(false))
} else {
assertionFailure()
}
}
#endif
}
}
// MARK: - HKHealthStore helpers
extension HealthKitSampleStore {
/// True if the user has explicitly denied access to any required share types
public var sharingDenied: Bool {
return healthStore.authorizationStatus(for: sampleType) == .sharingDenied
}
/// True if the store requires authorization
public var authorizationRequired: Bool {
return healthStore.authorizationStatus(for: sampleType) == .notDetermined
}
/**
Queries the preferred unit for the authorized share types. If more than one unit is retrieved,
then the completion contains just one of them.
- parameter completion: A closure called after the query is completed. This closure takes two arguments:
- unit: The retrieved unit
- error: An error object explaining why the retrieval was unsuccessful
*/
@available(*, deprecated, message: "Use HealthKitSampleStore.getter:preferredUnit instead")
public func preferredUnit(_ completion: @escaping (_ unit: HKUnit?, _ error: Error?) -> Void) {
preferredUnit { result in
switch result {
case .success(let unit):
completion(unit, nil)
case .failure(let error):
completion(nil, error)
}
}
}
/// Queries the preferred unit for the sample type.
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - Parameter completion: A closure called after the query is completed
/// - Parameter result: The query result
@available(*, deprecated, message: "Use HealthKitSampleStore.getter:preferredUnit instead")
private func preferredUnit(_ completion: @escaping (_ result: HealthKitSampleStoreResult<HKUnit>) -> Void) {
let quantityTypes = [self.sampleType].compactMap { (sampleType) -> HKQuantityType? in
return sampleType as? HKQuantityType
}
self.healthStore.preferredUnits(for: Set(quantityTypes)) { (quantityToUnit, error) -> Void in
if let error = error {
completion(.failure(.healthKitError(HKError(_nsError: error as NSError))))
} else if let unit = quantityToUnit.values.first {
completion(.success(unit))
} else {
assertionFailure()
}
}
}
}
extension HealthKitSampleStore: CustomDebugStringConvertible {
public var debugDescription: String {
return """
* observerQuery: \(String(describing: observerQuery))
* observationStart: \(observationStart)
* observationEnabled: \(observationEnabled)
* authorizationRequired: \(authorizationRequired)
"""
}
}
extension HealthKitSampleStore.StoreError: LocalizedError {
public var errorDescription: String? {
switch self {
case .authorizationDenied:
return LocalizedString("Authorization Denied", comment: "The error description describing when Health sharing was denied")
case .healthKitError(let error):
return error.localizedDescription
}
}
public var recoverySuggestion: String? {
switch self {
case .authorizationDenied:
return LocalizedString("Please re-enable sharing in Health", comment: "The error recovery suggestion when Health sharing was denied")
case .healthKitError(let error):
return error.errorUserInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
}
}
}
| mit | eb5cd55805ea58ecdc9291a1e572dd16 | 36.482385 | 192 | 0.637915 | 5.385903 | false | false | false | false |
mkoehnke/WKZombie | Sources/WKZombie/HTMLFetchable.swift | 1 | 3655 | //
// HTMLFetchable.swift
//
// Copyright (c) 2016 Mathias Koehnke (http://www.mathiaskoehnke.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ObjectiveC
//==========================================
// MARK: Fetchable Protocol
//==========================================
public protocol HTMLFetchable {
var fetchURL : URL? { get }
func fetchedContent<T: HTMLFetchableContent>() -> T?
}
private var WKZFetchedDataKey: UInt8 = 0
//==========================================
// MARK: Fetchable Default Implementation
//==========================================
extension HTMLFetchable {
internal var fetchedData: Data? {
get {
return objc_getAssociatedObject(self, &WKZFetchedDataKey) as? Data
}
set(newValue) {
objc_setAssociatedObject(self, &WKZFetchedDataKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
public func fetchedContent<T : HTMLFetchableContent>() -> T? {
if let fetchedData = fetchedData {
switch T.instanceFromData(fetchedData) {
case .success(let value): return value as? T
case .error: return nil
}
}
return nil
}
}
//==========================================
// MARK: FetchableContentType Protocol
//==========================================
public protocol HTMLFetchableContent {
associatedtype ContentType
static func instanceFromData(_ data: Data) -> Result<ContentType>
}
//==========================================
// MARK: Supported Fetchable Content Types
//==========================================
#if os(iOS)
import UIKit
extension UIImage : HTMLFetchableContent {
public typealias ContentType = UIImage
public static func instanceFromData(_ data: Data) -> Result<ContentType> {
if let image = UIImage(data: data) {
return Result.success(image)
}
return Result.error(.transformFailure)
}
}
#elseif os(OSX)
import Cocoa
extension NSImage : HTMLFetchableContent {
public typealias ContentType = NSImage
public static func instanceFromData(_ data: Data) -> Result<ContentType> {
if let image = NSImage(data: data) {
return Result.success(image)
}
return Result.error(.transformFailure)
}
}
#endif
extension Data : HTMLFetchableContent {
public typealias ContentType = Data
public static func instanceFromData(_ data: Data) -> Result<ContentType> {
return Result.success(data)
}
}
| mit | b0546294a28877b27c01695245b0017f | 33.481132 | 120 | 0.617784 | 5.111888 | false | false | false | false |
CodaFi/swiftz | Tests/SwiftzTests/NonEmptyListSpec.swift | 2 | 6345 | //
// NonEmptyListSpec.swift
// Swiftz
//
// Created by Robert Widmann on 7/12/15.
// Copyright © 2015-2016 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
extension NonEmptyList : Arbitrary where Element : Arbitrary {
public static var arbitrary : Gen<NonEmptyList<Element>> {
return [Element].arbitrary.suchThat({ !$0.isEmpty }).map { NonEmptyList<Element>(List(fromArray: $0))! }
}
public static func shrink(_ xs : NonEmptyList<Element>) -> [NonEmptyList<Element>] {
return List<Element>.shrink(xs.toList()).filter({ !$0.isEmpty }).compactMap { xs in
return NonEmptyList(xs)!
}
}
}
class NonEmptyListSpec : XCTestCase {
func testProperties() {
property("Non-empty Lists of Equatable elements obey reflexivity") <- forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { l in
return l == l
}
property("Non-empty Lists of Equatable elements obey symmetry") <- forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { x in
return forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { y in
return (x == y) == (y == x)
}
}
property("Non-empty Lists of Equatable elements obey transitivity") <- forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { x in
return forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { y in
let inner = forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { z in
return ((x == y) && (y == z)) ==> (x == z)
}
return inner
}
}
property("Non-empty Lists of Equatable elements obey negation") <- forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { x in
return forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { y in
return (x != y) == !(x == y)
}
}
property("Non-empty Lists of Comparable elements obey reflexivity") <- forAllShrink(NonEmptyList<Int>.arbitrary, shrinker: NonEmptyList<Int>.shrink) { l in
return l == l
}
property("NonEmptyList obeys the Functor identity law") <- forAll { (x : NonEmptyList<Int>) in
return (x.fmap(identity)) == identity(x)
}
property("NonEmptyList obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in
return forAll { (x : NonEmptyList<Int>) in
return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow))
}
}
property("NonEmptyList obeys the Applicative identity law") <- forAll { (x : NonEmptyList<Int>) in
return (NonEmptyList.pure(identity) <*> x) == x
}
// Swift unroller can't handle our scale; Use only small lists.
property("NonEmptyList obeys the first Applicative composition law") <- forAll { (fl : NonEmptyList<ArrowOf<Int8, Int8>>, gl : NonEmptyList<ArrowOf<Int8, Int8>>, x : NonEmptyList<Int8>) in
return (fl.count <= 3 && gl.count <= 3) ==> {
let f = fl.fmap({ $0.getArrow })
let g = gl.fmap({ $0.getArrow })
return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x))
}
}
property("NonEmptyList obeys the second Applicative composition law") <- forAll { (fl : NonEmptyList<ArrowOf<Int8, Int8>>, gl : NonEmptyList<ArrowOf<Int8, Int8>>, x : NonEmptyList<Int8>) in
return (fl.count <= 3 && gl.count <= 3) ==> {
let f = fl.fmap({ $0.getArrow })
let g = gl.fmap({ $0.getArrow })
return (NonEmptyList.pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x))
}
}
property("NonEmptyList obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Int>) in
let f : (Int) -> NonEmptyList<Int> = NonEmptyList<Int>.pure • fa.getArrow
return (NonEmptyList<Int>.pure(a) >>- f) == f(a)
}
property("NonEmptyList obeys the Monad right identity law") <- forAll { (m : NonEmptyList<Int>) in
return (m >>- NonEmptyList<Int>.pure) == m
}
property("NonEmptyList obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, Int>, ga : ArrowOf<Int, Int>) in
let f : (Int) -> NonEmptyList<Int> = NonEmptyList<Int>.pure • fa.getArrow
let g : (Int) -> NonEmptyList<Int> = NonEmptyList<Int>.pure • ga.getArrow
return forAll { (m : NonEmptyList<Int>) in
return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g })
}
}
property("NonEmptyList obeys the Comonad identity law") <- forAll { (x : NonEmptyList<Int>) in
return x.extend({ $0.extract() }) == x
}
property("NonEmptyList obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>) in
return forAll { (x : Identity<Int>) in
let f : (Identity<Int>) -> Int = ff.getArrow • { $0.runIdentity }
return x.extend(f).extract() == f(x)
}
}
property("NonEmptyList obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>, gg : ArrowOf<Int, Int>) in
return forAll { (x : NonEmptyList<Int>) in
let f : (NonEmptyList<Int>) -> Int = ff.getArrow • { $0.head }
let g : (NonEmptyList<Int>) -> Int = gg.getArrow • { $0.head }
return x.extend(f).extend(g) == x.extend({ g($0.extend(f)) })
}
}
property("head behaves") <- forAll { (x : Int) in
return forAll { (xs : List<Int>) in
return NonEmptyList(x, xs).head == x
}
}
property("tail behaves") <- forAll { (x : Int) in
return forAll { (xs : List<Int>) in
return NonEmptyList(x, xs).tail == xs
}
}
property("non-empty lists and lists that aren't empty are the same thing") <- forAll { (x : Int) in
return forAll { (xs : List<Int>) in
return NonEmptyList(x, xs).toList() == List(x, xs)
}
}
property("optional constructor behaves") <- forAll { (xs : List<Int>) in
switch xs.match {
case .Nil:
return NonEmptyList(xs) == nil
case .Cons(let y, let ys):
return NonEmptyList(xs)! == NonEmptyList(y, ys)
}
}
property("NonEmptyList is a Semigroup") <- forAll { (l : NonEmptyList<Int>, r : NonEmptyList<Int>) in
return (l <> r).toList() == l.toList() <> r.toList()
}
property("NonEmptyLists under double reversal is an identity") <- forAll { (l : NonEmptyList<Int>) in
return l.reverse().reverse() == l
}
}
#if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
static var allTests = testCase([
("testProperties", testProperties)
])
#endif
}
| bsd-3-clause | b6c951a933543d5f0cfb8bce3231d39b | 36.431953 | 191 | 0.644167 | 3.436176 | false | false | false | false |
jeksys/SwiftHelpers | Sources/IBDesignableHelpers.swift | 1 | 2759 | import UIKit
import Foundation
@IBDesignable extension UIButton{
@IBInspectable var borderColor: UIColor?{
get {
guard let color = layer.borderColor else{
return nil
}
return UIColor(cgColor: color)
}
set{
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var borderWidth: CGFloat{
get {
return layer.borderWidth
}
set{
layer.borderWidth = newValue
}
}
@IBInspectable var cornerRadius: CGFloat{
get {
return layer.cornerRadius
}
set{
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
}
}
@IBDesignable extension UILabel{
@IBInspectable var borderColor: UIColor?{
get {
guard let color = layer.borderColor else{
return nil
}
return UIColor(cgColor: color)
}
set{
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var borderWidth: CGFloat{
get {
return layer.borderWidth
}
set{
layer.borderWidth = newValue
}
}
@IBInspectable var cornerRadius: CGFloat{
get {
return layer.cornerRadius
}
set{
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
}
}
@IBDesignable extension UIButton {
@IBInspectable var kern: CGFloat{
get {
return 0
}
set{
self.kern(kerningValue: newValue)
}
}
func kern(kerningValue:CGFloat) {
if let text = self.titleLabel!.text{
let attributedString = NSMutableAttributedString(attributedString: self.titleLabel!.attributedText ?? NSMutableAttributedString(string: text))
attributedString.addAttribute(NSAttributedString.Key.kern, value: kern, range: NSMakeRange(0, attributedString.length))
self.setAttributedTitle(attributedString, for: .normal)
}
}
}
@IBDesignable extension UILabel {
@IBInspectable var kern: CGFloat{
get {
return 0
}
set{
self.kern(kerningValue: newValue)
}
}
func kern(kerningValue:CGFloat) {
if let text = self.text{
let attributedString = NSMutableAttributedString(attributedString: self.attributedText ?? NSMutableAttributedString(string: text))
attributedString.addAttribute(NSAttributedString.Key.kern, value: kern, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | 59a3809988ee4fa3629c39cb3e4d717d | 24.546296 | 155 | 0.566872 | 5.463366 | false | false | false | false |
RaviDesai/RSDRestServices | Pod/Classes/APICall.swift | 2 | 1905 | //
// APICall.swift
//
// Created by Ravi Desai on 6/10/15.
// Copyright (c) 2015 RSD. All rights reserved.
//
import Foundation
public class APICall<U: APIResponseParserProtocol> {
public private(set) var session: APISession
private var request: APIRequest<U>
public init(session: APISession, request: APIRequest<U>) {
self.session = session
self.request = request
}
private func performTask(callback: (NetworkResponse) -> ()) {
let message = "Could not construct a valid HTTP request."
let userInfo = [NSLocalizedDescriptionKey:message, NSLocalizedFailureReasonErrorKey: message];
let error = NSError(domain: "com.github.RaviDesai", code: 48118001, userInfo: userInfo)
if let request = self.request.makeRequest() {
let task = self.session.session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let result = NetworkResponse.create(data, response: response, error: error)
callback(result);
})
task.resume()
} else {
callback(NetworkResponse.SystemFailure(error))
}
}
public func execute(callback: (NSError?) -> ()) {
self.performTask { (networkResponse) -> () in
callback(networkResponse.getError())
}
}
public func executeRespondWithObject(callback: (U.T?, NSError?) ->()) {
self.performTask { (response) -> () in
let (result, error) = self.request.responseParser.Parse(response)
callback(result, error)
}
}
public func executeRespondWithArray(callback: ([U.T]?, NSError?) ->()) {
self.performTask { (response) -> () in
let (result, error) = self.request.responseParser.ParseToArray(response)
callback(result, error)
}
}
} | mit | 49055ca728d8dd61652967276172a3e7 | 33.654545 | 128 | 0.610499 | 4.579327 | false | false | false | false |
tobbi/projectgenerator | target_includes/ios_bridges/ApplicationView.swift | 1 | 2704 | //
// Activity.swift
// MobileApplicationsSwiftAufgabe1
//
// Created by Tobias Markus on 21.04.15.
// Copyright (c) 2015 Tobias Markus. All rights reserved.
//
import Foundation
import UIKit
public class ApplicationView: UIViewController {
/**
* Array containing all subviews of this activity
*/
var containedViews = [UIView]();
/**
* UIResponder parent context (aka Main function)
*/
var parentContext: UIResponder;
var width: CGFloat = 0, height: CGFloat = 0;
/**
* Initialize application view
* @param context The UIResponder parent (aka "Main function")
*/
public init(context: UIResponder, width: CGFloat, height: CGFloat) {
self.parentContext = context;
self.width = width;
self.height = height;
super.init(nibName: nil, bundle: nil);
}
public func getParentContext() -> UIResponder
{
return parentContext;
}
public func getWidth() -> CGFloat
{
return width;
}
public func getHeight() -> CGFloat
{
return height;
}
/**
* Function call required by iOS
*/
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
* Adds a new text field to this application view
* @param textfield The text field to add to this application view
*/
public func addTextfield(textfield: Textfield)
{
containedViews.append(textfield.getWrappedElement());
}
/**
* Adds a new button to this application view
* @param button The button to add to this application view
*/
public func addButton(button: Button)
{
containedViews.append(button.getWrappedElement());
}
/**
* Creates a new text field element
* @return The created text field element
*/
public func createTextfield() -> Textfield
{
return Textfield(context: self, eventContext: self.parentContext);
}
/**
* Creates a new button element
* @return The created button element
*/
public func createButton() -> Button
{
return Button(context:self, eventContext: self.parentContext);
}
/**
* Puts all added elements on this application view
*/
private func initializeUIElements() {
for containedView in containedViews {
view.addSubview(containedView);
}
}
/**
* Function that is executed when the view has been loaded
*/
override public func viewDidLoad() {
super.viewDidLoad();
initializeUIElements();
}
} | gpl-2.0 | e6b92004b2c0cbe1de05cd3bff8fc315 | 22.938053 | 74 | 0.605769 | 4.854578 | false | false | false | false |
carsonmcdonald/TinyPNGForMac | TinyPNG/FileTableViewController.swift | 1 | 3868 | import Cocoa
class FileTableViewController: NSViewController, NSTableViewDataSource {
@IBOutlet weak var filenameTable: NSTableView!
private var tinyPNGWorkflow = TinyPNGWorkflow()
private var filesAddedNotification: NSObjectProtocol?
deinit {
if self.filesAddedNotification != nil {
NSNotificationCenter.defaultCenter().removeObserver(self.filesAddedNotification!)
}
}
override func viewDidLoad() {
self.tinyPNGWorkflow.statusUpdate = { (imageProcessingInfo:ImageProcessingInfo) -> Void in
for row in 0...self.tinyPNGWorkflow.getImageCount()-1 {
if let cell = self.filenameTable.viewAtColumn(0, row: row, makeIfNecessary: false) as? ImageProcessingTableViewCell {
if cell.imageProcessingInfo.identifier == imageProcessingInfo.identifier {
self.filenameTable.reloadDataForRowIndexes(NSIndexSet(index: row), columnIndexes: NSIndexSet(index: 0))
if self.filenameTable.selectedRow == row {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.FileDetailSelected, object: self, userInfo: ["imageProcessingInfo":imageProcessingInfo])
}
break
}
}
}
}
self.filesAddedNotification = NSNotificationCenter.defaultCenter().addObserverForName(Config.Notification.FileDrop, object: nil, queue: NSOperationQueue.mainQueue()) { (notification:NSNotification) -> Void in
if notification.userInfo != nil {
if let fileList = notification.userInfo!["fileList"] as? [String] {
for file in fileList {
if FileUtils.isDirectory(file) {
var nestedFiles = [String]()
FileUtils.getNestedPNGFiles(file, files: &nestedFiles)
for subFile in nestedFiles {
self.tinyPNGWorkflow.queueImageForProcessing(subFile)
}
} else {
self.tinyPNGWorkflow.queueImageForProcessing(file)
}
}
self.filenameTable.reloadData()
}
}
}
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 30
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.tinyPNGWorkflow.getImageCount()
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeViewWithIdentifier("ImageProcessingTableViewCell", owner: self) as? ImageProcessingTableViewCell {
cell.imageProcessingInfo = self.tinyPNGWorkflow.getImageProcessingInfoAtIndex(row)
return cell
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
if self.filenameTable.selectedRow >= 0 && self.tinyPNGWorkflow.getImageCount() > self.filenameTable.selectedRow {
let imageProcessingInfo = self.tinyPNGWorkflow.getImageProcessingInfoAtIndex(self.filenameTable.selectedRow)
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.FileDetailSelected, object: self, userInfo: ["imageProcessingInfo":imageProcessingInfo])
} else {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.FileDetailSelected, object: self, userInfo: nil)
}
}
}
| mit | f1c0dee0fdfabee417d65a8a3d8792b6 | 42.460674 | 216 | 0.603154 | 6.468227 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI-tvOS/StudiesViewController.swift | 1 | 7036 | //
// FirstViewController.swift
// VBVMI-tvOS
//
// Created by Thomas Carey on 17/10/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import UIKit
import CoreData
import SnapKit
import AlamofireImage
class StudiesDataSource : NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
private let fetchedResultsController: NSFetchedResultsController<Study>
private let realSection : Int
private weak var viewController: UIViewController?
init(fetchedResultsController: NSFetchedResultsController<Study>, section: Int, viewController: UIViewController) {
self.fetchedResultsController = fetchedResultsController
self.realSection = section
self.viewController = viewController
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let sectionInfo = fetchedResultsController.sections?[realSection] else { return 0 }
return sectionInfo.numberOfObjects
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let realIndexPath = IndexPath(item: indexPath.item, section: realSection)
let study = fetchedResultsController.object(at: realIndexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StudyCell", for: indexPath) as! StudyCollectionViewCell
cell.mainTitle.text = study.title
if let thumbnailSource = study.thumbnailSource {
if let url = URL(string: thumbnailSource) {
let width = 300
let imageFilter = ScaledToSizeWithRoundedCornersFilter(size: CGSize(width: width, height: width), radius: 10, divideRadiusByImageScale: false)
cell.mainImage.af_setImage(withURL: url, placeholderImage: nil, filter: imageFilter, imageTransition: UIImageView.ImageTransition.crossDissolve(0.3), runImageTransitionIfCached: false, completion: { _ in
cell.backgroundImage.isHidden = true
})
// cell.coverImageView.af_setImage(withURL: url)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let realIndexPath = IndexPath(item: indexPath.item, section: realSection)
let study = fetchedResultsController.object(at: realIndexPath)
viewController?.performSegue(withIdentifier: "showStudy", sender: study)
}
var title: String? {
get {
return fetchedResultsController.sections?[realSection].name
}
}
var numberOfStudies: Int? {
get {
return fetchedResultsController.sections?[realSection].numberOfObjects
}
}
}
class StudiesViewController: UIViewController {
var fetchedResultsController: NSFetchedResultsController<Study>!
@IBOutlet weak var tableView: UITableView!
fileprivate func configureFetchRequest(_ fetchRequest: NSFetchRequest<Study>) {
let identifierSort = NSSortDescriptor(key: StudyAttributes.studyIndex.rawValue, ascending: true)
let bibleStudySort = NSSortDescriptor(key: StudyAttributes.bibleIndex.rawValue, ascending: true)
var sortDescriptors : [NSSortDescriptor] = [NSSortDescriptor(key: StudyAttributes.studyType.rawValue, ascending: true)]
sortDescriptors.append(contentsOf: [bibleStudySort, identifierSort])
fetchRequest.sortDescriptors = sortDescriptors
}
fileprivate func setupFetchedResultsController() {
let fetchRequest = NSFetchRequest<Study>(entityName: Study.entityName())
let context: NSManagedObjectContext = ContextCoordinator.sharedInstance.managedObjectContext!
fetchRequest.entity = Study.entity(managedObjectContext: context)
configureFetchRequest(fetchRequest)
fetchRequest.shouldRefreshRefetchedObjects = true
fetchedResultsController = NSFetchedResultsController<Study>(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: StudyAttributes.studyType.rawValue, cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
DispatchQueue.main.async { () -> Void in
self.reloadData()
}
} catch let error {
logger.error("Error fetching: \(error)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupFetchedResultsController()
tableView.register(UINib(nibName: "StudiesTableViewCell", bundle: nil), forCellReuseIdentifier: "StudiesCell")
tableView.contentInset = UIEdgeInsets(top: 30, left: 0, bottom: 60, right: 0)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let study = sender as? Study , segue.identifier == "showStudy" {
if let studyViewController = segue.destination as? StudyViewController {
studyViewController.study = study
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadData() {
tableView.reloadData()
}
}
extension StudiesViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 430
}
}
extension StudiesViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section == 0 else { return 0 }
return fetchedResultsController.sections?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSource = StudiesDataSource(fetchedResultsController: fetchedResultsController, section: indexPath.row, viewController: self)
let cell = tableView.dequeueReusableCell(withIdentifier: "StudiesCell", for: indexPath) as! StudiesTableViewCell
cell.collectionViewDatasource = dataSource
cell.collectionViewDelegate = dataSource
cell.header = dataSource.title
if let count = dataSource.numberOfStudies {
cell.studyCount = "\(count) Studies"
} else {
cell.studyCount = nil
}
return cell
}
}
extension StudiesViewController: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
reloadData()
}
}
| mit | e07f418758487e273d3bce959efc4eb7 | 37.442623 | 219 | 0.681023 | 5.89196 | false | false | false | false |
gottesmm/swift | test/Parse/errors.swift | 3 | 5069 | // RUN: %target-typecheck-verify-swift
enum MSV : Error {
case Foo, Bar, Baz
case CarriesInt(Int)
var domain: String { return "" }
var code: Int { return 0 }
}
func opaque_error() -> Error { return MSV.Foo }
func one() {
do {
true ? () : throw opaque_error() // expected-error {{expected expression after '? ... :' in ternary expression}}
} catch _ {
}
do {
} catch { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
let error2 = error
}
do {
} catch where true { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
let error2 = error
} catch {
}
// <rdar://problem/20985280> QoI: improve diagnostic on improper pattern match on type
do {
throw opaque_error()
} catch MSV { // expected-error {{'is' keyword required to pattern match against type name}} {{11-11=is }}
} catch {
}
do {
throw opaque_error()
} catch is Error { // expected-warning {{'is' test is always true}}
}
func foo() throws {}
do {
#if false
try foo()
#endif
} catch { // don't warn, #if code should be scanned.
}
do {
#if false
throw opaque_error()
#endif
} catch { // don't warn, #if code should be scanned.
}
}
func takesAutoclosure(_ fn : @autoclosure () -> Int) {}
func takesThrowingAutoclosure(_ fn : @autoclosure () throws -> Int) {}
func genError() throws -> Int { throw MSV.Foo }
func genNoError() -> Int { return 0 }
func testAutoclosures() throws {
takesAutoclosure(genError()) // expected-error {{call can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}}
takesAutoclosure(genNoError())
try takesAutoclosure(genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}}
try takesAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesAutoclosure(try genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}}
takesAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesThrowingAutoclosure(try genError())
takesThrowingAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
try takesThrowingAutoclosure(genError())
try takesThrowingAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesThrowingAutoclosure(genError()) // expected-error {{call can throw but is not marked with 'try'}}
takesThrowingAutoclosure(genNoError())
}
struct IllegalContext {
var x: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}}
func foo(_ x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}}
func catcher() throws {
do {
_ = try genError()
} catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}}
} catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}}
}
}
}
func illformed() throws {
do {
_ = try genError()
// TODO: this recovery is terrible
} catch MSV.CarriesInt(let i) where i == genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} expected-error {{expected '{'}} expected-error {{braced block of statements is an unused closure}} expected-error {{expression resolves to an unused function}}
}
}
func postThrows() -> Int throws { // expected-error{{'throws' may only occur before '->'}}{{19-19=throws }}{{25-32=}}
return 5
}
func postThrows2() -> throws Int { // expected-error{{'throws' may only occur before '->'}}{{20-22=throws}}{{23-29=->}}
return try postThrows()
}
func postRethrows(_ f: () throws -> Int) -> Int rethrows { // expected-error{{'rethrows' may only occur before '->'}}{{42-42=rethrows }}{{48-57=}}
return try f()
}
func postRethrows2(_ f: () throws -> Int) -> rethrows Int { // expected-error{{'rethrows' may only occur before '->'}}{{43-45=rethrows}}{{46-54=->}}
return try f()
}
func incompleteThrowType() {
// FIXME: Bad recovery for incomplete function type.
let _: () throws
// expected-error @-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error @-2 {{expected expression}}
}
// rdar://21328447
func fixitThrow0() throw {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}}
func fixitThrow1() throw -> Int {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}}
func fixitThrow2() throws {
var _: (Int)
throw MSV.Foo
var _: (Int) throw -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{16-21=throws}}
}
| apache-2.0 | 9649949e6eb7e744af4169757e1b2dc9 | 35.467626 | 316 | 0.672914 | 4.097817 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI/CenteredProgressView.swift | 1 | 1183 | //
// CenteredProgressView.swift
// VBVMI
//
// Created by Thomas Carey on 1/10/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import UIKit
class CenteredProgressView: UIView {
var progress: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
drawCenteredProgress(progress: progress, progressFrame: self.bounds)
}
func drawCenteredProgress(progress: CGFloat = 1, progressFrame: CGRect = CGRect(x: 0, y: 0, width: 80, height: 4)) {
if progress == 1 {
return
}
//// Variable Declarations
let progressWidth: CGFloat = (1 - progress) * (progressFrame.size.width - progressFrame.size.height) + progressFrame.size.height
let progressOffset: CGFloat = (progressFrame.size.width - progressWidth)// / 2.0
//// Rectangle Drawing
let rectanglePath = UIBezierPath(roundedRect: CGRect(x: progressOffset, y: 0, width: progressWidth, height: progressFrame.size.height), cornerRadius: progressFrame.size.height / 2.0)
StyleKit.orange.setFill()
rectanglePath.fill()
}
}
| mit | c1f638dfbbbd0067ceeaa5e61462cfa2 | 28.55 | 190 | 0.628596 | 4.361624 | false | false | false | false |
gottesmm/swift | test/Constraints/tuple.swift | 10 | 5591 | // RUN: %target-typecheck-verify-swift
// Test various tuple constraints.
func f0(x: Int, y: Float) {}
var i : Int
var j : Int
var f : Float
func f1(y: Float, rest: Int...) {}
func f2(_: (_ x: Int, _ y: Int) -> Int) {}
func f2xy(x: Int, y: Int) -> Int {}
func f2ab(a: Int, b: Int) -> Int {}
func f2yx(y: Int, x: Int) -> Int {}
func f3(_ x: (_ x: Int, _ y: Int) -> ()) {}
func f3a(_ x: Int, y: Int) {}
func f3b(_: Int) {}
func f4(_ rest: Int...) {}
func f5(_ x: (Int, Int)) {}
func f6(_: (i: Int, j: Int), k: Int = 15) {}
//===----------------------------------------------------------------------===//
// Conversions and shuffles
//===----------------------------------------------------------------------===//
// Variadic functions.
f4()
f4(1)
f4(1, 2, 3)
f2(f2xy)
f2(f2ab)
f2(f2yx)
f3(f3a)
f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}}
func getIntFloat() -> (int: Int, float: Float) {}
var values = getIntFloat()
func wantFloat(_: Float) {}
wantFloat(values.float)
var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}}
typealias Interval = (a:Int, b:Int)
func takeInterval(_ x: Interval) {}
takeInterval(Interval(1, 2))
f5((1,1))
// Tuples with existentials
var any : Any = ()
any = (1, 2)
any = (label: 4)
// Scalars don't have .0/.1/etc
i = j.0 // expected-error{{value of type 'Int' has no member '0'}}
any.1 // expected-error{{value of type 'Any' has no member '1'}}
// expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
any = (5.0, 6.0) as (Float, Float)
_ = (any as! (Float, Float)).1
// Fun with tuples
protocol PosixErrorReturn {
static func errorReturnValue() -> Self
}
extension Int : PosixErrorReturn {
static func errorReturnValue() -> Int { return -1 }
}
func posixCantFail<A, T : Comparable & PosixErrorReturn>
(_ f: @escaping (A) -> T) -> (_ args:A) -> T
{
return { args in
let result = f(args)
assert(result != T.errorReturnValue())
return result
}
}
func open(_ name: String, oflag: Int) -> Int { }
var foo: Int = 0
var fd = posixCantFail(open)(("foo", 0))
// Tuples and lvalues
class C {
init() {}
func f(_: C) {}
}
func testLValue(_ c: C) {
var c = c
c.f(c)
let x = c
c = x
}
// <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType
func invalidPatternCrash(_ k : Int) {
switch k {
case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}}
break
}
}
// <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang
class Paws {
init() throws {}
}
func scruff() -> (AnyObject?, Error?) {
do {
return try (Paws(), nil)
} catch {
return (nil, error)
}
}
// Test variadics with trailing closures.
func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) {
}
variadicWithTrailingClosure(1, 2, 3) { $0 + $1 }
variadicWithTrailingClosure(1) { $0 + $1 }
variadicWithTrailingClosure() { $0 + $1 }
variadicWithTrailingClosure { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, y: 0) { $0 + $1 }
variadicWithTrailingClosure(y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +)
variadicWithTrailingClosure(1, y: 0, fn: +)
variadicWithTrailingClosure(y: 0, fn: +)
variadicWithTrailingClosure(1, 2, 3, fn: +)
variadicWithTrailingClosure(1, fn: +)
variadicWithTrailingClosure(fn: +)
// <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment
func gcd_23700031<T>(_ a: T, b: T) {
var a = a
var b = b
(a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}}
// expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int)}}
}
// <rdar://problem/24210190>
// Don't ignore tuple labels in same-type constraints or stronger.
protocol Kingdom {
associatedtype King
}
struct Victory<General> {
init<K: Kingdom>(_ king: K) where K.King == General {}
}
struct MagicKingdom<K> : Kingdom {
typealias King = K
}
func magify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() }
func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> {
return Victory(magify(pair)) // expected-error {{cannot convert return expression of type 'Victory<(Int, Int)>' to return type 'Victory<(x: Int, y: Int)>'}}
}
// https://bugs.swift.org/browse/SR-596
// Compiler crashes when accessing a non-existent property of a closure parameter
func call(_ f: (C) -> Void) {}
func makeRequest() {
call { obj in
print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}}
}
}
// <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure
struct r25271859<T> {
}
extension r25271859 {
func map<U>(f: (T) -> U) -> r25271859<U> {
}
func andThen<U>(f: (T) -> r25271859<U>) {
}
}
func f(a : r25271859<(Float, Int)>) {
a.map { $0.0 }
.andThen { _ in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{18-18=-> r25271859<String> }}
print("hello") // comment this out and it runs, leave any form of print in and it doesn't
return r25271859<String>()
}
}
| apache-2.0 | b120c36ec1c5dceb36ac159968a57908 | 26.406863 | 254 | 0.619746 | 3.123464 | false | false | false | false |
gardner-lab/syllable-detector-swift | Common/Common.swift | 2 | 689 | // Common.swift
// VideoCapture
//
// Created by L. Nathan Perkins on 7/2/15.
// Copyright © 2015
import Foundation
/// A logging function that only executes in debugging mode.
func DLog(_ message: String, function: String = #function ) {
#if DEBUG
print("\(function): \(message)")
#endif
}
extension String {
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func splitAtCharacter(_ char: Character) -> [String] {
return self.split { $0 == char } .map(String.init)
}
}
extension Int {
func isPowerOfTwo() -> Bool {
return (self != 0) && (self & (self - 1)) == 0
}
}
| mit | f22f6ea50fcb5673d80f41e615f9315b | 21.933333 | 79 | 0.611919 | 3.78022 | false | false | false | false |
WeHUD/app | weHub-ios/Gzone_App/Gzone_App/ProfilUserViewController.swift | 1 | 7074 | //
// ProfilUserViewController.swift
// Gzone_App
//
// Created by Lyes Atek on 05/07/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import UIKit
class ProfilUserViewController : UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var reply: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var avatar: UIImageView!
var user : User?
var posts : [Post] = []
var cellIdentifier = "cell"
var followers : [User] = []
override func viewDidLoad() {
super.viewDidLoad()
self.getUsers()
self.getPostByUserId()
self.tableView.dataSource = self
self.tableView.delegate = self
self.username.text = self.user?.username
self.reply.text = self.user?.username
self.avatar.image = self.imageFromUrl(url: (self.user?.avatar!)!)
// self.follow.text = AuthenticationService.sharedInstance.followers.count.description
cellIdentifier = "MyFeedsCustomCell"
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 500.0
tableView.estimatedRowHeight = 800.0
tableView.allowsSelection = false
tableView.scrollsToTop = false
tableView.register(UINib(nibName: "MyFeedsTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier)
}
func showYoutubeModal(_ sender : UITapGestureRecognizer){
print("Tap image : ", sender.view?.tag ?? "no media content")
let mediaTag = sender.view?.tag
let postVideo = posts[mediaTag!].video
if (postVideo != "") {
// Instantiate a modal view when content media is tapped
let modalViewController = ModalViewController()
modalViewController.videoURL = postVideo
modalViewController.modalPresentationStyle = .popover
present(modalViewController, animated: true, completion: nil)
}
}
func imageFromUrl(url : String)->UIImage{
let imageUrlString = url
let imageUrl:URL = URL(string: imageUrlString)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
return UIImage(data: imageData as Data)!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Force update of cell height when no media content
let post = self.posts[indexPath.row]
var postHeight = 300.0
if(post.video != ""){
postHeight += 150.0
}
if(post.mark != nil){
postHeight += 50.0
}
return CGFloat(postHeight)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for:indexPath) as! MyFeedsTableViewCell
let post = self.posts[indexPath.row]
//Initialize cell image to nil for fixing reuse cell issues
cell.mediaImageView.image = nil
cell.userNameLabel.text = post.author
cell.userReplyLabel.text = "@" + post.author
cell.postDescription.text = post.text
cell.postDate.text = post.datetimeCreated.description
if(post.flagOpinion){
self.fillRates(rates: [cell.rate1,cell.rate2,cell.rate3,cell.rate4,cell.rate5], mark: post.mark!)
self.ratesHidden( rates: [cell.rate1,cell.rate2,cell.rate3,cell.rate4,cell.rate5],isHidden: false)
}else{
self.ratesHidden( rates: [cell.rate1,cell.rate2,cell.rate3,cell.rate4,cell.rate5],isHidden: true)
}
if(post.video != ""){
// Extract youtube ID from URL
let mediaId = post.video.youtubeID!
let mediaURL = "http://img.youtube.com/vi/"+mediaId+"/mqdefault.jpg"
// Use of Utils extension for downloading youtube thumbnails
let isSucessMediaDownload = cell.mediaImageView.imageFromYoutube(url: mediaURL)
if isSucessMediaDownload {
// On tap gesture display presentation view with media content
cell.mediaImageView.isUserInteractionEnabled = true;
cell.mediaImageView.tag = indexPath.row
let tapGesture = UITapGestureRecognizer(target:self, action: #selector(self.showYoutubeModal(_:)))
cell.mediaImageView.addGestureRecognizer(tapGesture)
}else {
cell.mediaImageView.isUserInteractionEnabled = false
}
}
cell.numberComment.text = post.comments.count.description
cell.numberLike.text = post.likes.count.description
cell.commentAction = { (cell) in self.comment(post: post)}
return cell
}
func comment(post : Post){
print(post._id)
let storyboard = UIStoryboard(name: "Home", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Comment_ID") as! CommentViewController
vc.post = post
vc.note = post.mark
vc.flagOpinion = post.flagOpinion
self.navigationController?.pushViewController(vc, animated: true)
}
func refreshTableView(){
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
func getPostByUserId(){
let postsWB : WBPost = WBPost()
postsWB.getPostByUserId(userId: (user?._id)!,accessToken: AuthenticationService.sharedInstance.accessToken!,offset: "0" ){
(result: [Post]) in
self.posts = result
self.posts.reverse()
self.refreshTableView()
}
}
func getUsers()->Void{
let userWB : WBUser = WBUser()
userWB.getFollowedUser(accessToken: AuthenticationService.sharedInstance.accessToken!, userId : AuthenticationService.sharedInstance.currentUser!._id,offset: "0") {
(result: [User]) in
self.followers = result
}
}
func fillRates(rates : [UIImageView],mark : Int){
if(mark == 0)
{
return
}
for i in 0 ..< mark {
rates[i].image = UIImage(named: "starFill.png")
}
}
func ratesHidden(rates : [UIImageView],isHidden : Bool){
for i in 0 ..< rates.count {
rates[i].isHidden = isHidden
}
}
}
| bsd-3-clause | fb8ec70844bc7ee901f516e1ff2940e7 | 31.897674 | 173 | 0.590131 | 5.005662 | false | false | false | false |
morizotter/TouchVisualizer | TouchVisualizer/UIWindow+Swizzle.swift | 3 | 846 | //
// UIWindow+Swizzle.swift
// TouchVisualizer
//
import UIKit
fileprivate var isSwizzled = false
@available(iOS 8.0, *)
extension UIWindow {
public func swizzle() {
guard isSwizzled == false else {
return
}
let sendEvent = class_getInstanceMethod(
object_getClass(self),
#selector(UIApplication.sendEvent(_:))
)
let swizzledSendEvent = class_getInstanceMethod(
object_getClass(self),
#selector(UIWindow.swizzledSendEvent(_:))
)
method_exchangeImplementations(sendEvent!, swizzledSendEvent!)
isSwizzled = true
}
}
// MARK: - Swizzle
extension UIWindow {
@objc public func swizzledSendEvent(_ event: UIEvent) {
Visualizer.sharedInstance.handleEvent(event)
swizzledSendEvent(event)
}
}
| mit | a3e11f9a1bddcce250f23ad9deec8056 | 21.263158 | 70 | 0.626478 | 4.779661 | false | false | false | false |
luckymore0520/leetcode | Stack.playground/Contents.swift | 1 | 2326 | //: Playground - noun: a place where people can play
import UIKit
class MinStack<T:Comparable>:Stack<T>{
let minStack:Stack<T>
override init() {
minStack = Stack<T>()
super.init()
}
var minElement:T? {
return minStack.peek();
}
override func push(element:T){
super.push(element: element)
minStack.push(element: min(minElement ?? element, element))
}
override func pop() -> T?{
minStack.pop()
return super.pop()
}
}
class Stack<T>{
var stack: [T]
init(){
stack = [T]()
}
func push(element:T){
stack.append(element)
}
func pop() -> T?{
if (stack.isEmpty) {
return nil;
}
return stack.removeLast()
}
func isEmpty() -> Bool {
return stack.isEmpty;
}
func peek() -> T? {
return stack.last
}
func size() -> Int {
return stack.count;
}
}
func checkPopOrder<T:Comparable>(popOrder:[T],pushOrder:[T]) -> Bool {
if (popOrder.isEmpty || pushOrder.isEmpty || pushOrder.count != popOrder.count) {
return false;
}
let stack = Stack<T>();
var pushOrder = pushOrder;
for element in popOrder {
let top = stack.peek()
//如果栈顶的元素和比较的元素相等,pop,下一个
if (element == top) {
stack.pop()
} else if (pushOrder.count > 0){
//这里需要保证push的数组里还有,如果没有的话就肯定不符合了
//这里如果不等于的都直接压栈
while let elementToPush = pushOrder.first, elementToPush != element {
stack.push(element: pushOrder.removeFirst())
print(elementToPush)
}
//空了代表不符合了
if (pushOrder.isEmpty) {
return false
}
//否则就把第一个拿掉吧
print(pushOrder.removeFirst());
} else {
return false;
}
}
return true
}
checkPopOrder(popOrder:[4,3,5,1,2], pushOrder: [1,2,3,4,5] )
//
//
//let minStack = MinStack<Int>()
//minStack.push(element: 3);
//minStack.push(element: 4);
//minStack.minElement
//minStack.push(element: 0);
//minStack.minElement
| mit | 633a61147cca46c2ed211ffb28b3528f | 21.863158 | 85 | 0.532689 | 3.803853 | false | false | false | false |
yuanhoujun/firefox-ios | ClientTests/MockProfile.swift | 5 | 4134 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
public class MockSyncManager: SyncManager {
public func syncClients() -> SyncResult { return deferResult(.Completed) }
public func syncClientsThenTabs() -> SyncResult { return deferResult(.Completed) }
public func syncHistory() -> SyncResult { return deferResult(.Completed) }
public func syncLogins() -> SyncResult { return deferResult(.Completed) }
public func beginTimedSyncs() {}
public func endTimedSyncs() {}
public func onAddedAccount() -> Success {
return succeed()
}
public func onRemovedAccount(account: FirefoxAccount?) -> Success {
return succeed()
}
}
public class MockTabQueue: TabQueue {
public func addToQueue(tab: ShareItem) -> Success {
return succeed()
}
public func getQueuedTabs() -> Deferred<Result<Cursor<ShareItem>>> {
return deferResult(ArrayCursor<ShareItem>(data: []))
}
public func clearQueuedTabs() -> Success {
return succeed()
}
}
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
func shutdown() {
if dbCreated {
db.close()
}
}
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "mock.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = {
return SQLiteHistory(db: self.db)
}()
var favicons: Favicons {
return self.places
}
lazy var queue: TabQueue = {
return MockTabQueue()
}()
var history: protocol<BrowserHistory, SyncableHistory> {
return self.places
}
lazy var syncManager: SyncManager = {
return MockSyncManager()
}()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
return SQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
lazy var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
private lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var logins: protocol<BrowserLogins, SyncableLogins> = {
return MockLogins(files: self.files)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
func getClients() -> Deferred<Result<[RemoteClient]>> {
return deferResult([])
}
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
}
} | mpl-2.0 | 6dadac0b15989c4fdaaafcfd2e05446a | 25.677419 | 99 | 0.651427 | 4.980723 | false | false | false | false |
dreamsxin/swift | test/SILGen/external_definitions.swift | 6 | 2608 | // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen | FileCheck %s
// REQUIRES: objc_interop
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @_TFCSo7AnsibleC
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @_TFCSo8NSObjectC{{.*}} : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: release_value [[ANSIBLE]] : $ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(method) (@owned ImplicitlyUnwrappedOptional<AnyObject>, @thick Ansible.Type) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared @_TFCSo8NSObjectC{{.*}} : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// -- Native Swift thunk for NSAnse
// CHECK: sil shared [fragile] [thunk] @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible> {
// CHECK: bb0(%0 : $ImplicitlyUnwrappedOptional<Ansible>):
// CHECK: %1 = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: %2 = apply %1(%0) : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: release_value %0 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: return %2 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(method) (@thick Ansible.Type) -> @owned Ansible
| apache-2.0 | 2a51c1b8a12e2d7e0a1eb97f285e88ba | 56.955556 | 193 | 0.712423 | 4.186196 | false | false | false | false |
diesmal/thisorthat | Carthage/Checkouts/PieCharts/PieCharts/Layer/Impl/View/PieViewLayer.swift | 1 | 2454 | //
// PieViewLayer.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
open class PieViewLayerSettings {
public var viewRadius: CGFloat?
public var hideOnOverflow = true // NOTE: Considers only space defined by angle with origin at the center of the pie chart. Arcs (inner/outer radius) are ignored.
public init() {}
}
open class PieViewLayer: PieChartLayer {
public weak var chart: PieChart?
public var settings: PieViewLayerSettings = PieViewLayerSettings()
public var onNotEnoughSpace: ((UIView, CGSize) -> Void)?
fileprivate var sliceViews = [PieSlice: UIView]()
public var animator: PieViewLayerAnimator = AlphaPieViewLayerAnimator()
public var viewGenerator: ((PieSlice, CGPoint) -> UIView)?
public init() {}
public func onEndAnimation(slice: PieSlice) {
addItems(slice: slice)
}
public func addItems(slice: PieSlice) {
guard sliceViews[slice] == nil else {return}
let center = settings.viewRadius.map{slice.view.midPoint(radius: $0)} ?? slice.view.arcCenter
guard let view = viewGenerator?(slice, center) else {print("Need a view generator to create views!"); return}
let size = view.frame.size
let availableSize = CGSize(width: slice.view.maxRectWidth(center: center, height: size.height), height: size.height)
if !settings.hideOnOverflow || availableSize.contains(size) {
view.center = center
chart?.addSubview(view)
} else {
onNotEnoughSpace?(view, availableSize)
}
animator.animate(view)
sliceViews[slice] = view
}
public func onSelected(slice: PieSlice, selected: Bool) {
guard let label = sliceViews[slice] else {print("Invalid state: slice not in dictionary"); return}
let p = slice.view.calculatePosition(angle: slice.view.midAngle, p: label.center, offset: selected ? slice.view.selectedOffset : -slice.view.selectedOffset)
UIView.animate(withDuration: 0.15) {
label.center = p
}
}
public func clear() {
for (_, view) in sliceViews {
view.removeFromSuperview()
}
sliceViews.removeAll()
}
}
| apache-2.0 | 38d4c00df27ce392edc9e1080fd13c04 | 29.283951 | 166 | 0.617611 | 4.672381 | false | false | false | false |
rowungiles/SwiftTech | SwiftTech/SwiftTech/Utilities/Operations/ConcurrentOperation.swift | 1 | 1420 | //
// ConcurrentOperation.swift
// SwiftTech
//
// Created by Rowun Giles on 06/01/2016.
// Copyright © 2016 Rowun Giles. All rights reserved.
//
import Foundation
class ConcurrentOperation: NSOperation {
enum State {
case Ready, Executing, Finished
func keyPath() -> String {
switch self {
case Ready:
return "isReady"
case Executing:
return "isExecuting"
case Finished:
return "isFinished"
}
}
}
var state = State.Ready {
willSet {
willChangeValueForKey(newValue.keyPath())
willChangeValueForKey(state.keyPath())
}
didSet {
didChangeValueForKey(oldValue.keyPath())
didChangeValueForKey(state.keyPath())
}
}
override var ready: Bool {
return super.ready && state == .Ready
}
override var executing: Bool {
return state == .Executing
}
override var finished: Bool {
return state == .Finished
}
override var asynchronous: Bool {
return true
}
override func start() {
if cancelled {
state = .Finished
} else {
main()
state = .Executing
}
}
} | gpl-3.0 | 2fc95781e439b732736d4c46a9815d32 | 19.57971 | 54 | 0.489077 | 5.653386 | false | false | false | false |
velvetroom/columbus | Source/Model/Settings/MSettingsTravelMode.swift | 1 | 953 | import UIKit
final class MSettingsTravelMode:MSettingsProtocol
{
let reusableIdentifier:String = VSettingsListCellTravelMode.reusableIdentifier
let cellHeight:CGFloat = 205
let items:[MSettingsTravelModeProtocol]
let indexMap:[DPlanTravelMode:Int]
private(set) weak var settings:DSettings!
private(set) weak var database:Database!
var selectedIndex:Int?
{
get
{
let index:Int? = indexMap[settings.travelMode]
return index
}
}
init(
settings:DSettings,
database:Database)
{
self.settings = settings
self.database = database
items = MSettingsTravelMode.factoryItems()
indexMap = MSettingsTravelMode.factoryIndexMap(items:items)
}
//MARK: internal
func selected(index:Int)
{
settings.travelMode = items[index].mode
database.save { }
}
}
| mit | d2f319ce7d1d1cafd82cf05d20ef529b | 22.825 | 82 | 0.623295 | 4.963542 | false | false | false | false |
ben-ng/swift | test/SILGen/functions.swift | 1 | 22471 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
import Swift // just for Optional
func markUsed<T>(_ t: T) {}
typealias Int = Builtin.Int64
typealias Int64 = Builtin.Int64
typealias Bool = Builtin.Int1
var zero = getInt()
func getInt() -> Int { return zero }
func standalone_function(_ x: Int, _ y: Int) -> Int {
return x
}
func higher_order_function(_ f: (_ x: Int, _ y: Int) -> Int, _ x: Int, _ y: Int) -> Int {
return f(x, y)
}
func higher_order_function2(_ f: (Int, Int) -> Int, _ x: Int, _ y: Int) -> Int {
return f(x, y)
}
struct SomeStruct {
// -- Constructors and methods are uncurried in 'self'
// -- Instance methods use 'method' cc
init(x:Int, y:Int) {}
mutating
func method(_ x: Int) {}
static func static_method(_ x: Int) {}
func generic_method<T>(_ x: T) {}
}
class SomeClass {
// -- Constructors and methods are uncurried in 'self'
// -- Instance methods use 'method' cc
// CHECK-LABEL: sil hidden @_TFC9functions9SomeClassc{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @owned SomeClass) -> @owned SomeClass
// CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $SomeClass):
// CHECK-LABEL: sil hidden @_TFC9functions9SomeClassC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass
// CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $@thick SomeClass.Type):
init(x:Int, y:Int) {}
// CHECK-LABEL: sil hidden @_TFC9functions9SomeClass6method{{.*}} : $@convention(method) (Builtin.Int64, @guaranteed SomeClass) -> ()
// CHECK: bb0(%0 : $Builtin.Int64, %1 : $SomeClass):
func method(_ x: Int) {}
// CHECK-LABEL: sil hidden @_TZFC9functions9SomeClass13static_method{{.*}} : $@convention(method) (Builtin.Int64, @thick SomeClass.Type) -> ()
// CHECK: bb0(%0 : $Builtin.Int64, %1 : $@thick SomeClass.Type):
class func static_method(_ x: Int) {}
var someProperty: Int {
get {
return zero
}
set {}
}
subscript(x:Int, y:Int) -> Int {
get {
return zero
}
set {}
}
func generic<T>(_ x: T) -> T {
return x
}
}
func SomeClassWithBenefits() -> SomeClass.Type {
return SomeClass.self
}
protocol SomeProtocol {
func method(_ x: Int)
static func static_method(_ x: Int)
}
struct ConformsToSomeProtocol : SomeProtocol {
func method(_ x: Int) { }
static func static_method(_ x: Int) { }
}
class SomeGeneric<T> {
init() { }
func method(_ x: T) -> T { return x }
func generic<U>(_ x: U) -> U { return x }
}
// CHECK-LABEL: sil hidden @_TF9functions5calls{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> ()
func calls(_ i:Int, j:Int, k:Int) {
var i = i
var j = j
var k = k
// CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $Builtin.Int64):
// CHECK: [[IBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Builtin.Int64>
// CHECK: [[IADDR:%.*]] = project_box [[IBOX]]
// CHECK: [[JBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Builtin.Int64>
// CHECK: [[JADDR:%.*]] = project_box [[JBOX]]
// CHECK: [[KBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Builtin.Int64>
// CHECK: [[KADDR:%.*]] = project_box [[KBOX]]
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: apply [[FUNC]]([[I]], [[J]])
standalone_function(i, j)
// -- Curry 'self' onto struct method argument lists.
// CHECK: [[ST_ADDR:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <SomeStruct>
// CHECK: [[CTOR:%.*]] = function_ref @_TFV9functions10SomeStructC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct
// CHECK: [[METATYPE:%.*]] = metatype $@thin SomeStruct.Type
// CHECK: [[I:%.*]] = load [trivial] [[IADDR]]
// CHECK: [[J:%.*]] = load [trivial] [[JADDR]]
// CHECK: apply [[CTOR]]([[I]], [[J]], [[METATYPE]]) : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct
var st = SomeStruct(x: i, y: j)
// -- Use of unapplied struct methods as values.
// CHECK: [[THUNK:%.*]] = function_ref @_TFV9functions10SomeStruct6method{{.*}}
// CHECK: [[THUNK_THICK:%.*]] = thin_to_thick_function [[THUNK]]
var stm1 = SomeStruct.method
stm1(&st)(i)
// -- Curry 'self' onto method argument lists dispatched using class_method.
// CHECK: [[CBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <SomeClass>
// CHECK: [[CADDR:%.*]] = project_box [[CBOX]]
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TFC9functions9SomeClassC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass
// CHECK: [[META:%[0-9]+]] = metatype $@thick SomeClass.Type
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: [[C:%[0-9]+]] = apply [[FUNC]]([[I]], [[J]], [[META]])
var c = SomeClass(x: i, y: j)
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: apply [[METHOD]]([[I]], [[C]])
// CHECK: destroy_value [[C]]
c.method(i)
// -- Curry 'self' onto unapplied methods dispatched using class_method.
// CHECK: [[METHOD_CURRY_THUNK:%.*]] = function_ref @_TFC9functions9SomeClass6method{{.*}}
// CHECK: apply [[METHOD_CURRY_THUNK]]
var cm1 = SomeClass.method(c)
cm1(i)
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: apply [[METHOD]]([[I]], [[C]])
// CHECK: destroy_value [[C]]
SomeClass.method(c)(i)
// -- Curry the Type onto static method argument lists.
// CHECK: [[C:%[0-9]+]] = load_borrow [[CADDR]]
// CHECK: [[META:%.*]] = value_metatype $@thick SomeClass.Type, [[C]]
// CHECK: [[METHOD:%[0-9]+]] = class_method [[META]] : {{.*}}, #SomeClass.static_method!1
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: apply [[METHOD]]([[I]], [[META]])
type(of: c).static_method(i)
// -- Curry property accesses.
// -- FIXME: class_method-ify class getters.
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[GETTER:%[0-9]+]] = class_method {{.*}} : $SomeClass, #SomeClass.someProperty!getter.1
// CHECK: apply [[GETTER]]([[C]])
// CHECK: destroy_value [[C]]
i = c.someProperty
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.someProperty!setter.1 : (SomeClass) -> (Builtin.Int64) -> ()
// CHECK: apply [[SETTER]]([[I]], [[C]])
// CHECK: destroy_value [[C]]
c.someProperty = i
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: [[K:%[0-9]+]] = load [trivial] [[KADDR]]
// CHECK: [[GETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!getter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 , $@convention(method) (Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> Builtin.Int64
// CHECK: apply [[GETTER]]([[J]], [[K]], [[C]])
// CHECK: destroy_value [[C]]
i = c[j, k]
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: [[K:%[0-9]+]] = load [trivial] [[KADDR]]
// CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!setter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> () , $@convention(method) (Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> ()
// CHECK: apply [[SETTER]]([[K]], [[I]], [[J]], [[C]])
// CHECK: destroy_value [[C]]
c[i, j] = k
// -- Curry the projected concrete value in an existential (or its Type)
// -- onto protocol type methods dispatched using protocol_method.
// CHECK: [[PBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <SomeProtocol>
// CHECK: [[PADDR:%.*]] = project_box [[PBOX]]
var p : SomeProtocol = ConformsToSomeProtocol()
// CHECK: [[TEMP:%.*]] = alloc_stack $SomeProtocol
// CHECK: copy_addr [[PADDR]] to [initialization] [[TEMP]]
// CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr [[TEMP]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]]
// CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]])
// CHECK: destroy_addr [[PVALUE]]
// CHECK: deinit_existential_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
p.method(i)
// CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr [[PADDR:%.*]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]]
// CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]])
var sp : SomeProtocol = ConformsToSomeProtocol()
sp.method(i)
// FIXME: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED:@opened(.*) SomeProtocol]], #SomeProtocol.static_method!1
// FIXME: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// FIXME: apply [[PMETHOD]]([[I]], [[PMETA]])
// Needs existential metatypes
//type(of: p).static_method(i)
// -- Use an apply or partial_apply instruction to bind type parameters of a generic.
// CHECK: [[GBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <SomeGeneric<Builtin.Int64>>
// CHECK: [[GADDR:%.*]] = project_box [[GBOX]]
// CHECK: [[CTOR_GEN:%[0-9]+]] = function_ref @_TFC9functions11SomeGenericC{{.*}} : $@convention(method) <τ_0_0> (@thick SomeGeneric<τ_0_0>.Type) -> @owned SomeGeneric<τ_0_0>
// CHECK: [[META:%[0-9]+]] = metatype $@thick SomeGeneric<Builtin.Int64>.Type
// CHECK: apply [[CTOR_GEN]]<Builtin.Int64>([[META]])
var g = SomeGeneric<Builtin.Int64>()
// CHECK: [[G:%[0-9]+]] = load [copy] [[GADDR]]
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.method!1
// CHECK: [[TMPI:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPI]], [[G]])
// CHECK: destroy_value [[G]]
g.method(i)
// CHECK: [[G:%[0-9]+]] = load [copy] [[GADDR]]
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.generic!1
// CHECK: [[TMPJ:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPJ]], [[G]])
// CHECK: destroy_value [[G]]
g.generic(j)
// CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]]
// CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.generic!1
// CHECK: [[TMPK:%.*]] = alloc_stack $Builtin.Int64
// CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64
// CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPK]], [[C]])
// CHECK: destroy_value [[C]]
c.generic(k)
// FIXME: curried generic entry points
//var gm1 = g.method
//gm1(i)
//var gg1 : (Int) -> Int = g.generic
//gg1(j)
//var cg1 : (Int) -> Int = c.generic
//cg1(k)
// SIL-level "thin" function values need to be able to convert to
// "thick" function values when stored, returned, or passed as arguments.
// CHECK: [[FBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <@callee_owned (Builtin.Int64, Builtin.Int64) -> Builtin.Int64>
// CHECK: [[FADDR:%.*]] = project_box [[FBOX]]
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: store [[FUNC_THICK]] to [init] [[FADDR]]
var f = standalone_function
// CHECK: [[F:%[0-9]+]] = load [copy] [[FADDR]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: apply [[F]]([[I]], [[J]])
f(i, j)
// CHECK: [[HOF:%[0-9]+]] = function_ref @_TF9functions21higher_order_function{{.*}} : $@convention(thin) {{.*}}
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: apply [[HOF]]([[FUNC_THICK]], [[I]], [[J]])
higher_order_function(standalone_function, i, j)
// CHECK: [[HOF2:%[0-9]+]] = function_ref @_TF9functions22higher_order_function2{{.*}} : $@convention(thin) {{.*}}
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%.*]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]]
// CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]]
// CHECK: apply [[HOF2]]([[FUNC_THICK]], [[I]], [[J]])
higher_order_function2(standalone_function, i, j)
}
// -- Curried entry points
// CHECK-LABEL: sil shared [thunk] @_TFV9functions10SomeStruct6method{{.*}} : $@convention(thin) (@inout SomeStruct) -> @owned @callee_owned (Builtin.Int64) -> () {
// CHECK: [[UNCURRIED:%.*]] = function_ref @_TFV9functions10SomeStruct6method{{.*}} : $@convention(method) (Builtin.Int64, @inout SomeStruct) -> (){{.*}} // user: %2
// CHECK: [[CURRIED:%.*]] = partial_apply [[UNCURRIED]]
// CHECK: return [[CURRIED]]
// CHECK-LABEL: sil shared [thunk] @_TFC9functions9SomeClass6method{{.*}} : $@convention(thin) (@owned SomeClass) -> @owned @callee_owned (Builtin.Int64) -> ()
// CHECK: bb0(%0 : $SomeClass):
// CHECK: class_method %0 : $SomeClass, #SomeClass.method!1 : (SomeClass) -> (Builtin.Int64) -> ()
// CHECK: %2 = partial_apply %1(%0)
// CHECK: return %2
func return_func() -> (_ x: Builtin.Int64, _ y: Builtin.Int64) -> Builtin.Int64 {
// CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64
// CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]]
// CHECK: return [[FUNC_THICK]]
return standalone_function
}
func standalone_generic<T>(_ x: T, y: T) -> T { return x }
// CHECK-LABEL: sil hidden @_TF9functions14return_genericFT_FTBi64_Bi64__Bi64_
func return_generic() -> (_ x:Builtin.Int64, _ y:Builtin.Int64) -> Builtin.Int64 {
// CHECK: [[GEN:%.*]] = function_ref @_TF9functions18standalone_generic{{.*}} : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0
// CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<Builtin.Int64>()
// CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in Builtin.Int64, @in Builtin.Int64) -> @out Builtin.Int64) -> Builtin.Int64
// CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]])
// CHECK: return [[T0]]
return standalone_generic
}
// CHECK-LABEL: sil hidden @_TF9functions20return_generic_tuple{{.*}}
func return_generic_tuple()
-> (_ x: (Builtin.Int64, Builtin.Int64), _ y: (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) {
// CHECK: [[GEN:%.*]] = function_ref @_TF9functions18standalone_generic{{.*}} : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0
// CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<(Builtin.Int64, Builtin.Int64)>()
// CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in (Builtin.Int64, Builtin.Int64), @in (Builtin.Int64, Builtin.Int64)) -> @out (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64)
// CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]])
// CHECK: return [[T0]]
return standalone_generic
}
// CHECK-LABEL: sil hidden @_TF9functions16testNoReturnAttrFT_Os5Never : $@convention(thin) () -> Never
func testNoReturnAttr() -> Never {}
// CHECK-LABEL: sil hidden @_TF9functions20testNoReturnAttrPoly{{.*}} : $@convention(thin) <T> (@in T) -> Never
func testNoReturnAttrPoly<T>(_ x: T) -> Never {}
// CHECK-LABEL: sil hidden @_TF9functions21testNoReturnAttrParam{{.*}} : $@convention(thin) (@owned @callee_owned () -> Never) -> ()
func testNoReturnAttrParam(_ fptr: () -> Never) -> () {}
// CHECK-LABEL: sil hidden [transparent] @_TF9functions15testTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
@_transparent func testTransparent(_ x: Bool) -> Bool {
return x
}
// CHECK-LABEL: sil hidden @_TF9functions16applyTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 {
func applyTransparent(_ x: Bool) -> Bool {
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF9functions15testTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
// CHECK: apply [[FUNC]]({{%[0-9]+}}) : $@convention(thin) (Builtin.Int1) -> Builtin.Int1
return testTransparent(x)
}
// CHECK-LABEL: sil hidden [noinline] @_TF9functions15noinline_calleeFT_T_ : $@convention(thin) () -> ()
@inline(never)
func noinline_callee() {}
// CHECK-LABEL: sil hidden [always_inline] @_TF9functions20always_inline_calleeFT_T_ : $@convention(thin) () -> ()
@inline(__always)
func always_inline_callee() {}
// CHECK-LABEL: sil [fragile] [always_inline] @_TF9functions27public_always_inline_calleeFT_T_ : $@convention(thin) () -> ()
@inline(__always)
public func public_always_inline_callee() {}
protocol AlwaysInline {
func alwaysInlined()
}
// CHECK-LABEL: sil hidden [always_inline] @_TFV9functions19AlwaysInlinedMember13alwaysInlined{{.*}} : $@convention(method) (AlwaysInlinedMember) -> () {
// protocol witness for functions.AlwaysInline.alwaysInlined <A : functions.AlwaysInline>(functions.AlwaysInline.Self)() -> () in conformance functions.AlwaysInlinedMember : functions.AlwaysInline in functions
// CHECK-LABEL: sil hidden [transparent] [thunk] [always_inline] @_TTWV9functions19AlwaysInlinedMemberS_12AlwaysInlineS_FS1_13alwaysInlined{{.*}} : $@convention(witness_method) (@in_guaranteed AlwaysInlinedMember) -> () {
struct AlwaysInlinedMember : AlwaysInline {
@inline(__always)
func alwaysInlined() {}
}
// CHECK-LABEL: sil hidden [_semantics "foo"] @_TF9functions9semanticsFT_T_ : $@convention(thin) () -> ()
@_semantics("foo")
func semantics() {}
// <rdar://problem/17828355> curried final method on a class crashes in irgen
final class r17828355Class {
func method(_ x : Int) {
var a : r17828355Class
var fn = a.method // currying a final method.
}
}
// The curry thunk for the method should not include a class_method instruction.
// CHECK-LABEL: sil shared [thunk] @_TFC9functions14r17828355Class6methodF
// CHECK: bb0(%0 : $r17828355Class):
// CHECK-NEXT: // function_ref functions.r17828355Class.method (Builtin.Int64) -> ()
// CHECK-NEXT: %1 = function_ref @_TFC9functions14r17828355Class6method{{.*}} : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> ()
// CHECK-NEXT: partial_apply %1(%0) : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> ()
// CHECK-NEXT: return
// <rdar://problem/19981118> Swift 1.2 beta 2: Closures nested in closures copy, rather than reference, captured vars.
func noescapefunc(f: () -> ()) {}
func escapefunc(_ f : @escaping () -> ()) {}
func testNoescape() {
// "a" must be captured by-box into noescapefunc because the inner closure
// could escape it.
var a = 0
noescapefunc {
escapefunc { a = 42 }
}
markUsed(a)
}
// CHECK-LABEL: functions.testNoescape () -> ()
// CHECK-NEXT: sil hidden @_TF9functions12testNoescapeFT_T_ : $@convention(thin) () -> ()
// CHECK: function_ref functions.(testNoescape () -> ()).(closure #1)
// CHECK-NEXT: function_ref @_TFF9functions12testNoescapeFT_T_U_FT_T_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> ()
// Despite being a noescape closure, this needs to capture 'a' by-box so it can
// be passed to the capturing closure.closure
// CHECK: functions.(testNoescape () -> ()).(closure #1)
// CHECK-NEXT: sil shared @_TFF9functions12testNoescapeFT_T_U_FT_T_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> () {
func testNoescape2() {
// "a" must be captured by-box into noescapefunc because the inner closure
// could escape it. This also checks for when the outer closure captures it
// in a way that could be used with escape: the union of the two requirements
// doesn't allow a by-address capture.
var a = 0
noescapefunc {
escapefunc { a = 42 }
markUsed(a)
}
markUsed(a)
}
// CHECK-LABEL: sil hidden @_TF9functions13testNoescape2FT_T_ : $@convention(thin) () -> () {
// CHECK: // functions.(testNoescape2 () -> ()).(closure #1)
// CHECK-NEXT: sil shared @_TFF9functions13testNoescape2FT_T_U_FT_T_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> () {
// CHECK: // functions.(testNoescape2 () -> ()).(closure #1).(closure #1)
// CHECK-NEXT: sil shared @_TFFF9functions13testNoescape2FT_T_U_FT_T_U_FT_T_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> () {
enum PartialApplyEnumPayload<T, U> {
case Left(T)
case Right(U)
}
struct S {}
struct C {}
func partialApplyEnumCases(_ x: S, y: C) {
let left = PartialApplyEnumPayload<S, C>.Left
let left2 = left(S())
let right = PartialApplyEnumPayload<S, C>.Right
let right2 = right(C())
}
// CHECK-LABEL: sil shared [transparent] [thunk] @_TFO9functions23PartialApplyEnumPayload4Left{{.*}}
// CHECK: [[UNCURRIED:%.*]] = function_ref @_TFO9functions23PartialApplyEnumPayload4Left{{.*}}
// CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0)
// CHECK: return [[CLOSURE]]
// CHECK-LABEL: sil shared [transparent] [thunk] @_TFO9functions23PartialApplyEnumPayload5Right{{.*}}
// CHECK: [[UNCURRIED:%.*]] = function_ref @_TFO9functions23PartialApplyEnumPayload5Right{{.*}}
// CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0)
// CHECK: return [[CLOSURE]]
| apache-2.0 | 5d6d10f42027be47dbf8a84258fd5c63 | 44.325253 | 298 | 0.612097 | 3.232387 | false | false | false | false |
mcxiaoke/learning-ios | ios_programming_4th/Homepwner-ch8/Homepwner/Item.swift | 1 | 1132 | //
// Item.swift
// Homepwner
//
// Created by Xiaoke Zhang on 2017/8/16.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import Foundation
struct Item {
var itemName:String
var serialNumber:String
var valueInDollars:Int
let dateCreated:Date = Date()
var description:String {
return "\(itemName) (\(serialNumber)) Worth \(valueInDollars), recorded on \(dateCreated)"
}
static func randomItem() -> Item {
let adjectives = ["Fluffy", "Rusty", "Shiny"]
let nouns = ["Bear", "Spork", "Mac"]
let ai = Int(arc4random()) % adjectives.count
let ni = Int(arc4random()) % nouns.count
let randomName = "\(adjectives[ai]) \(nouns[ni])"
let randomValue = Int(arc4random_uniform(100))
let s0 = "0\(arc4random_uniform(10))"
let s1 = "A\(arc4random_uniform(26))"
let s2 = "0\(arc4random_uniform(10))"
let randomSerialNumber = "\(s0)-\(s1)-\(s2)"
return Item(itemName:randomName,
serialNumber:randomSerialNumber,
valueInDollars: randomValue)
}
}
| apache-2.0 | 5171c0b97506443db4db9269bab4cd6d | 29.513514 | 98 | 0.59256 | 3.933798 | false | false | false | false |
iOS-mamu/SS | P/Pods/PSOperations/PSOperations/LocationCapability-OSX.swift | 1 | 2740 | //
// LocationCapability-OSX.swift
// PSOperations
//
// Created by Dev Team on 10/4/15.
// Copyright © 2015 Pluralsight. All rights reserved.
//
#if os(OSX)
import Foundation
import CoreLocation
public struct Location: CapabilityType {
public static let name = "Location"
public init() { }
public func requestStatus(_ completion: @escaping (CapabilityStatus) -> Void) {
guard CLLocationManager.locationServicesEnabled() else {
completion(.notAvailable)
return
}
let actual = CLLocationManager.authorizationStatus()
switch actual {
case .notDetermined:
completion(.notDetermined)
case .restricted:
completion(.notAvailable)
case .denied:
completion(.denied)
case .authorized:
completion(.authorized)
default:
completion(.authorized)
}
}
public func authorize(_ completion: @escaping (CapabilityStatus) -> Void) {
Authorizer.authorize(completion: completion)
}
}
private let Authorizer = LocationAuthorizer()
fileprivate class LocationAuthorizer: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var completion: ((CapabilityStatus) -> Void)?
override init() {
super.init()
manager.delegate = self
}
func authorize(completion: @escaping (CapabilityStatus) -> Void) {
guard self.completion == nil else {
fatalError("Attempting to authorize location when a request is already in-flight")
}
self.completion = completion
let key = "NSLocationUsageDescription"
manager.startUpdatingLocation()
// This is helpful when developing an app.
assert(Bundle.main.object(forInfoDictionaryKey: key) != nil, "Requesting location permission requires the \(key) key in your Info.plist")
}
@objc func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if let completion = self.completion, manager == self.manager {
self.completion = nil
switch status {
case .authorized:
completion(.authorized)
case .denied:
completion(.denied)
case .restricted:
completion(.notAvailable)
case .notDetermined:
self.completion = completion
manager.startUpdatingLocation()
manager.stopUpdatingLocation()
default:
completion(.authorized)
}
}
}
}
#endif
| mit | 1e9efd79a4a50cddbf08ae75b16136d6 | 27.831579 | 145 | 0.60314 | 5.601227 | false | false | false | false |
thierrybucco/Eureka | Source/Core/BaseRow.swift | 5 | 9445 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseRow: BaseRowType {
var callbackOnChange: (() -> Void)?
var callbackCellUpdate: (() -> Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (() -> Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var callbackOnCellHighlightChanged: (() -> Void)?
var callbackOnRowValidationChanged: (() -> Void)?
var _inlineRow: BaseRow?
public var validationOptions: ValidationOptions = .validatesOnBlur
// validation state
public internal(set) var validationErrors = [ValidationError]() {
didSet {
guard validationErrors != oldValue else { return }
RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self)
callbackOnRowValidationChanged?()
updateCell()
}
}
public internal(set) var wasBlurred = false
public internal(set) var wasChanged = false
public var isValid: Bool { return validationErrors.isEmpty }
public var isHighlighted: Bool = false
/// The title will be displayed in the textLabel of the row.
public var title: String?
/// Parameter used when creating the cell for this row.
public var cellStyle = UITableViewCellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
public var tag: String?
/// The untyped cell associated to this row.
public var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
public var baseValue: Any? {
set {}
get { return nil }
}
public func validate() -> [ValidationError] {
return []
}
public static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
public var disabled: Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
public var hidden: Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
public var isDisabled: Bool { return disabledCache }
/// Returns if this row is currently hidden or not
public var isHidden: Bool { return hiddenCache }
/// The section to which this row belongs.
public weak var section: Section?
public required init(tag: String? = nil) {
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
open func prepare(for segue: UIStoryboardSegue) {}
/**
Returns the IndexPath where this row is in the current form.
*/
public final var indexPath: IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.index(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
var hiddenCache = false
var disabledCache = false {
willSet {
if newValue && !disabledCache {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_, let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hide(row: self)
} else {
section?.show(row: self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_, let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedTo(section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers() {
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm() {
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers() {
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(with rowAnimation: UITableViewRowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(animated: Bool = true) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(animated: Bool = false, scrollPosition: UITableViewScrollPosition = .none) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
}
public func == (lhs: BaseRow, rhs: BaseRow) -> Bool {
return lhs === rhs
}
| mit | 5957cf4f7a357a95bad350cc879f0e99 | 34.641509 | 177 | 0.652091 | 5.048103 | false | false | false | false |
qds-hoi/suracare | suracare/suracare/App/ViewControllers/PlayAudioViewController/rSPlayAudioViewController.swift | 1 | 13636 | //
// rSPlayAudioViewController.swift
// suracare
//
// Created by hoi on 8/16/16.
// Copyright © 2016 Sugar Rain. All rights reserved.
//
import UIKit
import AVFoundation
import Foundation
import CoreData
class Voice: NSObject {
var date: NSDate
var filename: String?
var subject: String = ""
var duration: NSNumber = 0.0
override init() {
self.date = NSDate()
self.filename = "filename"
self.subject = "subject"
self.duration = 0.0
}
}
class AudioSessionHelper {
struct Constants {
struct Notification {
struct AudioObjectWillStart {
static let Name = "KMAudioObjectWillStartNotification"
struct UserInfo {
static let AudioObjectKey = "KMAudioObjectWillStartNotificationAudioObjectKey"
}
}
}
}
class func postStartAudioNotificaion(AudioObject: NSObject) {
let userInfo = [Constants.Notification.AudioObjectWillStart.UserInfo.AudioObjectKey: AudioObject]
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.AudioObjectWillStart.Name,
object: nil,
userInfo: userInfo)
}
class func setupSessionActive(active: Bool, catagory: String = AVAudioSessionCategoryPlayback) {
let session = AVAudioSession.sharedInstance()
if active {
do {
try session.setCategory(catagory)
} catch {
debugPrint("Could not set session category: \(error)")
}
do {
try session.setActive(true)
} catch {
debugPrint("Could not activate session: \(error)")
}
} else {
do {
try session.setActive(false, withOptions: .NotifyOthersOnDeactivation)
} catch {
("Could not deactivate session: \(error)")
}
}
}
}
protocol rSPlayAudioViewControllerDelegate {
func didFinishViewController(detailViewController: rSPlayAudioViewController, didSave: Bool)
}
class rSPlayAudioViewController: rSBaseViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var progressSlider: UISlider!
var voice: Voice = Voice()
var recordingHasUpdates = false
var overlayTransitioningDelegate: KMOverlayTransitioningDelegate?
let tmpStoreURL = NSURL.fileURLWithPath(NSTemporaryDirectory()).URLByAppendingPathComponent("tmpVoice.caf")
lazy var dateFormatter: NSDateFormatter = {
var formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .ShortStyle
return formatter
}()
lazy var directoryURL: NSURL = {
let doucumentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let _directoryURL = doucumentURL.URLByAppendingPathComponent("Voice")
do {
try NSFileManager.defaultManager().createDirectoryAtURL(_directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
assertionFailure("Error creating directory: \(error)")
}
return _directoryURL
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
playback.playButton = self.playButton
playback.progressSlider = self.progressSlider
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
NSNotificationCenter.defaultCenter().addObserver(self, selector: "audioObjectWillStart:", name: AudioSessionHelper.Constants.Notification.AudioObjectWillStart.Name, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "proximityStateDidChange:", name: UIDeviceProximityStateDidChangeNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if playback.audioPlayer?.playing == true {
playback.state = .Default(deactive: true)
} else {
playback.state = .Default(deactive: false)
}
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
NSNotificationCenter.defaultCenter().removeObserver(self, name: AudioSessionHelper.Constants.Notification.AudioObjectWillStart.Name, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceProximityStateDidChangeNotification, object: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Record" {
playback.state = .Default(deactive: false)
let recordViewController = segue.destinationViewController as! rSRecordViewController
recordViewController.configRecorderWithURL(tmpStoreURL, delegate: self)
overlayTransitioningDelegate = KMOverlayTransitioningDelegate()
transitioningDelegate = overlayTransitioningDelegate
recordViewController.modalPresentationStyle = .Custom
recordViewController.transitioningDelegate = overlayTransitioningDelegate
}
}
@IBAction func playAudioButtonTapped(sender: AnyObject) {
if let player = playback.audioPlayer {
if player.playing {
playback.state = .Pause(deactive: true)
} else {
playback.state = .Play
}
} else {
let url: NSURL = {
if self.recordingHasUpdates {
return self.tmpStoreURL
} else {
return self.directoryURL.URLByAppendingPathComponent(self.voice.filename!)
}
}()
do {
try playback.audioPlayer = AVAudioPlayer(contentsOfURL: url)
playback.audioPlayer!.delegate = self
playback.audioPlayer!.prepareToPlay()
playback.state = .Play
} catch {
let alertController = UIAlertController(title: nil, message: "The audio file seems to be corrupted. Do you want to retake?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { _ in
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Retake", style: .Destructive) { _ in
self.performSegueWithIdentifier("Record", sender: self)
}
alertController.addAction(OKAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
}
// MARK: - Playback Control
class KMPlayback {
var playButton: UIButton!
var progressSlider: UISlider!
var audioPlayer: AVAudioPlayer?
var timer: NSTimer?
var state: KMPlaybackState = .Default(deactive: false) {
didSet {
state.changePlaybackState(self)
}
}
@objc func updateprogressSliderValue() {
if let player = audioPlayer {
progressSlider.value = Float(player.currentTime / player.duration)
}
}
}
enum KMPlaybackState {
case Play
case Pause(deactive: Bool)
case Finish
case Default(deactive: Bool)
func changePlaybackState(playback: KMPlayback) {
switch self {
case .Play:
if let player = playback.audioPlayer {
AudioSessionHelper.postStartAudioNotificaion(player)
playback.timer?.invalidate()
playback.timer = NSTimer(
timeInterval: 0.1,
target: playback,
selector: "updateprogressSliderValue",
userInfo: nil,
repeats: true)
NSRunLoop.currentRunLoop().addTimer(playback.timer!, forMode: NSRunLoopCommonModes)
AudioSessionHelper.setupSessionActive(true)
if !player.playing {
player.currentTime = NSTimeInterval(playback.progressSlider.value) * player.duration
player.play()
}
UIDevice.currentDevice().proximityMonitoringEnabled = true
playback.playButton.setImage(UIImage(named: "ic_pause"), forState: .Normal)
playback.updateprogressSliderValue()
}
case .Pause(let deactive):
playback.timer?.invalidate()
playback.timer = nil
playback.audioPlayer?.pause()
UIDevice.currentDevice().proximityMonitoringEnabled = false
if deactive {
AudioSessionHelper.setupSessionActive(false)
}
playback.playButton.setImage(UIImage(named: "ic_play"), forState: .Normal)
playback.updateprogressSliderValue()
case .Finish:
playback.timer?.invalidate()
playback.timer = nil
UIDevice.currentDevice().proximityMonitoringEnabled = false
AudioSessionHelper.setupSessionActive(false)
playback.playButton.setImage(UIImage(named: "ic_play"), forState: .Normal)
playback.progressSlider.value = 1.0
case .Default(let deactive):
playback.timer?.invalidate()
playback.timer = nil
playback.audioPlayer = nil
UIDevice.currentDevice().proximityMonitoringEnabled = false
if deactive {
AudioSessionHelper.setupSessionActive(false)
}
playback.playButton.setImage(UIImage(named: "ic_play"), forState: .Normal)
playback.progressSlider.value = 0.0
}
}
}
lazy var playback = KMPlayback()
// AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
if flag {
recordingHasUpdates = true
playback.playButton.hidden = false
playback.progressSlider.hidden = false
recordButton.setTitle("", forState: .Normal)
let asset = AVURLAsset(URL: recorder.url, options: nil)
let duration = asset.duration
let durationInSeconds = Int(ceil(CMTimeGetSeconds(duration)))
voice.duration = durationInSeconds
}
}
func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) {
assertionFailure("Encode Error occurred! Error: \(error)")
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
playback.state = .Finish
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
assertionFailure("Decode Error occurred! Error: \(error)")
}
func handleInterruption(notification: NSNotification) {
if let userInfo = notification.userInfo {
let interruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as! UInt
if interruptionType == AVAudioSessionInterruptionType.Began.rawValue {
if playback.audioPlayer?.playing == true {
playback.state = .Pause(deactive: true)
}
}
}
}
func audioObjectWillStart(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let audioObject: AnyObject = userInfo[AudioSessionHelper.Constants.Notification.AudioObjectWillStart.UserInfo.AudioObjectKey] {
if playback.audioPlayer != audioObject as? AVAudioPlayer && playback.audioPlayer?.playing == true {
playback.state = .Pause(deactive: false)
}
}
}
}
func proximityStateDidChange(notification: NSNotification) {
if playback.audioPlayer?.playing == true {
if UIDevice.currentDevice().proximityState {
AudioSessionHelper.setupSessionActive(true, catagory: AVAudioSessionCategoryPlayAndRecord)
} else {
AudioSessionHelper.setupSessionActive(true)
}
}
}
}
| mit | b14ff2d0236eb18bcbac63701c728920 | 37.735795 | 185 | 0.606307 | 6.141892 | false | false | false | false |
mac-cain13/R.swift | Sources/RswiftCore/Generators/NibStructGenerator.swift | 1 | 9441 | //
// NibStructGenerator.swift
// R.swift
//
// Created by Mathijs Kadijk on 10-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
private let Ordinals = [
(number: 1, word: "first"),
(number: 2, word: "second"),
(number: 3, word: "third"),
(number: 4, word: "fourth"),
(number: 5, word: "fifth"),
(number: 6, word: "sixth"),
(number: 7, word: "seventh"),
(number: 8, word: "eighth"),
(number: 9, word: "ninth"),
(number: 10, word: "tenth"),
(number: 11, word: "eleventh"),
(number: 12, word: "twelfth"),
(number: 13, word: "thirteenth"),
(number: 14, word: "fourteenth"),
(number: 15, word: "fifteenth"),
(number: 16, word: "sixteenth"),
(number: 17, word: "seventeenth"),
(number: 18, word: "eighteenth"),
(number: 19, word: "nineteenth"),
(number: 20, word: "twentieth"),
]
struct NibStructGenerator: StructGenerator {
private let nibs: [Nib]
private let instantiateParameters = [
Function.Parameter(name: "owner", localName: "ownerOrNil", type: Type._AnyObject.asOptional()),
Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(module: .stdLib, name: SwiftIdentifier(rawValue: "[UINib.OptionsKey : Any]"), optional: true), defaultValue: "nil")
]
init(nibs: [Nib]) {
self.nibs = nibs
}
func generatedStructs(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> StructGenerator.Result {
let structName: SwiftIdentifier = "nib"
let qualifiedName = prefix + structName
let groupedNibs = nibs.grouped(bySwiftIdentifier: { $0.name })
groupedNibs.printWarningsForDuplicatesAndEmpties(source: "xib", result: "file")
let internalStruct = Struct(
availables: [],
comments: [],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: [],
functions: [],
structs: groupedNibs
.uniques
.map { nibStruct(for: $0, at: externalAccessLevel) },
classes: [],
os: ["iOS", "tvOS"]
)
let nibProperties: [Let] = groupedNibs
.uniques
.map { nibVar(for: $0, at: externalAccessLevel, prefix: qualifiedName) }
let nibFunctions: [Function] = groupedNibs
.uniques
.flatMap { nib -> [Function] in
let qualifiedCurrentNibName = qualifiedName + SwiftIdentifier(name: nib.name)
let deprecatedFunction = Function(
availables: ["*, deprecated, message: \"Use UINib(resource: \(qualifiedCurrentNibName)) instead\""],
comments: ["`UINib(name: \"\(nib.name)\", in: bundle)`"],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: nib.name),
generics: nil,
parameters: [
Function.Parameter(name: "_", type: Type._Void, defaultValue: "()")
],
doesThrow: false,
returnType: Type._UINib,
body: "return UIKit.UINib(resource: \(qualifiedCurrentNibName))",
os: ["iOS", "tvOS"]
)
guard let firstViewInfo = nib.rootViews.first else { return [deprecatedFunction] }
let newFunction = Function(
availables: [],
comments: [],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: nib.name),
generics: nil,
parameters: instantiateParameters,
doesThrow: false,
returnType: firstViewInfo.asOptional(),
body: "return \(qualifiedCurrentNibName).instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? \(firstViewInfo)",
os: []
)
return [deprecatedFunction, newFunction]
}
let externalStruct = Struct(
availables: [],
comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(nibProperties.count) nibs."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: nibProperties,
functions: nibFunctions,
structs: [],
classes: [],
os: []
)
return (
externalStruct,
internalStruct
)
}
private func nibVar(for nib: Nib, at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Let {
let structName = SwiftIdentifier(name: "_\(nib.name)")
let qualifiedName = prefix + structName
let structType = Type(module: .host, name: SwiftIdentifier(rawValue: "_\(qualifiedName)"))
return Let(
comments: ["Nib `\(nib.name)`."],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: nib.name),
typeDefinition: .inferred(structType),
value: "\(structType)()"
)
}
private func nibStruct(for nib: Nib, at externalAccessLevel: AccessLevel) -> Struct {
let bundleLet = Let(
comments: [],
accessModifier: externalAccessLevel,
isStatic: false,
name: "bundle",
typeDefinition: .inferred(Type._Bundle),
value: "R.hostingBundle"
)
let nameVar = Let(
comments: [],
accessModifier: externalAccessLevel,
isStatic: false,
name: "name",
typeDefinition: .inferred(Type._String),
value: "\"\(nib.name)\""
)
let viewFuncs = zip(nib.rootViews, Ordinals)
.map { (view: $0.0, ordinal: $0.1) }
.map { viewInfo -> Function in
let viewIndex = viewInfo.ordinal.number - 1
let viewTypeString = viewInfo.view.description
return Function(
availables: [],
comments: [],
accessModifier: externalAccessLevel,
isStatic: false,
name: SwiftIdentifier(name: "\(viewInfo.ordinal.word)View"),
generics: nil,
parameters: instantiateParameters,
doesThrow: false,
returnType: viewInfo.view.asOptional(),
body: "return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[\(viewIndex)] as? \(viewTypeString)",
os: []
)
}
let reuseIdentifierProperties: [Let]
let reuseProtocols: [Type]
let reuseTypealiasses: [Typealias]
if let reusable = nib.reusables.first , nib.rootViews.count == 1 && nib.reusables.count == 1 {
reuseIdentifierProperties = [Let(
comments: [],
accessModifier: externalAccessLevel,
isStatic: false,
name: "identifier",
typeDefinition: .inferred(Type._String),
value: "\"\(reusable.identifier)\""
)]
reuseTypealiasses = [Typealias(accessModifier: externalAccessLevel, alias: "ReusableType", type: reusable.type)]
reuseProtocols = [Type.ReuseIdentifierType]
} else {
reuseIdentifierProperties = []
reuseTypealiasses = []
reuseProtocols = []
}
// Validation
let validateImagesLines = nib.usedImageIdentifiers.uniqueAndSorted()
.map { nameCatalog -> String in
if nameCatalog.isSystemCatalog {
return "if #available(iOS 13.0, *) { if UIKit.UIImage(systemName: \"\(nameCatalog.name)\") == nil { throw Rswift.ValidationError(description: \"[R.swift] System image named '\(nameCatalog.name)' is used in nib '\(nib.name)', but couldn't be loaded.\") } }"
} else {
return "if UIKit.UIImage(named: \"\(nameCatalog.name)\", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: \"[R.swift] Image named '\(nameCatalog.name)' is used in nib '\(nib.name)', but couldn't be loaded.\") }"
}
}
let validateColorLines = nib.usedColorResources.uniqueAndSorted()
.compactMap { nameCatalog -> String? in
if nameCatalog.isSystemCatalog { return nil }
return "if UIKit.UIColor(named: \"\(nameCatalog.name)\", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: \"[R.swift] Color named '\(nameCatalog.name)' is used in nib '\(nib.name)', but couldn't be loaded.\") }"
}
let validateColorLinesWithAvailableIf = ["if #available(iOS 11.0, tvOS 11.0, *) {"] +
validateColorLines.map { $0.indent(with: " ") } +
["}"]
var validateFunctions: [Function] = []
var validateImplements: [Type] = []
if validateImagesLines.count > 0 {
let validateFunction = Function(
availables: [],
comments: [],
accessModifier: externalAccessLevel,
isStatic: true,
name: "validate",
generics: nil,
parameters: [],
doesThrow: true,
returnType: Type._Void,
body: (validateImagesLines + validateColorLinesWithAvailableIf).joined(separator: "\n"),
os: []
)
validateFunctions.append(validateFunction)
validateImplements.append(Type.Validatable)
}
let sanitizedName = SwiftIdentifier(name: nib.name, lowercaseStartingCharacters: false)
return Struct(
availables: [],
comments: [],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: SwiftIdentifier(name: "_\(sanitizedName)")),
implements: ([Type.NibResourceType] + reuseProtocols + validateImplements).map(TypePrinter.init),
typealiasses: reuseTypealiasses,
properties: [bundleLet, nameVar] + reuseIdentifierProperties,
functions: viewFuncs + validateFunctions,
structs: [],
classes: [],
os: []
)
}
}
| mit | 98bff1bf10a861c766a9c5251f721036 | 35.451737 | 266 | 0.626523 | 4.336702 | false | false | false | false |
blackspotbear/MMDViewer | MMDViewer/MMDView.swift | 1 | 7443 | import Foundation
import UIKit
import GLKit
import Metal
let InitialCameraPosition = GLKVector3Make(0, 10, 20)
class MMDView: MetalView {
var pmxUpdater: PMXUpdater?
private var cameraUpdater = CameraUpdater(rot: GLKQuaternionIdentity, pos: InitialCameraPosition)
private var renderer = BasicRenderer()
private var traverser: Traverser
private var root = Node()
private var timer: CADisplayLink!
private var lastFrameTimestamp: CFTimeInterval = 0.0
private var pmx: PMX!
private var vmd: VMD!
private var miku: PMXObject!
private var layerSizeDidUpdate = false
override init(frame: CGRect) {
traverser = Traverser(renderer: renderer)
super.init(frame: frame)
renderer.configure(device!)
initCommon()
}
required init?(coder aDecoder: NSCoder) {
traverser = Traverser(renderer: renderer)
super.init(coder: aDecoder)
renderer.configure(device!)
initCommon()
}
// private panRecognizer: UIPanGestureRecognizer
private func initCommon() {
isOpaque = true
backgroundColor = nil
let tapg = UITapGestureRecognizer(target: self, action: #selector(MMDView.handleTap(_:)))
tapg.numberOfTapsRequired = 2
addGestureRecognizer(tapg)
addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(MMDView.handlePan(_:))))
addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(MMDView.handlePinch(_:))))
addGestureRecognizer(UIRotationGestureRecognizer(target: self, action: #selector(MMDView.handleRotate(_:))))
}
// MARK: Override UIView
override var contentScaleFactor: CGFloat {
set(v) {
super.contentScaleFactor = v
layerSizeDidUpdate = true
}
get {
return super.contentScaleFactor
}
}
override func layoutSubviews() {
super.layoutSubviews()
layerSizeDidUpdate = true
}
override func didMoveToWindow() {
super.didMoveToWindow()
contentScaleFactor = self.window!.screen.nativeScale
// Load resource
pmx = LoadPMD("data/mmd/Alicia_solid")
vmd = LoadVMD("data/vmd/2分ループステップ17")
miku = PMXObject(device: device!, pmx: pmx!, vmd: vmd)
renderer.setEndHandler({ [weak self] (_ renderer: Renderer) in
if let drawable = self?.currentDrawable {
if let commandBuffer = renderer.commandBuffer {
commandBuffer.present(drawable)
commandBuffer.commit()
}
self?.releaseCurrentDrawable()
}
})
let colorFormat = setupSceneGraph()
if let metalLayer = self.metalLayer {
metalLayer.pixelFormat = colorFormat
metalLayer.framebufferOnly = true
}
// Set up animation loop
timer = CADisplayLink(target: self, selector: #selector(MMDView.mainLoop(_:)))
if #available(iOS 10.0, *) {
timer.preferredFramesPerSecond = 30
} else {
timer.frameInterval = 2
}
timer.add(to: RunLoop.main, forMode: RunLoop.Mode.default)
}
#if true // forward rendering
private func setupSceneGraph() -> MTLPixelFormat {
let node = Node()
pmxUpdater = PMXUpdater(pmxObj: miku)
node.updater = pmxUpdater
node.drawer = PMXDrawer(pmxObj: miku, device: device!)
node.pass = ForwardRenderPass(view: self)
root.updater = cameraUpdater
root.children.append(node)
return .bgra8Unorm
}
#else // deferred rendering
private func setupSceneGraph() -> MTLPixelFormat {
let shadowNode = Node()
let shadowPass = ShadowPass(device: device!)
shadowNode.pass = shadowPass
shadowNode.drawer = PMXShadowDrawer(pmxObj: miku)
let gbufferNode = Node()
let gbufferPass = GBufferPass(view: self)
gbufferNode.pass = gbufferPass
let pmxDrawNode = Node()
pmxDrawNode.drawer = PMXGBufferDrawer(
device: device!,
pmxObj: miku,
shadowTexture: shadowPass.shadowTexture)
let pointLightNode = Node()
pointLightNode.drawer = PointLightDrawer(
device: device!,
lightCount: 1)
gbufferNode.children.append(pmxDrawNode)
gbufferNode.children.append(pointLightNode)
let wireframeNode = Node()
let wireframePass = WireframePass(device: device!)
wireframeNode.pass = wireframePass
wireframeNode.drawer = WireFrameDrawer(device: device!)
let node = Node()
pmxUpdater = PMXUpdater(pmxObj: miku)
node.updater = pmxUpdater
node.children.append(shadowNode)
node.children.append(gbufferNode)
node.children.append(wireframeNode)
root.updater = cameraUpdater
root.children.append(node)
return .bgra8Unorm
}
#endif
// MARK: UI Event Handlers
@objc func handlePan(_ recognize: UIPanGestureRecognizer) {
let t = recognize.translation(in: self)
let dx = Float(t.x)
let dy = Float(t.y)
if dx == 0 && dy == 0 {
return
}
if recognize.numberOfTouches == 1 {
let len = sqrt(dx * dx + dy * dy)
let rad = len / 500 * Float.pi
cameraUpdater.rot = cameraUpdater.rot.mul(
GLKQuaternionMakeWithAngleAndVector3Axis(rad, GLKVector3Make(dy / len, dx / len, 0)))
} else if recognize.numberOfTouches == 2 {
let dX = cameraUpdater.viewMatrix.ixAxis().mul(-dx / 10)
let dY = cameraUpdater.viewMatrix.iyAxis().mul(dy / 10)
cameraUpdater.pos = cameraUpdater.pos.add(dX).add(dY)
}
recognize.setTranslation(CGPoint(x: 0, y: 0), in: self)
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
cameraUpdater.rot = GLKQuaternionIdentity
cameraUpdater.pos = InitialCameraPosition
}
}
@objc func handlePinch(_ recognize: UIPinchGestureRecognizer) {
let v = Float(recognize.velocity)
let dz = -v * 0.5
let dZ = cameraUpdater.viewMatrix.izAxis().mul(dz)
cameraUpdater.pos = cameraUpdater.pos.add(dZ)
recognize.scale = 1
}
@objc func handleRotate(_ recognize: UIRotationGestureRecognizer) {
let v = Float(recognize.velocity)
let rad = v * 0.05
cameraUpdater.rot = cameraUpdater.rot.mul(
GLKQuaternionMakeWithAngleAndVector3Axis(rad, GLKVector3Make(0, 0, 1)))
recognize.rotation = 0
}
// MARK: Loop
@objc func mainLoop(_ displayLink: CADisplayLink) {
if lastFrameTimestamp == 0.0 {
lastFrameTimestamp = displayLink.timestamp
}
let elapsed = displayLink.timestamp - lastFrameTimestamp
lastFrameTimestamp = displayLink.timestamp
if layerSizeDidUpdate {
self.drawableSize.width = self.bounds.size.width * contentScaleFactor
self.drawableSize.height = self.bounds.size.height * contentScaleFactor
renderer.reshape(self.bounds)
layerSizeDidUpdate = false
}
traverser.update(elapsed, node: root)
traverser.draw(root)
}
}
| mit | 243cd4c8d339e79ac38d80c917a9481c | 30.320675 | 116 | 0.624545 | 4.758333 | false | false | false | false |
yasuoza/graphPON | graphPON WatchKit Extension/Interfaces/DailyChartInterfaceController.swift | 1 | 2856 | import WatchKit
import Foundation
import GraphPONDataKit
class DailyChartInterfaceController: WKInterfaceController {
@IBOutlet weak var durationLabel: WKInterfaceLabel!
@IBOutlet weak var chartValueLabel: WKInterfaceLabel!
@IBOutlet weak var chartImageView: WKInterfaceImage!
@IBOutlet weak var durationControlButtonGroup: WKInterfaceGroup!
@IBOutlet weak var inThisMonthButton: WKInterfaceButton!
@IBOutlet weak var last30DaysButton: WKInterfaceButton!
private var serviceCode: String!
private var duration: HdoService.Duration = .InThisMonth
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
NSNotificationCenter.defaultCenter().addObserverForName(
PacketInfoManager.LatestPacketLogsDidFetchNotification,
object: nil, queue: nil, usingBlock: { _ in
if let serviceCode = Context.sharedContext.serviceCode {
self.serviceCode = serviceCode
self.reloadChartData()
}
})
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func willActivate() {
super.willActivate()
if self.serviceCode != Context.sharedContext.serviceCode {
self.serviceCode = Context.sharedContext.serviceCode
self.reloadChartData()
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: - Actions
@IBAction func InThisMonthButtonAction() {
self.inThisMonthButton.setBackgroundColor(UIColor.blackColor().colorWithAlphaComponent(0.8))
self.last30DaysButton.setBackgroundColor(UIColor.clearColor())
self.duration = .InThisMonth
self.reloadChartData()
}
@IBAction func last30DaysButtonAction() {
self.inThisMonthButton.setBackgroundColor(UIColor.clearColor())
self.last30DaysButton.setBackgroundColor(UIColor.blackColor().colorWithAlphaComponent(0.8))
self.duration = .InLast30Days
self.reloadChartData()
}
@IBAction func showSummaryChartMenuAction() {
self.presentControllerWithName("ServiceListInterfaceController", context: nil)
self.reloadChartData()
}
// MARK: - Update views
private func reloadChartData() {
let frame = CGRectMake(0, 0, contentFrame.width, contentFrame.height / 2)
let scene = DailyChartScene(serviceCode: serviceCode, duration: duration)
let image = scene.drawImage(frame: frame)
self.chartImageView.setImage(image)
self.chartValueLabel.setText(scene.valueText)
self.durationLabel.setText(scene.durationText)
self.setTitle(Context.sharedContext.serviceNickname)
}
}
| mit | ec63d2acf50ed0dfde99765dd3beb7a4 | 33.829268 | 100 | 0.696779 | 5.450382 | false | false | false | false |
tkremenek/swift | test/TBD/move_to_extension_comove.swift | 19 | 1490 | // REQUIRES: OS=macosx
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck %s -emit-tbd -emit-tbd-path %t/before_move.tbd -D BEFORE_MOVE -module-name Foo -enable-library-evolution -emit-sil -o %t/before_move.sil
// RUN: %FileCheck %s --check-prefix=CHECK-TBD < %t/before_move.tbd
// RUN: %FileCheck %s --check-prefix=CHECK-SIL < %t/before_move.sil
// RUN: %target-swift-frontend %s -emit-module -emit-module-path %t/FooCore.swiftmodule -D AFTER_MOVE_FOO_CORE -module-name FooCore -enable-library-evolution -emit-tbd -emit-tbd-path %t/after_move.tbd -emit-sil -o %t/after_move.sil
// RUN: %FileCheck %s --check-prefix=CHECK-TBD < %t/after_move.tbd
// RUN: %FileCheck %s --check-prefix=CHECK-SIL < %t/after_move.sil
// CHECK-TBD: '_$s3Foo4DateC03SubB0V4yearAESi_tcfC'
// CHECK-TBD: '_$s3Foo4DateC03SubB0VMn'
// CHECK-SIL: sil [available 10.7] @$s3Foo4DateC03SubB0V4yearAESi_tcfC : $@convention(method) (Int, @thin Date.SubDate.Type) -> @out Date.SubDate
#if BEFORE_MOVE
@available(OSX 10.7, *)
public class Date {
public static func getCurrentYear() -> Int { return 2020 }
}
@available(OSX 10.7, *)
extension Date {
public struct SubDate {
public init(year: Int) {}
}
}
#endif
#if AFTER_MOVE_FOO_CORE
@available(OSX 10.7, *)
@_originallyDefinedIn(module: "Foo", OSX 10.9)
public class Date {}
@available(OSX 10.7, *)
@_originallyDefinedIn(module: "Foo", OSX 10.9)
extension Date {
public struct SubDate {
public init(year: Int) {}
}
}
#endif
| apache-2.0 | 2fe2e9660413752e5e763c36f5e3448a | 30.041667 | 231 | 0.695973 | 2.785047 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/BusinessLayer/Services/Rates/RateService.swift | 1 | 1575 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Foundation
protocol RateSource {
func fiatString(for amount: Currency, in iso: String) -> String
func rawAmount(for amount: Currency, in iso: String) -> Decimal
func fiatLabelString(currency: Currency, selectedCurrency: String) -> String
}
class RateService: RateSource {
let rateRateRepository: RateRepository
init(rateRepository: RateRepository) {
self.rateRateRepository = rateRepository
}
// MARK: Privates
private func rate(from: String, to: String) -> Rate? {
return rateRateRepository.rates.first(where: { $0.from == from && $0.to == to })
}
func fiatString(for amount: Currency, in iso: String) -> String {
guard let rate = rate(from: amount.iso, to: iso) else {
return FiatCurrencyFactory.amount(currency: amount, iso: iso, rate: 0)
}
return FiatCurrencyFactory.amount(currency: amount, iso: iso, rate: rate.value)
}
func rawAmount(for amount: Currency, in iso: String) -> Decimal {
guard let rate = rate(from: amount.iso, to: iso) else {
return 0
}
return amount.value * Decimal(rate.value)
}
func fiatLabelString(currency: Currency, selectedCurrency: String) -> String {
let description = Localized.balanceLabel(currency.iso.uppercased(), currency.name)
guard selectedCurrency != currency.iso else {
return description
}
return rawAmount(for: currency, in: selectedCurrency) == 0 ?
description : fiatString(for: currency, in: selectedCurrency)
}
}
| gpl-3.0 | 6cc44ea5a1ce5a57971e31333ef69f8b | 31.791667 | 86 | 0.697586 | 4.088312 | false | false | false | false |
addisflava/iSub | Classes/CustomUITableView.swift | 2 | 10591 | //
// CustomUITableView.swift
// iSub
//
// Created by Benjamin Baron on 12/20/14.
// Copyright (c) 2014 Ben Baron. All rights reserved.
//
import Foundation
import UIKit
public class CustomUITableView: UITableView {
let HorizSwipeDragMin: Double = 3.0
let VertSwipeDragMax: Double = 80.0
let CellEnableDelay: NSTimeInterval = 1.0
let TapAndHoldDelay: NSTimeInterval = 0.25
let _settings = SavedSettings.sharedInstance()
var _startTouchPosition: CGPoint?
var _swiped: Bool = false
var _cellShowingOverlay: UITableViewCell?
var _tapAndHoldCell: UITableViewCell?
var _lastDeleteToggle: NSDate = NSDate()
var _tapAndHoldTimer: NSTimer?
private func _setup() {
self.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
self.sectionIndexBackgroundColor = UIColor.clearColor()
}
public override init() {
super.init()
self._setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self._setup()
}
public override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self._setup()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
// MARK: - Touch Gestures Interception -
private func _hideAllOverlays(cellToSkip: UITableViewCell?) {
for cell in self.visibleCells() as [UITableViewCell] {
if let customCell: CustomUITableViewCell = cell as? CustomUITableViewCell {
if customCell != cellToSkip {
customCell.hideOverlay()
}
}
}
}
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
// Don't try anything when the tableview is moving and do not catch as a swipe if touch is far right (potential index control)
if !self.decelerating && point.x < 290 {
// Find the cell
if let indexPath = self.indexPathForRowAtPoint(point) {
if let cell = self.cellForRowAtIndexPath(indexPath) {
// TODO: Move multi delete touch handling to CustomUITableViewCell
// Handle multi delete touching
if self.editing && point.x < 40.0 && NSDate().timeIntervalSinceDate(self._lastDeleteToggle) > 0.25 {
self._lastDeleteToggle = NSDate()
if let customCell: CustomUITableViewCell = cell as? CustomUITableViewCell {
customCell.toggleDelete()
}
}
// Remove overlays
if !self._swiped {
self._hideAllOverlays(cell)
if let customCell: CustomUITableViewCell = cell as? CustomUITableViewCell {
if customCell.overlayShowing {
EX2Dispatch.runInMainThreadAfterDelay(1.0, {
customCell.hideOverlay()
})
}
}
}
}
}
}
return super.hitTest(point, withEvent: event)
}
public override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
return true
}
public override func touchesShouldBegin(touches: NSSet!, withEvent event: UIEvent!, inContentView view: UIView!) -> Bool {
return true
}
// MARK: - Touch gestures for custom cell view -
private func _disableCellsTemporarily() {
self.allowsSelection = false
EX2Dispatch.runInMainThreadAfterDelay(CellEnableDelay, {
self.allowsSelection = true
})
}
private func _isTouchHorizontal(touch: UITouch) -> Bool
{
let currentTouchPosition: CGPoint = touch.locationInView(self)
if let startTouchPosition = self._startTouchPosition? {
let xMovement = fabs(Double(startTouchPosition.x) - Double(currentTouchPosition.x))
let yMovement = fabs(Double(startTouchPosition.y) - Double(currentTouchPosition.y))
return xMovement > yMovement
}
return false
}
private func _lookForSwipeGestureInTouches(touches: NSSet, event: UIEvent)
{
var cell: UITableViewCell? = nil
let currentTouchPosition: CGPoint? = touches.anyObject()?.locationInView(self)
if currentTouchPosition != nil {
let indexPath: NSIndexPath? = self.indexPathForRowAtPoint(currentTouchPosition!)
if indexPath != nil {
cell = self.cellForRowAtIndexPath(indexPath!)
}
}
if (!self._swiped && cell != nil)
{
// Check if this is a full swipe
if let startTouchPosition: CGPoint = self._startTouchPosition? {
let startTouchX = Double(startTouchPosition.x)
let startTouchY = Double(startTouchPosition.y)
let currentTouchX = Double(currentTouchPosition!.x)
let currentTouchY = Double(currentTouchPosition!.y)
let xDiff = fabs(startTouchX - currentTouchX)
let yDiff = fabs(startTouchY - currentTouchY)
if xDiff >= HorizSwipeDragMin && yDiff <= VertSwipeDragMax {
self._swiped = true
self.scrollEnabled = false
// Temporarily disable the cells so we don't get accidental selections
self._disableCellsTemporarily()
// Hide any open overlays
self._hideAllOverlays(nil)
// Detect the direction
if startTouchX < currentTouchX {
// Right swipe
if _settings.isSwipeEnabled && !IS_IPAD() {
if let customCell = cell as? CustomUITableViewCell {
customCell.showOverlay()
}
self._cellShowingOverlay = cell
}
} else {
// Left Swipe
if let customCell = cell as? CustomUITableViewCell {
customCell.scrollLabels()
}
}
} else {
// Process a non-swipe event.
}
}
}
}
public func _tapAndHoldFired() {
self._swiped = true
if let customCell: CustomUITableViewCell = self._tapAndHoldCell as? CustomUITableViewCell {
customCell.showOverlay()
}
self._cellShowingOverlay = self._tapAndHoldCell
}
private func _cancelTapAndHold() {
_tapAndHoldTimer?.invalidate();
_tapAndHoldTimer = nil
}
public override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.allowsSelection = false
self.scrollEnabled = true
// Handle swipe
self._startTouchPosition = touches.anyObject()!.locationInView(self)
self._swiped = false
self._cellShowingOverlay = nil
// Handle tap and hold
if (_settings.isTapAndHoldEnabled) {
let indexPath = self.indexPathForRowAtPoint(self._startTouchPosition!)
if let indexPath = indexPath? {
self._tapAndHoldCell = self.cellForRowAtIndexPath(indexPath)
_tapAndHoldTimer = NSTimer.scheduledTimerWithTimeInterval(TapAndHoldDelay, target: self, selector: "_tapAndHoldFired", userInfo: nil, repeats: false);
}
}
super.touchesBegan(touches, withEvent: event)
}
public override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
// Cancel the tap and hold if user moves finger
self._cancelTapAndHold()
// Check for swipe
if self._isTouchHorizontal(touches.anyObject()! as UITouch) {
self._lookForSwipeGestureInTouches(touches, event: event)
}
super.touchesMoved(touches, withEvent: event)
}
public override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
self.allowsSelection = true
self.scrollEnabled = true
self._cancelTapAndHold()
if self._swiped {
// Enable the buttons if the overlay is showing
if let customCell: CustomUITableViewCell = self._cellShowingOverlay as? CustomUITableViewCell {
customCell.overlayView?.enableButtons();
}
} else {
// Select the cell if this was a touch not a swipe or tap and hold
let currentTouchPosition = touches.anyObject()!.locationInView(self)
if (self.editing && Float(currentTouchPosition.x) > 40.0) || !self.editing {
let indexPath: NSIndexPath? = self.indexPathForRowAtPoint(currentTouchPosition)
if indexPath != nil {
self.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
if let delegate: UITableViewDelegate = self.delegate? {
delegate.tableView?(self, didSelectRowAtIndexPath: indexPath!)
}
}
}
}
self._swiped = false
super.touchesEnded(touches, withEvent: event)
}
public override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
self._cancelTapAndHold()
self.allowsSelection = true
self.scrollEnabled = true
self._swiped = false
if let customCell: CustomUITableViewCell = self._cellShowingOverlay as? CustomUITableViewCell {
customCell.overlayView?.enableButtons();
}
super.touchesCancelled(touches, withEvent: event)
}
}
| gpl-3.0 | 0216dfdb76c448d1fb6709fe2ae857a0 | 36.424028 | 166 | 0.547163 | 5.956693 | false | false | false | false |
guidomb/Portal | Example/Views/ModalScreen.swift | 1 | 2160 | //
// ModalScreen.swift
// PortalExample
//
// Created by Guido Marucci Blas on 6/10/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Portal
enum ModalScreen {
typealias Action = Portal.Action<Route, Message>
typealias View = Portal.View<Route, Message, Navigator>
static func view(counter: UInt) -> View {
let modalButtonStyleSheet = buttonStyleSheet { base, button in
base.backgroundColor = .green
button.textColor = .white
}
return View(
navigator: .modal,
root: .stack(ExampleApplication.navigationBar(title: "Modal")),
component: container(
children: [
label(text: "Modal screen"),
button(
text: "Close and present detail",
onTap: .dismissNavigator(thenSend: .navigate(to: .detail)),
style: modalButtonStyleSheet
),
button(
text: "Close",
onTap: .dismissNavigator(thenSend: .none),
style: modalButtonStyleSheet
),
label(text: "Counter \(counter)"),
button(
text: "Increment!",
onTap: .sendMessage(.increment),
style: modalButtonStyleSheet
),
button(
text: "Present modal landscape",
onTap: .navigate(to: .landscape),
style: buttonStyleSheet { base, button in
base.backgroundColor = .green
button.textColor = .white
}
),
],
style: styleSheet() {
$0.backgroundColor = .red
},
layout: layout() {
$0.flex = flex() {
$0.grow = .one
}
}
)
)
}
}
| mit | 93e728808eb1a47577dafe5b1565e502 | 32.734375 | 83 | 0.428902 | 5.757333 | false | false | false | false |
omalovichko/MAGLoader | MAGLoader/ViewController.swift | 1 | 1487 | //
// ViewController.swift
// MAGLoader
//
// Created by MAG on 9/16/15.
// Copyright (c) 2015 MAG. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, LoadManagerDelegate {
@IBOutlet weak var tableView: UITableView!
var images = [UIImage]()
var loadManager = LoadManager()
override func viewDidLoad() {
super.viewDidLoad()
loadManager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loadImages(sender: UIButton) {
loadManager.loadItems()
}
// MARK: TableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as! ImageCell
cell.imageHolder?.image = images[indexPath.row]
return cell
}
// MARK: LoadManager
func itemDidLoad(data: NSData?) {
if let imageData = data {
if let image = UIImage(data: imageData) {
images.append(image)
tableView.reloadData()
}
}
}
}
| mit | 8b47edc224d376be4719723f5a14c809 | 23.783333 | 114 | 0.62542 | 5.217544 | false | false | false | false |
jpsim/SourceKitten | Source/SourceKittenFramework/Request.swift | 1 | 21365 | import Dispatch
import Foundation
#if SWIFT_PACKAGE
import SourceKit
#endif
// swiftlint:disable file_length
// This file could easily be split up
public protocol SourceKitRepresentable {
func isEqualTo(_ rhs: SourceKitRepresentable) -> Bool
}
extension Array: SourceKitRepresentable {}
extension Dictionary: SourceKitRepresentable {}
extension String: SourceKitRepresentable {}
extension Int64: SourceKitRepresentable {}
extension Bool: SourceKitRepresentable {}
extension Data: SourceKitRepresentable {}
extension SourceKitRepresentable {
public func isEqualTo(_ rhs: SourceKitRepresentable) -> Bool {
switch self {
case let lhs as [SourceKitRepresentable]:
for (idx, value) in lhs.enumerated() {
if let rhs = rhs as? [SourceKitRepresentable], rhs[idx].isEqualTo(value) {
continue
}
return false
}
return true
case let lhs as [String: SourceKitRepresentable]:
for (key, value) in lhs {
if let rhs = rhs as? [String: SourceKitRepresentable],
let rhsValue = rhs[key], rhsValue.isEqualTo(value) {
continue
}
return false
}
return true
case let lhs as String:
return lhs == rhs as? String
case let lhs as Int64:
return lhs == rhs as? Int64
case let lhs as Bool:
return lhs == rhs as? Bool
default:
fatalError("Should never happen because we've checked all SourceKitRepresentable types")
}
}
}
// swiftlint:disable:next cyclomatic_complexity
private func fromSourceKit(_ sourcekitObject: sourcekitd_variant_t) -> SourceKitRepresentable? {
switch sourcekitd_variant_get_type(sourcekitObject) {
case SOURCEKITD_VARIANT_TYPE_ARRAY:
var array = [SourceKitRepresentable]()
_ = withUnsafeMutablePointer(to: &array) { arrayPtr in
sourcekitd_variant_array_apply_f(sourcekitObject, { index, value, context in
if let value = fromSourceKit(value), let context = context {
let localArray = context.assumingMemoryBound(to: [SourceKitRepresentable].self)
localArray.pointee.insert(value, at: Int(index))
}
return true
}, arrayPtr)
}
return array
case SOURCEKITD_VARIANT_TYPE_DICTIONARY:
var dict = [String: SourceKitRepresentable]()
_ = withUnsafeMutablePointer(to: &dict) { dictPtr in
sourcekitd_variant_dictionary_apply_f(sourcekitObject, { key, value, context in
if let key = String(sourceKitUID: key!), let value = fromSourceKit(value), let context = context {
let localDict = context.assumingMemoryBound(to: [String: SourceKitRepresentable].self)
localDict.pointee[key] = value
}
return true
}, dictPtr)
}
return dict
case SOURCEKITD_VARIANT_TYPE_STRING:
return String(cString: sourcekitd_variant_string_get_ptr(sourcekitObject)!)
case SOURCEKITD_VARIANT_TYPE_INT64:
return sourcekitd_variant_int64_get_value(sourcekitObject)
case SOURCEKITD_VARIANT_TYPE_BOOL:
return sourcekitd_variant_bool_get_value(sourcekitObject)
case SOURCEKITD_VARIANT_TYPE_UID:
return String(sourceKitUID: sourcekitd_variant_uid_get_value(sourcekitObject)!)
case SOURCEKITD_VARIANT_TYPE_NULL:
return nil
case SOURCEKITD_VARIANT_TYPE_DATA:
return sourcekitd_variant_data_get_ptr(sourcekitObject).map { ptr in
return Data(bytes: ptr, count: sourcekitd_variant_data_get_size(sourcekitObject))
}
default:
fatalError("Should never happen because we've checked all SourceKitRepresentable types")
}
}
/// Lazily and singly computed Void constants to initialize SourceKit once per session.
private let initializeSourceKit: Void = {
sourcekitd_initialize()
}()
private let initializeSourceKitFailable: Void = {
initializeSourceKit
sourcekitd_set_notification_handler { response in
if !sourcekitd_response_is_error(response!) {
fflush(stdout)
fputs("sourcekitten: connection to SourceKitService restored!\n", stderr)
sourceKitWaitingRestoredSemaphore.signal()
}
sourcekitd_response_dispose(response!)
}
}()
/// dispatch_semaphore_t used when waiting for sourcekitd to be restored.
private var sourceKitWaitingRestoredSemaphore = DispatchSemaphore(value: 0)
private extension String {
/**
Cache SourceKit requests for strings from UIDs
- returns: Cached UID string if available, nil otherwise.
*/
init?(sourceKitUID: sourcekitd_uid_t) {
let bytes = sourcekitd_uid_get_string_ptr(sourceKitUID)
self = String(cString: bytes!)
return
}
}
/// Represents a SourceKit request.
public enum Request {
/// An `editor.open` request for the given File.
case editorOpen(file: File)
/// A `cursorinfo` request for an offset in the given file, using the `arguments` given.
case cursorInfo(file: String, offset: ByteCount, arguments: [String])
/// A `cursorinfo` request for a USR in the given file, using the `arguments` given.
case cursorInfoUSR(file: String, usr: String, arguments: [String], cancelOnSubsequentRequest: Bool)
/// A custom request by passing in the `SourceKitObject` directly.
case customRequest(request: SourceKitObject)
/// A request generated by sourcekit using the yaml representation.
case yamlRequest(yaml: String)
/// A `codecomplete` request by passing in the file name, contents, offset
/// for which to generate code completion options and array of compiler arguments.
case codeCompletionRequest(file: String, contents: String, offset: ByteCount, arguments: [String])
/// ObjC Swift Interface
case interface(file: String, uuid: String, arguments: [String])
/// Find USR
case findUSR(file: String, usr: String)
/// Index
case index(file: String, arguments: [String])
/// Format
case format(file: String, line: Int64, useTabs: Bool, indentWidth: Int64)
/// ReplaceText
case replaceText(file: String, range: ByteRange, sourceText: String)
/// A documentation request for the given source text.
case docInfo(text: String, arguments: [String])
/// A documentation request for the given module.
case moduleInfo(module: String, arguments: [String])
/// Gets the serialized representation of the file's SwiftSyntax tree. JSON string if `byteTree` is false,
/// binary data otherwise.
case syntaxTree(file: File, byteTree: Bool)
/// Get the version triple of the compiler that SourceKit is using
case compilerVersion
fileprivate var sourcekitObject: SourceKitObject {
switch self {
case let .editorOpen(file):
if let path = file.path {
return [
"key.request": UID("source.request.editor.open"),
"key.name": path,
"key.sourcefile": path
]
} else {
return [
"key.request": UID("source.request.editor.open"),
"key.name": String(abs(file.contents.hash)),
"key.sourcetext": file.contents
]
}
case let .cursorInfo(file, offset, arguments):
return [
"key.request": UID("source.request.cursorinfo"),
"key.name": file,
"key.sourcefile": file,
"key.offset": Int64(offset.value),
"key.compilerargs": arguments
]
case let .cursorInfoUSR(file, usr, arguments, cancelOnSubsequentRequest):
return [
"key.request": UID("source.request.cursorinfo"),
"key.sourcefile": file,
"key.usr": usr,
"key.compilerargs": arguments,
"key.cancel_on_subsequent_request": cancelOnSubsequentRequest ? 1 : 0
]
case let .customRequest(request):
return request
case let .yamlRequest(yaml):
return SourceKitObject(yaml: yaml)
case let .codeCompletionRequest(file, contents, offset, arguments):
return [
"key.request": UID("source.request.codecomplete"),
"key.name": file,
"key.sourcefile": file,
"key.sourcetext": contents,
"key.offset": Int64(offset.value),
"key.compilerargs": arguments
]
case .interface(let file, let uuid, var arguments):
if !arguments.contains("-x") {
arguments.append(contentsOf: ["-x", "objective-c"])
}
if !arguments.contains("-isysroot") {
arguments.append(contentsOf: ["-isysroot", sdkPath()])
}
return [
"key.request": UID("source.request.editor.open.interface.header"),
"key.name": uuid,
"key.filepath": file,
"key.compilerargs": [file] + arguments
]
case let .findUSR(file, usr):
return [
"key.request": UID("source.request.editor.find_usr"),
"key.usr": usr,
"key.sourcefile": file
]
case let .index(file, arguments):
return [
"key.request": UID("source.request.indexsource"),
"key.sourcefile": file,
"key.compilerargs": arguments
]
case let .format(file, line, useTabs, indentWidth):
return [
"key.request": UID("source.request.editor.formattext"),
"key.name": file,
"key.line": line,
"key.editor.format.options": [
"key.editor.format.indentwidth": indentWidth,
"key.editor.format.tabwidth": indentWidth,
"key.editor.format.usetabs": useTabs ? 1 : 0
]
]
case let .replaceText(file, range, sourceText):
return [
"key.request": UID("source.request.editor.replacetext"),
"key.name": file,
"key.offset": Int64(range.location.value),
"key.length": Int64(range.length.value),
"key.sourcetext": sourceText
]
case let .docInfo(text, arguments):
return [
"key.request": UID("source.request.docinfo"),
"key.name": NSUUID().uuidString,
"key.compilerargs": arguments,
"key.sourcetext": text
]
case let .moduleInfo(module, arguments):
return [
"key.request": UID("source.request.docinfo"),
"key.name": NSUUID().uuidString,
"key.compilerargs": arguments,
"key.modulename": module
]
case let .syntaxTree(file, byteTree):
let serializationFormat = byteTree ? "bytetree" : "json"
if let path = file.path {
return [
"key.request": UID("source.request.editor.open"),
"key.name": path,
"key.sourcefile": path,
"key.enablesyntaxmap": 0,
"key.enablesubstructure": 0,
"key.enablesyntaxtree": 1,
"key.syntactic_only": 1,
"key.syntaxtreetransfermode": UID("source.syntaxtree.transfer.full"),
"key.syntax_tree_serialization_format":
UID("source.syntaxtree.serialization.format.\(serializationFormat)")
]
} else {
return [
"key.request": UID("source.request.editor.open"),
"key.name": String(abs(file.contents.hash)),
"key.sourcetext": file.contents,
"key.enablesyntaxmap": 0,
"key.enablesubstructure": 0,
"key.enablesyntaxtree": 1,
"key.syntactic_only": 1,
"key.syntaxtreetransfermode": UID("source.syntaxtree.transfer.full"),
"key.syntax_tree_serialization_format":
UID("source.syntaxtree.serialization.format.\(serializationFormat)")
]
}
case .compilerVersion:
return [ "key.request": UID("source.request.compiler_version") ]
}
}
/**
Create a Request.CursorInfo.sourcekitObject() from a file path and compiler arguments.
- parameter filePath: Path of the file to create request.
- parameter arguments: Compiler arguments.
- returns: sourcekitd_object_t representation of the Request, if successful.
*/
internal static func cursorInfoRequest(filePath: String?, arguments: [String]) -> SourceKitObject? {
if let path = filePath {
return Request.cursorInfo(file: path, offset: 0, arguments: arguments).sourcekitObject
}
return nil
}
/**
Send a Request.CursorInfo by updating its offset. Returns SourceKit response if successful.
- parameter cursorInfoRequest: `SourceKitObject` representation of Request.CursorInfo
- parameter offset: Offset to update request.
- returns: SourceKit response if successful.
*/
internal static func send(cursorInfoRequest: SourceKitObject, atOffset offset: ByteCount) -> [String: SourceKitRepresentable]? {
if offset == 0 {
return nil
}
cursorInfoRequest.updateValue(Int64(offset.value), forKey: SwiftDocKey.offset)
return try? Request.customRequest(request: cursorInfoRequest).send()
}
/**
Sends the request to SourceKit and return the response as an [String: SourceKitRepresentable].
- returns: SourceKit output as a dictionary.
- throws: Request.Error on fail ()
*/
public func send() throws -> [String: SourceKitRepresentable] {
initializeSourceKitFailable
let response = sourcekitObject.sendSync()
defer { sourcekitd_response_dispose(response!) }
if sourcekitd_response_is_error(response!) {
let error = Request.Error(response: response!)
if case .connectionInterrupted = error {
_ = sourceKitWaitingRestoredSemaphore.wait(timeout: DispatchTime.now() + 10)
}
throw error
}
return fromSourceKit(sourcekitd_response_get_value(response!)) as! [String: SourceKitRepresentable]
}
/// A enum representation of SOURCEKITD_ERROR_*
public enum Error: Swift.Error, CustomStringConvertible {
case connectionInterrupted(String?)
case invalid(String?)
case failed(String?)
case cancelled(String?)
case unknown(String?)
/// A textual representation of `self`.
public var description: String {
return getDescription() ?? "no description"
}
private func getDescription() -> String? {
switch self {
case let .connectionInterrupted(string): return string
case let .invalid(string): return string
case let .failed(string): return string
case let .cancelled(string): return string
case let .unknown(string): return string
}
}
fileprivate init(response: sourcekitd_response_t) {
let description = String(validatingUTF8: sourcekitd_response_error_get_description(response)!)
switch sourcekitd_response_error_get_kind(response) {
case SOURCEKITD_ERROR_CONNECTION_INTERRUPTED: self = .connectionInterrupted(description)
case SOURCEKITD_ERROR_REQUEST_INVALID: self = .invalid(description)
case SOURCEKITD_ERROR_REQUEST_FAILED: self = .failed(description)
case SOURCEKITD_ERROR_REQUEST_CANCELLED: self = .cancelled(description)
default: self = .unknown(description)
}
}
}
/**
Sends the request to SourceKit and return the response as an [String: SourceKitRepresentable].
- returns: SourceKit output as a dictionary.
- throws: Request.Error on fail ()
*/
@available(*, deprecated, renamed: "send()")
public func failableSend() throws -> [String: SourceKitRepresentable] {
return try send()
}
}
// MARK: CustomStringConvertible
extension Request: CustomStringConvertible {
/// A textual representation of `Request`.
public var description: String { return sourcekitObject.description }
}
private func interfaceForModule(_ module: String, compilerArguments: [String]) throws -> [String: SourceKitRepresentable] {
return try Request.customRequest(request: [
"key.request": UID("source.request.editor.open.interface"),
"key.name": NSUUID().uuidString,
"key.compilerargs": compilerArguments,
"key.modulename": module
]).send()
}
extension String {
private func nameFromFullFunctionName() -> String {
return String(self[..<range(of: "(")!.lowerBound])
}
fileprivate func extractFreeFunctions(inSubstructure substructure: [[String: SourceKitRepresentable]]) -> [String] {
return substructure.filter({
SwiftDeclarationKind(rawValue: SwiftDocKey.getKind($0)!) == .functionFree
}).compactMap { function -> String? in
let name = (function["key.name"] as! String).nameFromFullFunctionName()
let unsupportedFunctions = [
"clang_executeOnThread",
"sourcekitd_variant_dictionary_apply",
"sourcekitd_variant_array_apply"
]
guard !unsupportedFunctions.contains(name) else {
return nil
}
let parameters = SwiftDocKey.getSubstructure(function)?.map { parameterStructure in
return parameterStructure["key.typename"] as! String
} ?? []
var returnTypes = [String]()
if let offset = SwiftDocKey.getOffset(function), let length = SwiftDocKey.getLength(function) {
let stringView = StringView(self)
if let functionDeclaration = stringView.substringWithByteRange(ByteRange(location: offset, length: length)),
let startOfReturnArrow = functionDeclaration.range(of: "->", options: .backwards)?.lowerBound {
let adjustedDistance = distance(from: startIndex, to: startOfReturnArrow)
let adjustedReturnTypeStartIndex = functionDeclaration.index(functionDeclaration.startIndex,
offsetBy: adjustedDistance + 3)
returnTypes.append(String(functionDeclaration[adjustedReturnTypeStartIndex...]))
}
}
let joinedParameters = parameters.map({ $0.replacingOccurrences(of: "!", with: "?") }).joined(separator: ", ")
let joinedReturnTypes = returnTypes.map({ $0.replacingOccurrences(of: "!", with: "?") }).joined(separator: ", ")
let lhs = "internal let \(name): @convention(c) (\(joinedParameters)) -> (\(joinedReturnTypes))"
let rhs = "library.load(symbol: \"\(name)\")"
return "\(lhs) = \(rhs)".replacingOccurrences(of: "SourceKittenFramework.", with: "")
}
}
}
internal func libraryWrapperForModule(_ module: String,
macOSPath: String,
linuxPath: String?,
compilerArguments: [String]) throws -> String {
let sourceKitResponse = try interfaceForModule(module, compilerArguments: compilerArguments)
let substructure = SwiftDocKey.getSubstructure(Structure(sourceKitResponse: sourceKitResponse).dictionary)!
let source = sourceKitResponse["key.sourcetext"] as! String
let freeFunctions = source.extractFreeFunctions(inSubstructure: substructure)
let spmImport = "#if SWIFT_PACKAGE\nimport \(module)\n#endif\n"
let library: String
if let linuxPath = linuxPath {
library = """
#if os(Linux)
private let path = "\(linuxPath)"
#else
private let path = "\(macOSPath)"
#endif
private let library = toolchainLoader.load(path: path)
"""
} else {
library = "private let library = toolchainLoader.load(path: \"\(macOSPath)\")\n"
}
let swiftlintDisableComment = "// swiftlint:disable unused_declaration - We don't care if some of these are unused.\n"
let startPlatformCheck: String
let endPlatformCheck: String
if linuxPath == nil {
startPlatformCheck = "#if !os(Linux)\nimport Darwin\n"
endPlatformCheck = "\n#endif\n"
} else {
startPlatformCheck = ""
endPlatformCheck = "\n"
}
return startPlatformCheck + spmImport + library + swiftlintDisableComment + freeFunctions.joined(separator: "\n") + endPlatformCheck
}
| mit | ffdcb4022b69ae9ca86a324e74758502 | 42.336714 | 136 | 0.603417 | 4.947893 | false | false | false | false |
crazytonyli/GeoNet-iOS | GeoNet/Quakes/QuakesViewController.swift | 1 | 4383 | //
// QuakesViewController.swift
// GeoNet
//
// Created by Tony Li on 18/11/16.
// Copyright © 2016 Tony Li. All rights reserved.
//
import UIKit
import GeoNetAPI
class QuakesViewController: UITableViewController {
weak var loadQuakesTask: URLSessionTask? {
willSet {
loadQuakesTask?.cancel()
}
}
var quakes = [Quake]() {
didSet {
tableView?.reloadData()
}
}
var titleTapGestureRecognizer: UITapGestureRecognizer?
init() {
super.init(style: .plain)
title = "Quakes"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(loadQuakes), for: .valueChanged)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80
tableView.separatorInset = UIEdgeInsets(top: 0, left: QuakeInfoTableViewCell.intensityIndicatorWidth, bottom: 0, right:0)
tableView.register(QuakeInfoTableViewCell.self, forCellReuseIdentifier: "cell")
loadQuakes()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if titleTapGestureRecognizer == nil {
titleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showIntensitySelection))
self.navigationController?.navigationBar.addGestureRecognizer(titleTapGestureRecognizer!)
}
titleTapGestureRecognizer?.isEnabled = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
titleTapGestureRecognizer?.isEnabled = false
}
}
extension QuakesViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quakes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable force_cast
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! QuakeInfoTableViewCell
cell.update(with: quakes[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
navigationController?.pushViewController(QuakeMapViewController(quake: quakes[indexPath.row]), animated: true)
}
}
private extension QuakesViewController {
@objc func showIntensitySelection() {
let controller = IntensitiesViewController(intensity: UserDefaults.app.selectedIntensity ?? .weak)
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.delegate = self
controller.popoverPresentationController?.sourceView = self.navigationController!.navigationBar
controller.popoverPresentationController?.sourceRect = self.navigationController!.navigationBar.bounds.insetBy(dx: 0, dy: 8)
present(controller, animated: true, completion: nil)
controller.selectionChange = { [unowned self] intensity in
self.dismiss(animated: true, completion: nil)
UserDefaults.app.selectedIntensity = intensity
self.quakes = []
self.loadQuakes()
}
}
@objc func loadQuakes() {
let intensity = UserDefaults.app.selectedIntensity ?? .weak
guard let mmi = QuakeMMI(rawValue: intensity.MMIRange.lowerBound) else {
return
}
navigationItem.title = "Quake (\(intensity.description)+)"
loadQuakesTask = URLSession.API.quakes(with: mmi) { [weak self] result in
guard let `self` = self else { return }
self.refreshControl?.endRefreshing()
switch result {
case .success(let quakes): self.quakes = quakes
case .failure(let error): break
}
}
}
}
extension QuakesViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
| mit | f8a380e159c62c7a027e9817bf8b4dff | 31.947368 | 132 | 0.681424 | 5.370098 | false | false | false | false |
phimage/Arithmosophi | Sources/Sigma.swift | 1 | 15038 | //
// Sigma.swift
// Arithmosophi
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#if os(Linux)
import Glibc
#else
import Darwin
import CoreGraphics
#if os(watchOS)
import UIKit
#endif
#endif
// MARK: variance
// http://en.wikipedia.org/wiki/Variance
public enum VarianceMode {
case sample
case population
}
public extension Collection where Self.Iterator.Element: Averagable & Initializable & Substractable & Multiplicable {
// Return varianceSample: Σ( (Element - average)^2 ) / (count - 1)
// https://en.wikipedia.org/wiki/Variance#Sample_variance
var varianceSample: Self.Iterator.Element? {
if self.count < 2 { return nil }
let avgerageValue = average
let n = self.reduce(Self.Iterator.Element()) { total, value in
total + (avgerageValue - value) * (avgerageValue - value)
}
let count = AveragableDivideType(Int64(self.count)) // XXX check swift 4 conversion...
return n / (count - 1)
}
// Return variancePopulation: Σ( (Element - average)^2 ) / count
// https://en.wikipedia.org/wiki/Variance#Population_variance
var variancePopulation: Self.Iterator.Element? {
if self.count == 0 { return nil }
let avgerageValue = average
let numerator = self.reduce(Self.Iterator.Element()) { total, value in
total + (avgerageValue - value) * (avgerageValue - value)
}
let count = AveragableDivideType(Int64(self.count)) // XXX check swift 4 conversion...
return numerator / count
}
func variance(mode: VarianceMode) -> Self.Iterator.Element? {
switch mode {
case .sample: return varianceSample
case .population: return variancePopulation
}
}
}
public extension Collection where Self.Iterator.Element: Averagable & Initializable & Substractable & Multiplicable & Arithmos {
var standardDeviationSample: Self.Iterator.Element? {
return varianceSample?.sqrt() ?? nil
}
var standardDeviationPopulation: Self.Iterator.Element? {
return variancePopulation?.sqrt() ?? nil
}
func standardDeviation(mode: VarianceMode) -> Self.Iterator.Element? {
switch mode {
case .sample: return standardDeviationSample
case .population: return standardDeviationPopulation
}
}
var σSample: Self.Iterator.Element? {
return standardDeviationSample
}
var σPopulation: Self.Iterator.Element? {
return standardDeviationPopulation
}
}
// MARK: Moment, kurtosis, skewness
public struct Moment<T: Averagable & ExpressibleByIntegerLiteral & Substractable & Multiplicable & Arithmos & Equatable & Dividable> {
public private(set) var M0: T = 0
public private(set) var M1: T = 0
public private(set) var M2: T = 0
public private(set) var M3: T = 0
public private(set) var M4: T = 0
init?(_ col: [T]) {
if col.count == 0 { return nil }
M0 = T(Double(col.count))
var n: T = 0
for x in col {
let n1 = n
n += 1
let delta = x - M1
let delta_n = delta / n
let delta_n2 = delta_n * delta_n
let term1 = delta * delta_n * n1
M1 += delta_n
let t4 = 6 * delta_n2 * M2 - 4 * delta_n * M3
let t3 = (n*n - 3*n + 3)
let t5 = term1 * delta_n2 * t3
M4 += t5 + t4
M3 += (term1 * delta_n * (n - 2)) as T - (3 * delta_n * M2) as T
M2 += term1
}
}
// https://en.wikipedia.org/wiki/Kurtosis#Excess_kurtosis
public var excessKurtosis: T {
return kurtosis - 3
}
//https://en.wikipedia.org/wiki/Kurtosis
public var kurtosis: T {
return (M0 * M4) / (M2 * M2)
}
// https://en.wikipedia.org/wiki/Skewness
public var skewness: T {
let p: T = 3 / 2
return M0.sqrt() * M3 / M2.pow(p)
}
public var average: T {
return M1
}
public var varianceSample: T {
return M2 / (M0 - 1)
}
public var variancePopulation: T {
return M2 / M0
}
public var standardDeviationSample: T {
return varianceSample.sqrt()
}
public var standardDeviationPopulation: T {
return variancePopulation.sqrt()
}
}
public extension Collection where Self.Iterator.Element: Averagable & ExpressibleByIntegerLiteral & Substractable & Multiplicable & Arithmos & Equatable & Dividable {
//https://en.wikipedia.org/wiki/Kurtosis
var kurtosis: Self.Iterator.Element? {
return moment?.kurtosis
}
// https://en.wikipedia.org/wiki/Skewness
var skewness: Self.Iterator.Element? {
return moment?.skewness
}
// https://en.wikipedia.org/wiki/Moment_(mathematics)
var moment: Moment<Self.Iterator.Element>? {
return Moment(Array(self))
}
}
// MARK: covariance
public extension Collection where Self.Iterator.Element: Averagable & Initializable & Substractable & Multiplicable & Arithmos {
func covariance<W: Collection>
(_ with: W, type: VarianceMode) -> Self.Iterator.Element? where W.Iterator.Element == Self.Iterator.Element {
switch type {
case .sample:
return covarianceSample(with)
case .population:
return covariancePopulation(with)
}
}
func covarianceSample<W: Collection>
(_ with: W) -> Self.Iterator.Element? where W.Iterator.Element == Self.Iterator.Element {
if self.count < 2 { return nil }
guard self.count == with.count else {
return nil
}
let average = self.average
let withAverage = with.average
var sum = Self.Iterator.Element()
for (element, withElement) in zip(self, with) {
sum += (element - average) * (withElement - withAverage)
}
let count = AveragableDivideType(Int64(self.count)) // XXX check swift 4 conversion...
return sum / (count - 1)
}
func covariancePopulation<W: Collection>
(_ with: W) -> Self.Iterator.Element? where W.Iterator.Element == Self.Iterator.Element {
if self.count < 2 { return nil }
guard self.count == with.count else {
return nil
}
let average = self.average
let withAverage = with.average
var sum = Self.Iterator.Element()
for (element, withElement) in zip(self, with) {
sum += (element - average) * (withElement - withAverage)
}
let count = AveragableDivideType(Int64(self.count)) // XXX check swift 4 conversion...
return sum / count
}
func covariance<W: Collection>
(_ with: W, mode: VarianceMode) -> Self.Iterator.Element? where W.Iterator.Element == Self.Iterator.Element {
switch mode {
case .sample: return covarianceSample(with)
case .population: return covariancePopulation(with)
}
}
}
// MARK: Pearson product-moment correlation coefficient
public extension Collection where Self.Iterator.Element: Averagable & Initializable & Substractable & Multiplicable & Arithmos & Equatable & Dividable {
// http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
func pearson<W: Collection>
(_ with: W) -> Self.Iterator.Element? where W.Iterator.Element == Self.Iterator.Element {
if let cov = self.covariancePopulation(with),
let σself = self.standardDeviationPopulation,
let σwith = with.standardDeviationPopulation {
let zero = Self.Iterator.Element()
if σself == zero || σwith == zero {
return nil
}
return cov / (σself * σwith)
}
return nil
}
}
// MARK: percentile
// https://en.wikipedia.org/wiki/Percentile
// NOT IMPLEMENTED YET
// MARK: linear regression
// https://en.wikipedia.org/wiki/Linear_regression
public enum LinearRegressionMethod {
case ols
case multiply
// case Accelerate (use upsurge?)
}
// Use with Double and fFloat (not Int)
public extension Collection where Self.Iterator.Element: Averagable & Initializable & Substractable & Multiplicable & Dividable {
// @return (intercept, slope) where with = slope * self + intercept
func linearRegression<W: Collection>
(_ with: W, method: LinearRegressionMethod = .ols) -> (Self.Iterator.Element, Self.Iterator.Element)? where W.Iterator.Element == Self.Iterator.Element {
guard self.count > 1 else {
return nil
}
guard self.count == with.count else {
return nil
}
let average = self.average
let withAverage = with.average
var sum1 = Self.Iterator.Element()
var sum2 = Self.Iterator.Element()
switch method {
case .multiply:
let m1 = multiply(with).average
sum1 = m1 - average * withAverage
let m2 = multiply(self).average
sum2 = m2 - average * average
case .ols:
for (element, withElement) in zip(self, with) {
let elMinusAverage = (element - average)
sum1 += elMinusAverage * (withElement - withAverage)
sum2 += elMinusAverage * elMinusAverage
}
}
let slope = sum1 / sum2 // ISSUE Int will failed here by dividing by zero (Int linear regression must return float result)
let intercept = withAverage - slope * average
return (intercept, slope)
}
func linearRegressionClosure<W: Collection>
(_ with: W, method: LinearRegressionMethod = .ols) -> ((Self.Iterator.Element) -> Self.Iterator.Element)? where W.Iterator.Element == Self.Iterator.Element {
guard let (intercept, slope) = self.linearRegression(with) else {
return nil
}
// y = slope * x + intercept
return { intercept + slope * $0 }
}
// Create a closure : slope * x + intercept with x closure parameters
static func linearRegressionClosure(_ intercept: Self.Iterator.Element, slope: Self.Iterator.Element) -> ((Self.Iterator.Element) -> Self.Iterator.Element) {
return { intercept + slope * $0 }
}
// https://en.wikipedia.org/wiki/Coefficient_of_determination
func coefficientOfDetermination<W: Collection>
(_ with: W, linearRegressionClosure: ((Self.Iterator.Element) -> Self.Iterator.Element)) -> Self.Iterator.Element where W.Iterator.Element == Self.Iterator.Element {
let withAverage = with.average
var sumSquareModel = Self.Iterator.Element() // sum of squares of the deviations of the estimated values of the response variable of the model
var sumSquareTotal = Self.Iterator.Element() // sum of squares of the deviations of the observed
for (element, withElement) in zip(self, with) {
let predictedValue = linearRegressionClosure(element)
let sub1 = predictedValue - withAverage
sumSquareModel += sub1 * sub1
let sub2 = withElement - withAverage
sumSquareTotal += sub2 * sub2
}
return sumSquareModel / sumSquareTotal
}
func coefficientOfDetermination<W: Collection>
(_ with: W, intercept: Self.Iterator.Element, slope: Self.Iterator.Element) -> Self.Iterator.Element where W.Iterator.Element == Self.Iterator.Element {
return self.coefficientOfDetermination(with, linearRegressionClosure: Self.linearRegressionClosure(intercept, slope: slope))
}
}
// MARK: geometric mean
public extension Sequence where Self.Element: Addable & Arithmos & Dividable & Multiplicable & ExpressibleByIntegerLiteral {
var geometricMean: Self.Element? {
let zero: Self.Element = 0
var result = zero
var n = zero
for value in self {
// swiftlint:disable:next shorthand_operator
result = result * value
n += 1
}
if n == 0 {
return 0
}
return result.pow(1 / n)
}
}
public extension Collection where Self.Element: Hashable {
typealias HashableElement = Self.Element
// Most frequent value in data set
// https://en.wikipedia.org/wiki/Mode_(statistics)
var mode: [Self.Element] {
var counter = [HashableElement: Int]()
var mode = [HashableElement]()
var max = 0
for value in self {
if let c = counter[value] {
counter[value] = c + 1
} else {
counter[value] = 0
}
let c = counter[value]!
if c == max {
mode.append(value)
} else if c > max {
max = c
mode = [value]
}
}
return mode
}
}
// MARK: - collection operations
// MARK: multiply
private extension Sequence where Self.Element: Multiplicable {
func multiply<W: Sequence>
(_ with: W) -> [Self.Element] where W.Element == Self.Element {
return zip(self, with).map { s, w in
return s * w
}
}
}
// MARK: add
private extension Sequence where Self.Element: Addable {
func add<W: Sequence>
(_ array: W) -> [Self.Iterator.Element] where W.Element == Self.Element {
return zip(self, array).map { s, w in
return s + w
}
}
}
// MARK: subtract
private extension Sequence where Self.Element: Substractable {
func subtract<W: Sequence>
(_ array: W) -> [Self.Iterator.Element] where W.Element == Self.Element {
return zip(self, array).map { s, w in
return s - w
}
}
}
// MARK: divide
private extension Sequence where Self.Element: Dividable {
func divide<W: Sequence>
(_ with: W) -> [Self.Iterator.Element] where W.Element == Self.Element {
return zip(self, with).map { s, w in
return s / w // NO ZERO valu
}
}
}
| mit | 82621a8fa752113cdb83b7cb26aa7dfa | 31.042644 | 173 | 0.625166 | 4.274175 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Branding/Banner/JetpackBannerView.swift | 1 | 2107 | import Combine
import UIKit
class JetpackBannerView: UIView {
var buttonAction: (() -> Void)?
init(buttonAction: (() -> Void)? = nil) {
super.init(frame: .zero)
self.buttonAction = buttonAction
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
@objc private func jetpackButtonTapped() {
buttonAction?()
}
private func setup() {
translatesAutoresizingMaskIntoConstraints = false
heightAnchor.constraint(equalToConstant: JetpackBannerView.minimumHeight).isActive = true
backgroundColor = Self.jetpackBannerBackgroundColor
let jetpackButton = JetpackButton(style: .banner)
jetpackButton.translatesAutoresizingMaskIntoConstraints = false
jetpackButton.addTarget(self, action: #selector(jetpackButtonTapped), for: .touchUpInside)
addSubview(jetpackButton)
pinSubviewToSafeArea(jetpackButton)
}
/// Preferred minimum height to be used for constraints
static let minimumHeight: CGFloat = 44
private static let jetpackBannerBackgroundColor = UIColor(light: .muriel(color: .jetpackGreen, .shade0),
dark: .muriel(color: .jetpackGreen, .shade90))
}
// MARK: Responding to scroll events
extension JetpackBannerView: Subscriber {
typealias Input = Bool
typealias Failure = Never
func receive(subscription: Subscription) {
subscription.request(.unlimited)
}
func receive(_ input: Bool) -> Subscribers.Demand {
let isHidden = input
guard self.isHidden != isHidden else {
return .unlimited
}
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseIn], animations: {
self.isHidden = isHidden
self.superview?.layoutIfNeeded()
}, completion: nil)
return .unlimited
}
func receive(completion: Subscribers.Completion<Never>) {}
}
| gpl-2.0 | 1d7b788c7d0fe450d00a2eedda29bdd7 | 28.263889 | 108 | 0.643094 | 5.151589 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.