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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catalanjrj/BarMate | BarMateCustomer/BarMateCustomer/barMenuViewViewController.swift | 1 | 4331 | //
// barMenuViewViewController.swift
// BarMateCustomer
//
// Created by Jorge Catalan on 6/23/16.
// Copyright © 2016 Jorge Catalan. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class barMenuViewViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var barMenuTableView: UITableView!
@IBOutlet weak var barNameLabel: UILabel!
var ref : FIRDatabaseReference = FIRDatabase.database().reference()
var barMenuArray = [String]()
var barMenuDict = [String:Drink]()
override func viewDidLoad() {
super.viewDidLoad()
//present drinkReady Alert
drinkReadyPopUp()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// remove observers when user leaves view
self.ref.removeAllObservers()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
bars()
}
// retrive barMenus
func bars(){
self.ref.child("Bars").child("aowifjeafasg").observeEventType(FIRDataEventType.Value, withBlock: {(snapshot) in
guard snapshot.value != nil else{
return
}
self.barMenuArray = [String]()
self.barMenuDict = [String:Drink]()
for (key,value)in snapshot.value!["barMenu"] as! [String:AnyObject]{
self.barMenuArray.append(key)
self.barMenuDict[key] = Drink(data: value as! [String:AnyObject])
}
dispatch_async(dispatch_get_main_queue(), {self.barMenuTableView.reloadData()})
})
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return barMenuArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("drinkMenuTableCell", forIndexPath: indexPath)as! drinkMenuTableCell
let label = barMenuArray[indexPath.row]
let bar = barMenuDict[label]
cell.configurMenuCell(bar!)
return cell
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "drinkDetailView"{
if let indexPath = self.barMenuTableView.indexPathForSelectedRow{
let object = barMenuArray[indexPath.row]
let destinationViewController = segue.destinationViewController as! confirmOrderViewController
destinationViewController.drink = barMenuDict[object]
}
}
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
func barNameLabel(bar:Bar){
barNameLabel.text = bar.barName
}
func drinkReadyPopUp(){
_ = self.ref.child("Orders/completed/").queryOrderedByChild("bar").queryEqualToValue("aowifjeafasg").observeEventType(FIRDataEventType.ChildAdded, withBlock: {(snapshot) in
if snapshot.value != nil{
let drinkReadyAlert = UIAlertController(title:"Order Status", message: "Your order is ready for pick up!", preferredStyle: .Alert)
let okAction = UIAlertAction(title:"Ok",style: .Default){(action) in
}
drinkReadyAlert.addAction(okAction)
self.presentViewController(drinkReadyAlert, animated:true){}
}else{
return
}
})
}
}
| cc0-1.0 | 92baa548751251095d79efe181494f53 | 30.376812 | 180 | 0.604157 | 5.392279 | false | false | false | false |
quickthyme/PUTcat | PUTcat/Presentation/TransactionDetail/Parameter/ParameterPresenter.swift | 1 | 3400 |
import UIKit
class ParameterPresenter : NSObject {}
extension ParameterPresenter : NameValueSceneDelegate {
func getSceneData(parentRefID: String, scene: NameValueScene) {
UseCaseFetchParameterList.action(transactionID: parentRefID).execute {
guard let list = $0 else { return }
let sceneData = ParameterSceneDataBuilder.constructSceneData(parameterList: list)
self.displaySceneData(sceneData, scene: scene)
}
}
func addItem(parentRefID: String, scene: NameValueScene) {
UseCaseAddParameter.action(transactionID: parentRefID).execute { _ in
self.getSceneData(parentRefID: parentRefID, scene: scene)
}
}
func scene(_ scene: NameValueScene, didUpdate item: NameValueSceneDataItem, parentRefID: String) {
UseCaseUpdateParameter
.action(transactionID: parentRefID, name: item.title ?? "", value: item.detail ?? "", id: item.refID)
.execute { _ in
self.getSceneData(parentRefID: parentRefID, scene: scene)
}
}
func scene(_ scene: NameValueScene, didDeleteItem item: NameValueSceneDataItem, parentRefID: String) {
UseCaseDeleteParameter.action(transactionID: parentRefID, parameterID: item.refID).execute { _ in
self.getSceneData(parentRefID: parentRefID, scene: scene)
}
}
func scene(_ scene: NameValueScene, didUpdateOrdinality sceneData: NameValueSceneData, parentRefID: String) {
let ordinality : [String] = sceneData.section[0].item.map { $0.refID }
UseCaseSortParameterList.action(transactionID: parentRefID, ordinality: ordinality).execute { _ in
self.getSceneData(parentRefID: parentRefID, scene: scene)
}
}
func scene(_ scene: NameValueScene, didCopy original: NameValueSceneDataItem, to new: NameValueSceneDataItem, parentRefID: String) {
UseCaseCopyParameter.action(parameterID: original.refID, transactionID: parentRefID).execute {
guard let copyResult = $0 else { return }
let item = ParameterSceneDataBuilder.constructSceneDataItem(parameter: copyResult.newCopy)
DispatchQueue.main.async { scene.updatedCopiedItem(item) }
}
}
func scene(_ scene: NameValueScene, didSelect item: NameValueSceneDataItem, parentRefID: String) {
guard let projectID = scene.projectID else { return }
UseCaseGetParsedParameter.action(transactionID: parentRefID, parameterID: item.refID, projectID: projectID)
.onFailure { error in
let error = error as? PCError
DispatchQueue.main.async {
scene.presentBasicAlert(title: "Hsss! Grrr.", message: error?.text,
button: "Meow", handler: nil)
}
}
.execute {
guard let parsedParameter = $0 else { return }
DispatchQueue.main.async {
scene.presentBasicAlert(title: parsedParameter.name, message: parsedParameter.value,
button: "OK", handler: nil)
}
}
}
private func displaySceneData(_ sceneData:NameValueSceneData, scene: NameValueScene) {
DispatchQueue.main.async {
scene.sceneData = sceneData
scene.refreshScene()
}
}
}
| apache-2.0 | efccc0bf5423054b4dc8f14261465c94 | 43.736842 | 136 | 0.642647 | 4.619565 | false | false | false | false |
jmgc/swift | test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift | 1 | 4275 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS2iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^\)]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwup{{[^)]+}} to i8*),
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS2iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS2iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{16|8}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second> {
case first(First)
case second(First, Second)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS2iGMf"
// CHECK-SAME: to %swift.full_type*),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.second(13, 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | b1eaa1d46fe1525fa2bfc45f529d3d87 | 44.478723 | 187 | 0.553684 | 2.861446 | false | false | false | false |
netprotections/atonecon-ios | AtoneCon/Sources/Payment.swift | 1 | 1563 | //
// Payment.swift
// AtoneCon
//
// Created by Pham Ngoc Hanh on 6/30/17.
// Copyright © 2017 AsianTech Inc. All rights reserved.
//
import Foundation
import ObjectMapper
extension AtoneCon {
public struct Payment {
public var amount = 0
public var userNo: String?
public var shopTransactionNo = ""
public var salesSettled: Bool?
public var descriptionTrans: String?
public var checksum = ""
public var transactionOptions: [Int] = []
public var customer: Customer = Customer(name: "")
public var serviceSupplier: Supplier?
public var desCustomers: [DesCustomer]?
public var items: [Item] = []
public init(amount: Int,
shopTransactionNo: String,
checksum: String) {
self.amount = amount
self.shopTransactionNo = shopTransactionNo
self.checksum = checksum
}
}
}
extension AtoneCon.Payment: Mappable {
public init?(map: Map) {
}
public mutating func mapping(map: Map) {
amount <- map["amount"]
userNo <- map["user_no"]
shopTransactionNo <- map["shop_transaction_no"]
salesSettled <- map["sales_settled"]
descriptionTrans <- map["description_trans"]
transactionOptions <- map["transaction_options"]
checksum <- map["checksum"]
customer <- map["customer"]
desCustomers <- map["dest_customers"]
items <- map["items"]
serviceSupplier <- map["service_supplier"]
}
}
| mit | cec236c11c18b20bf93ded3d7933b65a | 27.925926 | 58 | 0.597951 | 4.37535 | false | false | false | false |
Ryan-Korteway/GVSSS | GVBandwagon/GVBandwagon/userInfoTableViewController.swift | 1 | 5472 | //
// userInfoTableViewController.swift
// GVBandwagon
//
// Created by Nicolas Heady on 2/7/17.
// Copyright © 2017 Nicolas Heady. All rights reserved.
//
import UIKit
import Firebase
class userInfoTableViewController: UITableViewController {
@IBOutlet var fNameField: UITextField!
@IBOutlet var lNameField: UITextField!
@IBOutlet var phoneField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var venmoField: UITextField!
@IBOutlet var makeField: UITextField!
@IBOutlet var colorField: UITextField!
@IBOutlet var modelField: UITextField!
var currentUser : FIRUser?
var ref: FIRDatabaseReference = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.currentUser = FIRAuth.auth()?.currentUser
let userID = self.currentUser?.uid
//self.fNameField.text = currentUser?.displayName
print("What is display name? : \(currentUser?.displayName)")
self.ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let fname = value?["name"] as? String ?? ""
//let user = User.init(username: username)
let phone = value?["phone"] as? String ?? ""
self.emailField.text = self.currentUser?.email
self.fNameField.text = fname
self.phoneField.text = phone
// ...
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 7
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath.section == 0 || indexPath.section == 6) {
return 100
} else {
return 44
}
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
override func viewWillDisappear(_ animated : Bool) {
super.viewWillDisappear(animated)
if (self.isMovingFromParentViewController) {
print("Updating...")
self.ref.child("users").child("\(self.currentUser!.uid)").observeSingleEvent(of: .value, with: { (snapshot) in
self.ref.child("users/\(self.currentUser!.uid)/name").setValue(self.fNameField.text! + " " + self.lNameField.text!)
self.ref.child("users/\(self.currentUser!.uid)/phone").setValue(self.phoneField.text)
}) { (error) in
print("Update Error, \(error.localizedDescription)")
}
}
}
}
| apache-2.0 | b5dd6b0dd77ecb56c748c344ce090c4e | 34.296774 | 136 | 0.631694 | 5.17597 | false | false | false | false |
mvader/Subtle | Subtle/AppDelegate.swift | 1 | 2266 | //
// AppDelegate.swift
// Subtle
//
// Created by Miguel Molina on 03/02/16.
// Copyright © 2016 Miguel Molina. All rights reserved.
//
import Cocoa
import MASPreferences
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var masterViewController: MasterViewController!
private var preferencesWindow: MASPreferencesWindowController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
masterViewController = MasterViewController(nibName: "MasterViewController", bundle: nil)
window.contentView?.addSubview(masterViewController.view)
masterViewController.view.frame = window.contentView!.bounds
self.window.styleMask = self.window.styleMask | NSFullSizeContentViewWindowMask
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
// MARK - Actions
extension AppDelegate {
@IBAction func openDocument(sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = true
openPanel.canChooseDirectories = false
openPanel.canChooseFiles = true
openPanel.beginWithCompletionHandler { (result) -> Void in
if result == NSFileHandlingPanelOKButton {
openPanel.URLs.map{
return $0.absoluteString.substringFromIndex(
$0.absoluteString.startIndex.advancedBy(7)
)
}.forEach{ path in
if isMovie(path) {
self.masterViewController.queueFile(path)
}
}
}
}
}
@IBAction func openPreferences(sender: AnyObject?) {
preferencesWindowController().showWindow(nil)
}
}
// Mark - MASPreferences
extension AppDelegate {
func preferencesWindowController() -> NSWindowController {
if preferencesWindow == nil {
let controllers = [LanguagePreferencesViewController()]
preferencesWindow = MASPreferencesWindowController(viewControllers: controllers, title: "Preferences")
}
return preferencesWindow!
}
}
| mit | 4eec5cf780bb2d6dfce53c5f2e8b16bc | 30.458333 | 114 | 0.659161 | 5.792839 | false | false | false | false |
CD1212/Doughnut | Doughnut/Windows/ShowPodcastWindow.swift | 1 | 7577 | /*
* Doughnut Podcast Client
* Copyright (C) 2017 Chris Dyer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
import AVFoundation
class ShowPodcastWindowController: NSWindowController {
override func windowDidLoad() {
window?.isMovableByWindowBackground = true
window?.titleVisibility = .hidden
window?.styleMask.insert([ .resizable ])
window?.standardWindowButton(.closeButton)?.isHidden = true
window?.standardWindowButton(.miniaturizeButton)?.isHidden = true
window?.standardWindowButton(.toolbarButton)?.isHidden = true
window?.standardWindowButton(.zoomButton)?.isHidden = true
}
}
class ShowPodcastWindow: NSWindow {
override var canBecomeKey: Bool {
get {
return true
}
}
}
class ShowPodcastViewController: NSViewController {
let defaultPodcastArtwork = NSImage(named: NSImage.Name(rawValue: "PodcastPlaceholder"))
@IBOutlet weak var artworkView: NSImageView!
@IBOutlet weak var titleLabelView: NSTextField!
@IBOutlet weak var authorLabelView: NSTextField!
@IBOutlet weak var copyrightLabelView: NSTextField!
@IBOutlet weak var tabBarView: NSSegmentedControl!
@IBOutlet weak var tabView: NSTabView!
// Details Tab
@IBOutlet weak var titleInputView: NSTextField!
@IBOutlet weak var authorInputView: NSTextField!
@IBOutlet weak var linkInputView: NSTextField!
@IBOutlet weak var copyrightInputView: NSTextField!
@IBAction func titleInputEvent(_ sender: NSTextField) {
titleLabelView.stringValue = sender.stringValue
}
@IBAction func authorInputEvent(_ sender: NSTextField) {
authorLabelView.stringValue = sender.stringValue
}
@IBAction func copyrightInputEvent(_ sender: NSTextField) {
copyrightLabelView.stringValue = sender.stringValue
}
// Artwork Tab
var modifiedImage = false
@IBOutlet weak var artworkLargeView: NSImageView!
// Description Tab
var modifiedDescription = false
@IBOutlet weak var descriptionInputView: NSTextField!
// Options Tab
@IBOutlet weak var reloadInputView: NSPopUpButton!
@IBOutlet weak var lastParsedLabelView: NSTextField!
@IBOutlet weak var autoDownloadCheckView: NSButton!
@IBOutlet weak var storageLabelView: NSTextField!
@IBOutlet weak var capacityLabelView: NSTextField!
override func viewDidLoad() {
tabBarView.selectedSegment = 0
tabView.selectTabViewItem(at: 0)
artworkView.wantsLayer = true
artworkView.layer?.borderWidth = 1.0
artworkView.layer?.borderColor = NSColor(calibratedWhite: 0.8, alpha: 1.0).cgColor
artworkView.layer?.cornerRadius = 3.0
artworkView.layer?.masksToBounds = true
}
var podcast: Podcast? {
didSet {
if let artwork = podcast?.image {
artworkView.image = artwork
} else {
artworkView.image = defaultPodcastArtwork
}
titleLabelView.stringValue = podcast?.title ?? ""
authorLabelView.stringValue = podcast?.author ?? ""
copyrightLabelView.stringValue = podcast?.copyright ?? ""
// Details View
titleInputView.stringValue = podcast?.title ?? ""
authorInputView.stringValue = podcast?.author ?? ""
linkInputView.stringValue = podcast?.link ?? ""
copyrightInputView.stringValue = podcast?.copyright ?? ""
// Artwork View
if let artwork = podcast?.image {
artworkLargeView.image = artwork
} else {
artworkLargeView.image = defaultPodcastArtwork
}
// Description View
descriptionInputView.stringValue = podcast?.description ?? ""
// Options View
reloadInputView.selectItem(withTag: podcast?.reloadFrequency ?? 0)
autoDownloadCheckView.state = (podcast?.autoDownload ?? false) ? .on : .off
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
if let lastParsed = podcast?.lastParsed {
lastParsedLabelView.stringValue = dateFormatter.string(from: lastParsed)
} else {
lastParsedLabelView.stringValue = "Never"
}
storageLabelView.stringValue = podcast?.storagePath()?.path ?? "Unknown"
if let podcast = podcast {
if let capacity = Storage.podcastSize(podcast) {
capacityLabelView.stringValue = capacity
}
} else {
capacityLabelView.stringValue = "0 GB"
}
}
}
@IBAction func switchTab(_ sender: NSSegmentedCell) {
let clickedSegment = sender.selectedSegment
tabView.selectTabViewItem(at: clickedSegment)
}
@IBAction func cancel(_ sender: Any) {
self.view.window?.close()
}
// Permeate UI input changes to podcat object
func commitChanges(_ podcast: Podcast) {
podcast.title = titleInputView.stringValue
podcast.author = authorInputView.stringValue
podcast.link = linkInputView.stringValue
podcast.copyright = copyrightInputView.stringValue
if modifiedImage {
podcast.image = artworkLargeView.image
}
if modifiedDescription {
podcast.description = descriptionInputView.stringValue
}
podcast.reloadFrequency = reloadInputView.selectedTag()
if autoDownloadCheckView.state == .on {
podcast.autoDownload = true
} else {
podcast.autoDownload = false
}
}
@IBAction func savePodcast(_ sender: Any) {
if let podcast = podcast {
commitChanges(podcast)
if validate() {
Library.global.save(podcast: podcast)
self.view.window?.close()
}
} else {
// Create new podcast
let podcast = Podcast(title: titleInputView.stringValue)
commitChanges(podcast)
if validate() {
Library.global.subscribe(podcast: podcast)
self.view.window?.close()
}
}
}
@IBAction func addArtwork(_ sender: Any) {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.runModal()
if let url = panel.url {
if url.pathExtension == "jpg" || url.pathExtension == "png" {
artworkLargeView.image = NSImage(contentsOfFile: url.path)
} else {
let asset = AVAsset(url: url)
for item in asset.commonMetadata {
if let key = item.commonKey, let value = item.value {
if key.rawValue == "artwork" {
artworkLargeView.image = NSImage(data: value as! Data)
}
}
}
}
artworkView.image = artworkLargeView.image
modifiedImage = true
}
}
func validate() -> Bool {
guard let podcast = podcast else { return false }
if let invalid = podcast.invalid() {
let alert = NSAlert()
alert.messageText = "Unable to Save Podcast"
alert.informativeText = invalid
alert.runModal()
return false
} else {
return true
}
}
}
| gpl-3.0 | 165df2e8f8387d7b07abf81daecc41f7 | 29.429719 | 90 | 0.674541 | 4.819975 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/Glucose/Identifier/Identifier+GlucoseMonitorViewController.swift | 1 | 1997 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
extension Identifier: CaseIterable where Value == GlucoseMonitorViewController {
static var allCases: [Identifier<GlucoseMonitorViewController>] {
return [.all, .first, .last]
}
static let all: Identifier<GlucoseMonitorViewController> = "All"
static let first: Identifier<GlucoseMonitorViewController> = "First"
static let last: Identifier<GlucoseMonitorViewController> = "Last"
}
| bsd-3-clause | f771e90b0ab6165903e4299c44c1db28 | 45.44186 | 84 | 0.772659 | 4.754762 | false | false | false | false |
ryanspillsbury90/HaleMeditates | ios/Hale Meditates/SessionTableViewCell.swift | 1 | 2163 | //
// SessionTableViewCell.swift
// Hale Meditates
//
// Created by Ryan Pillsbury on 9/4/15.
// Copyright (c) 2015 koait. All rights reserved.
//
import UIKit
class SessionTableViewCell: UITableViewCell {
var model: AudioSession? {
didSet {
setUI();
}
}
@IBOutlet weak var titlelabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var instructorImage: UIImageView!
@IBOutlet weak var instructorNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setUI() {
self.titlelabel.text = self.model?.title
if self.model != nil {
self.durationLabel.text = UIUtil.formatTimeStringLong(self.model!.duration);
} else {
self.durationLabel.text = "";
}
self.instructorNameLabel.text = (self.model?.instructorName != nil) ? self.model?.instructorName : "";
if self.model?.instructorImage == nil {
if (self.model?.instructorImageUrl != nil) {
Util.enqueue(({
let url = self.model!.instructorImageUrl!;
if let data = HttpUtil.GET(url, body: nil, headers: nil, isAsync: false, callback: nil) {
dispatch_async(dispatch_get_main_queue(), ({
if (url == self.model?.instructorImageUrl) {
let image = UIImage(data: data);
self.model?.instructorImage = image;
self.instructorImage.image = self.model?.instructorImage;
}
}));
}
}), priority: Util.PRIORITY.SUPER_HIGH)
}
} else {
self.instructorImage.image = self.model?.instructorImage
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 2538290d5efe7714c81235e0303b15b4 | 29.9 | 110 | 0.530744 | 4.774834 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 33--The-Eagle-has-Landed/LaberintoLabyrinth/LaberintoLabyrinth/MazeViewController.swift | 1 | 11250 | //
// ViewController.swift
// LaberintoLabyrinth
//
// Created by Pedro Trujillo on 11/18/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
import CoreMotion
class MazeViewController: UIViewController, UICollisionBehaviorDelegate
{
@IBOutlet weak var starStopButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
//main variables
var delegator: playMazeProtocolDelegate!
var borderUpDistance = 100
var mazeSize:Int = 26
var numberOfBalls: Int = 1
var mazeHightRows = 1 // por defirnir
//phyx
var animator:UIDynamicAnimator!
var gravity:UIGravityBehavior!
var collision:UICollisionBehavior!
var motionManager:CMMotionManager!
//objects
var ballsArray:Array<BallUIView> = []
var mazeArray:Array<Array<BrickMaze>> = []
var timer:NSTimer?
var startTime = NSDate.timeIntervalSinceReferenceDate()//NSTimeInterval()
var originalCount = 0
//objects visual properties
var radiusBalls: CGFloat = 30.0
var brickSize:CGFloat!
//objects phyx properties
var ballsElasticity: CGFloat = 0.8
var ballsDensity:CGFloat = 0.1
var ballsFriction:CGFloat = 0.01
override func viewDidLoad()
{
super.viewDidLoad()
brickSize = CGFloat(UIScreen.mainScreen().bounds.size.width)/CGFloat(mazeSize) // calculate size of each brick
radiusBalls = CGFloat(brickSize)/CGFloat(1.7)//calculate the size of ball
//[!!!] uncoment this if you don't have an iPhone to test, this is for test in simulator
// NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated:", name: UIDeviceOrientationDidChangeNotification, object: UIDevice.currentDevice())
///collision = UICollisionBehavior()
//this order is nescesary to conserv the speed of the app
createBalls(numberOfBalls)
setProperties()
createMaze()
}
func createMaze()
{
let matrix = createMatrix()
var yPos:CGFloat = CGFloat(borderUpDistance)
for y in matrix
{
var xPos:CGFloat = 0
var rowArray: Array<BrickMaze> = []
for x in y
{
let aBrick:BrickMaze = BrickMaze(frame: CGRect(x: xPos, y: yPos, width: brickSize, height: brickSize))
aBrick.setId(x)//set the colors of each brick
if x == 0
{
//self.collision.addItem(aBrick)
self.collision.addBoundaryWithIdentifier("aBrick", forPath: UIBezierPath(rect: aBrick.frame))
}
rowArray.append(aBrick)
view.addSubview(aBrick)
xPos += brickSize
}
mazeArray.append(rowArray)
yPos += brickSize
}
}
func rotated(note: NSNotification)
{
let device: UIDevice = note.object as! UIDevice
switch(device.orientation)
{
case UIDeviceOrientation.Portrait:
print("Portrait ")
let v = CGVectorMake(0.0 , 1.0);
self.gravity.gravityDirection = v
break
case UIDeviceOrientation.PortraitUpsideDown:
print("Portrait Upside Down ")
let v = CGVectorMake(0.0 , -1.0);
self.gravity.gravityDirection = v
break
case UIDeviceOrientation.LandscapeLeft:
print("Landscape Left ")
let v = CGVectorMake(-1.0 , 0.0);
self.gravity.gravityDirection = v
break
case UIDeviceOrientation.LandscapeRight:
print("Landscape Right ")
let v = CGVectorMake(1.0 , 0.0);
self.gravity.gravityDirection = v
break
case UIDeviceOrientation.Unknown:
print("Unknown ")
break
default:
break
}
print("dir X: \(self.gravity.gravityDirection.dx)")
print("dir Y: \(self.gravity.gravityDirection.dy)")
}
func createBalls(numberOfBalls:Int)
{
//objects
for nb in 0..<(numberOfBalls)
{
let aBall:BallUIView = BallUIView(frame: CGRectMake(100.0, 50.0, radiusBalls, radiusBalls))
aBall.ID = nb
aBall.layer.cornerRadius = aBall.bounds.size.width/2
aBall.layer.masksToBounds = true
//collision.addItem(aBall)
///self.collision.addBoundaryWithIdentifier("aBall", forPath: UIBezierPath(rect: aBall.frame))
ballsArray.append(aBall)
view.addSubview(aBall)
}
}
func createMatrix() -> Array<Array<Int>>
{
var list = [Int]()
let size = mazeSize
let rootValue = 7//Int(arc4random_uniform(UInt32(size)))//Int(size/5)// it can chagne to set the sie of the maze just spliting the size, it decide where begin the root
let newTree:BinaryTree = BinaryTree(rootVal: rootValue)
var ran = rootValue
list.append(ran)
print("root insert: \(rootValue)")
for x in 1...size
{
list.append(ran)
repeat
{
ran = Int(arc4random_uniform(UInt32(size)))
}
while list.contains(ran) && ran == 0
newTree.sortedInsert(ran, newNode: newTree.root)
}
print("\n tree level \(newTree.height)")
return newTree.BFSearchMatix(newTree.root,size: size)
}
func setProperties()//numberOfBalls:Int)
{
//phyx
animator = UIDynamicAnimator(referenceView: view)
gravity = UIGravityBehavior(items: ballsArray)
animator.addBehavior(gravity)
collision = UICollisionBehavior(items: ballsArray)
collision.collisionDelegate = self
collision.translatesReferenceBoundsIntoBoundary = true // add stage frame to colisions area
animator?.addBehavior(collision)
//phyx properties for items
let ballElasticity = UIDynamicItemBehavior(items: ballsArray)
ballElasticity.elasticity = ballsElasticity
animator.addBehavior(ballElasticity)
let ballDensity = UIDynamicItemBehavior(items: ballsArray)
ballDensity.density = ballsDensity
animator.addBehavior(ballDensity)
let ballFriction = UIDynamicItemBehavior(items: ballsArray)
ballFriction.friction = ballsFriction
animator.addBehavior(ballFriction)
//Motion Device//reference [2]
motionManager = CMMotionManager()
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: gravityUpdated)
}
func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint)
{
print("Boundary contact occurred - \(identifier)")
//print("Contact Item occurred - \(item)")
let collidingView = item as! UIView
collidingView.backgroundColor = UIColor.whiteColor()
UIView.animateWithDuration(0.4)
{
collidingView.backgroundColor = UIColor.orangeColor()
}
}
func gravityUpdated(motion:CMDeviceMotion?, error:NSError?)
{
//print("Test")
// if (error != nil)
// {
//
//
// }
// else
// {
// print("Motion device (gravity) error: ",error?.localizedDescription)
// }
//
let grav: CMAcceleration = (motion?.gravity)!;
let x = CGFloat(grav.x)
let y = CGFloat(grav.y)
var p = CGPointMake(x,y)
// Have to correct for orientation.
let orientation = UIApplication.sharedApplication().statusBarOrientation;
if orientation == UIInterfaceOrientation.LandscapeLeft {
let t = p.x
p.x = 0 - p.y
p.y = t
} else if orientation == UIInterfaceOrientation.LandscapeRight {
let t = p.x
p.x = p.y
p.y = 0 - t
} else if orientation == UIInterfaceOrientation.PortraitUpsideDown {
p.x *= -1
p.y *= -1
}
let v = CGVectorMake(p.x, 0 - p.y);
gravity.gravityDirection = v;
//print("dir X: \(self.gravity.gravityDirection.dx)")
//print("dir Y: \(self.gravity.gravityDirection.dy)")
}
//MARK: Timer
func setTimer()
{
}
//MARK: - Action Handlers
@IBAction func startStopTapped(sender: UIButton)
{
startTimer()
}
// @IBAction func resetTapped(sender: UIButton)
// {
// stopTimer()
// timerLabel.text = "\(originalCount)"
// }
private func startTimer()
{
if timer == nil
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "Render:", userInfo: nil, repeats: true)
starStopButton.setTitle("Pause", forState: UIControlState.Normal)
}
else
{
stopTimer()
starStopButton.setTitle("Start", forState: UIControlState.Normal)
}
}
private func stopTimer()
{
timer?.invalidate()
timer = nil
}
func Render(time:NSTimer)
{
print(startTime)
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime : NSTimeInterval = currentTime - startTime
let hours = Int(elapsedTime / 3600.0)
elapsedTime -= (NSTimeInterval(hours) * 3600)
let minutes = Int(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = Int(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = Int(elapsedTime * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
timerLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
//timerLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
// if newCount == 0
// {
// view.backgroundColor = UIColor.redColor()
// stopTimer()
// }
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//reference [1] http://stackoverflow.com/questions/25651969/setting-device-orientation-in-swift-ios
//reference [2] https://www.bignerdranch.com/blog/uidynamics-in-swift/
//reference [3] http://stackoverflow.com/questions/32106856/how-to-make-nstimer-show-hrs-min-sec | cc0-1.0 | b5d7641fa460d059912be3a220cbf6db | 28.145078 | 175 | 0.571784 | 4.871806 | false | false | false | false |
szk-atmosphere/ReuseCellConfigure | ReuseCellConfigureSample/ReuseCellConfigureSample/TableView/TableViewController.swift | 1 | 1888 | //
// TableViewController.swift
// ReuseCellConfigureSample
//
// Created by 鈴木 大貴 on 2016/01/05.
// Copyright © 2016年 szk-atmosphere. All rights reserved.
//
import UIKit
import ReuseCellConfigure
final class TableViewController: UIViewController {
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.register(with: LeftIconTableViewCell.self)
tableView.register(with: RightIconTableViewCell.self)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
}
extension TableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int("Z".unicodeScalars.first!.value - "A".unicodeScalars.first!.value) + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell?
let alphabet = String(describing: UnicodeScalar("A".unicodeScalars.first!.value + UInt32(indexPath.row))!)
switch indexPath.row % 2 {
case 0:
cell = tableView.dequeue(with: LeftIconTableViewCell.self) { cell in
cell.alphabetLabel.text = alphabet
cell.randomBackgoundColor()
}
case 1:
cell = tableView.dequeue(with: RightIconTableViewCell.self) { cell in
cell.alphabetLabel.text = alphabet
}
default:
cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
}
return cell!
}
}
extension TableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
| mit | fc101c95f46cb0bcce340ee7ef221720 | 32.517857 | 114 | 0.671817 | 5.005333 | false | false | false | false |
xedin/swift | test/attr/open.swift | 8 | 6332 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-module -c %S/Inputs/OpenHelpers.swift -o %t/OpenHelpers.swiftmodule
// RUN: %target-typecheck-verify-swift -I %t
import OpenHelpers
/**** General structural limitations on open. ****/
open private class OpenIsNotCompatibleWithPrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}}
open fileprivate class OpenIsNotCompatibleWithFilePrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}}
open internal class OpenIsNotCompatibleWithInternal {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}}
open public class OpenIsNotCompatibleWithPublic {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}}
open open class OpenIsNotCompatibleWithOpen {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}}
open typealias OpenIsNotAllowedOnTypeAliases = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}}
open struct OpenIsNotAllowedOnStructs {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}}
open enum OpenIsNotAllowedOnEnums_AtLeastNotYet {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}}
/**** Open entities are at least public. ****/
func foo(object: ExternalOpenClass) {
object.openMethod()
object.openProperty += 5
object[MarkerForOpenSubscripts()] += 5
}
/**** Open classes. ****/
open class ClassesMayBeDeclaredOpen {}
class ExternalSuperClassesMustBeOpen : ExternalNonOpenClass {} // expected-error {{cannot inherit from non-open class 'ExternalNonOpenClass' outside of its defining module}}
class ExternalSuperClassesMayBeOpen : ExternalOpenClass {}
class NestedClassesOfPublicTypesAreOpen : ExternalStruct.OpenClass {}
// This one is hard to diagnose.
class NestedClassesOfInternalTypesAreNotOpen : ExternalInternalStruct.OpenClass {} // expected-error {{use of undeclared type 'ExternalInternalStruct'}}
class NestedPublicClassesOfOpenClassesAreNotOpen : ExternalOpenClass.PublicClass {} // expected-error {{cannot inherit from non-open class 'ExternalOpenClass.PublicClass' outside of its defining module}}
open final class ClassesMayNotBeBothOpenAndFinal {} // expected-error {{class cannot be declared both 'final' and 'open'}}
public class NonOpenSuperClass {} // expected-note {{superclass is declared here}}
open class OpenClassesMustHaveOpenSuperClasses : NonOpenSuperClass {} // expected-error {{superclass 'NonOpenSuperClass' of open class must be open}}
/**** Open methods. ****/
open class AnOpenClass {
open func openMethod() {}
open var openVar: Int = 0
open typealias MyInt = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}}
open subscript(_: MarkerForOpenSubscripts) -> Int {
return 0
}
}
internal class NonOpenClassesCanHaveOpenMembers {
open var openVar: Int = 0;
open func openMethod() {}
}
class SubClass : ExternalOpenClass {
override func openMethod() {}
override var openProperty: Int { get{return 0} set{} }
override subscript(index: MarkerForOpenSubscripts) -> Int {
get { return 0 }
set {}
}
override func nonOpenMethod() {} // expected-error {{overriding non-open instance method outside of its defining module}}
override var nonOpenProperty: Int { get{return 0} set{} } // expected-error {{overriding non-open property outside of its defining module}}
override subscript(index: MarkerForNonOpenSubscripts) -> Int { // expected-error {{overriding non-open subscript outside of its defining module}}
get { return 0 }
set {}
}
}
open class ValidOpenSubClass : ExternalOpenClass {
public override func openMethod() {}
public override var openProperty: Int { get{return 0} set{} }
public override subscript(index: MarkerForOpenSubscripts) -> Int {
get { return 0 }
set {}
}
}
open class InvalidOpenSubClass : ExternalOpenClass {
internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-11=open}}
internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding property must be as accessible as the declaration it overrides}} {{3-11=open}}
internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-11=open}}
get { return 0 }
set {}
}
}
open class OpenSubClassFinalMembers : ExternalOpenClass {
final public override func openMethod() {}
final public override var openProperty: Int { get{return 0} set{} }
final public override subscript(index: MarkerForOpenSubscripts) -> Int {
get { return 0 }
set {}
}
}
open class InvalidOpenSubClassFinalMembers : ExternalOpenClass {
final internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{9-17=public}}
final internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding property must be as accessible as its enclosing type}} {{9-17=public}}
final internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{9-17=public}}
get { return 0 }
set {}
}
}
public class PublicSubClass : ExternalOpenClass {
public override func openMethod() {}
public override var openProperty: Int { get{return 0} set{} }
public override subscript(index: MarkerForOpenSubscripts) -> Int {
get { return 0 }
set {}
}
}
// The proposal originally made these invalid, but we changed our minds.
open class OpenSuperClass {
public func publicMethod() {}
public var publicProperty: Int { return 0 }
public subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 }
}
open class OpenSubClass : OpenSuperClass {
open override func publicMethod() {}
open override var publicProperty: Int { return 0 }
open override subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 }
}
| apache-2.0 | 2846e7b39c0862b90cdbd421d4b8b5a7 | 45.558824 | 203 | 0.747631 | 4.348901 | false | false | false | false |
mubstimor/smartcollaborationvapor | Sources/App/Controllers/SmartController.swift | 1 | 13478 | //
// SmartController.swift
// SmartCollaborationVapor
//
// Created by Timothy Mubiru on 28/02/2017.
//
//
import Vapor
import HTTP
import VaporPostgreSQL
import Foundation
final class SmartController{
func addRoutes(drop: Droplet){
let api_home = drop.grouped(BasicAuthMiddleware(), StaticInfo.protect).grouped("api")
api_home.get(handler: index)
api_home.get("dbversion", handler: dbversion)
api_home.post("name", handler: postName)
api_home.post("clubinjuries", handler: clubInjuries)
api_home.post("clubinjury_trends", handler: clubInjuryTrends)
api_home.get("appointments", handler: appointments)
api_home.get("fixtures_today", handler: get_todays_fixtures)
api_home.post("club_subscription", handler: create_club_subscription)
api_home.post("paymentupdates", handler: processPayments)
api_home.post("updatepackage", handler: updatePackage)
api_home.post("club_appointments", handler: clubSpecialistAppointments)
api_home.post("specialist_details", handler: specialistDetails)
}
func dbversion(request: Request) throws -> ResponseRepresentable{
if let db = drop.database?.driver as? PostgreSQLDriver{
let version = try db.raw("SELECT version()")
return try JSON(node: version)
}else{
return "NO DB Connection"
}
}
func postName(request: Request) throws -> ResponseRepresentable{
guard let name = request.data["name"]?.string else{
throw Abort.badRequest
}
return try JSON(node:[
"message":"Hello \(name)"
])
}
func specialistDetails(request: Request) throws -> ResponseRepresentable{
guard let specialist_id = request.data["specialist_id"]?.string else{
throw Abort.badRequest
}
let specialist = try Specialist.query().filter("id", specialist_id).first()
let club = try Club.query().filter("id", (specialist?.club_id)!).first()
let specialist_club = club?.name
let subscription = try Subscription.query().filter("club_id", (specialist?.club_id)!).first()
let club_package = subscription?.package
let payment_id = subscription?.payment_id
let response = try Node(node: [
"club": specialist_club,
"package": club_package,
"payment_id": payment_id,
"specialist": specialist
])
return try JSON(response.makeNode())
}
func clubInjuries(request: Request) throws -> ResponseRepresentable{
guard let club_id = request.data["club_id"]?.string else{
throw Abort.badRequest
}
let injuries = try Injury.query()
.union(Player.self)
.filter(Player.self, "club_id", .in, [club_id]).all()
return try JSON(injuries.makeNode())
}
func clubInjuryTrends(request: Request) throws -> ResponseRepresentable{
guard let club_id = request.data["club_id"]?.string else{
throw Abort.badRequest
}
let injuries = try Injury.query()
.union(Player.self)
.filter(Player.self, "club_id", .in, [club_id]).all()
let sortedInjuryList = injuries.sorted(by: { Date().convertFullStringToDate(dateString: $0.time_of_injury) < Date().convertFullStringToDate(dateString: $1.time_of_injury) })
// let index = str.index(str.startIndex, offsetBy: 5)
// str.substring(to: index)
let groupedData = sortedInjuryList.group(by: { $0.time_of_injury.substring(to: ($0.time_of_injury.index(($0.time_of_injury.startIndex), offsetBy: 7))) })
var response:[Node] = []
var result: [String: Int] = [:]
for set in groupedData {
result[set.key] = set.value.count
let object = try Node(node: [
"period": set.key,
"total": set.value.count
])
response += object
}
print("response data \(result)")
// return try JSON(node: ["response": "\(result)" ])
return try JSON(response.makeNode())
}
func clubSpecialistAppointments(request: Request) throws -> ResponseRepresentable{
guard let club_id = request.data["club_id"]?.string else{
throw Abort.badRequest
}
guard let club = try Club.find(club_id) else{
throw Abort.custom(status: .badRequest, message: "Unable to find specialists")
}
let specialists = try club.specialists()
// loop through specialists and add each one's treatments to response
var specialist_treatments:[Treatment] = []
var response: [Node] = []
for(specialist) in specialists {
var playerName = ""
var injuryName = ""
print(specialist.name)
let treatments = try specialist.treatments()
for treatment in treatments {
// print("injury id = ")
// print(treatment.injury_id!)
let injuryId = treatment.injury_id!
let injury = try Injury.find(injuryId)
injuryName = (injury?.name)!
// print("player from injury \((injury?.player_id)!)")
let player = try Player.find((injury?.player_id)!)
// print("Player name: \(player?.name)")
playerName = (player?.name)!
let specialist_id = treatment.specialist_id
let specialist = try Specialist.find(specialist_id!)
// compare dates
let today = Date().getCurrentDate()
let app_time = treatment.next_appointment
// print("today is \(today)")
// print("APP TIME is \(app_time)")
let appointment_time = Date().convertStringToDate(dateString: app_time)
let now = Date().convertStringToDate(dateString: today)
if appointment_time < now {
continue
}
let object = try Node(node: [
"player": playerName,
// "treatment": treatment,
"specialist": specialist?.name,
"injury": injuryName,
"appointment_time": app_time
])
response += object
}
specialist_treatments += treatments
}
// let injuries = try Injury.query()
// .union(Player.self)
// .filter(Player.self, "club_id", .in, [club_id]).all()
return try JSON(response.makeNode())
}
// assign user to default subscription package
func create_club_subscription(request: Request) throws -> ResponseRepresentable{
/*
guard let club_id = request.data["club_id"]?.string else{
throw Abort.badRequest
} */
guard let email = request.data["email"]?.string else{
throw Abort.badRequest
}
// if user is the first to register from a given club, create a sub package for them
//if try Specialist.query().filter("club_id", club_id).first() == nil {
let dictionary:Node = [
"email": Node.string(email)
]
// send request to stripe server
let stripeResponse = try drop.client.post("https://smartcollaborationstripe.herokuapp.com/customer.php", headers: [
"Content-Type": "application/x-www-form-urlencoded"
], body: Body.data( Node(dictionary).formURLEncoded()))
return try JSON(node:[
"message": stripeResponse.json!
])
//}else{
// return try JSON(node:[
// "message":"Unable to create package"
// ])
//}
}
func processPayments(request: Request) throws -> ResponseRepresentable{
guard let customer_id = request.data["customer_id"]?.string else{
throw Abort.badRequest
}
guard let amount = request.data["amount"]?.string else{
throw Abort.badRequest
}
guard let status = request.data["status"]?.string else{
throw Abort.badRequest
}
guard var subscription = try Subscription.query().filter("payment_id", customer_id).first() else{
throw Abort.custom(status: .badRequest, message: "Unable to find subscription")
}
// update returned subscription object
subscription.amount_paid = Double(amount)!
subscription.status = status
try subscription.save()
return try JSON(subscription.makeNode())
}
func updatePackage(request: Request) throws -> ResponseRepresentable{
guard let customer_id = request.data["payment_id"]?.string else{
throw Abort.badRequest
}
guard let amount = request.data["amount_paid"]?.string else{
throw Abort.badRequest
}
guard let date_paid = request.data["date_paid"]?.string else{
throw Abort.badRequest
}
guard let next_payment = request.data["date_of_next_payment"]?.string else{
throw Abort.badRequest
}
guard let status = request.data["status"]?.string else{
throw Abort.badRequest
}
guard let sub_package = request.data["package"]?.string else{
throw Abort.badRequest
}
var subscription = try Subscription.query().filter("payment_id", customer_id).first()
// update returned subscription object
subscription?.amount_paid = Double(amount)!
subscription?.status = status
subscription?.date_of_next_payment = next_payment
subscription?.date_paid = date_paid
subscription?.package = sub_package
try subscription?.save()
return try JSON(subscription!.makeNode())
}
func appointments(request: Request) throws -> ResponseRepresentable{
let appointments = try Treatment.query().union(Injury.self)
.union(Specialist.self).all()
return try JSON(appointments.makeNode())
}
func get_todays_fixtures(request: Request) throws -> ResponseRepresentable{
// guard let game_date = request.data["game_date"]?.string else{
// throw Abort.badRequest
// }
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "yyyy-MM-dd"
let today = dateFormatter.string(from: currentDate) // use current date
let fixture = try Fixture.query().filter("game_date", today).all()
return try JSON(fixture.makeNode())
}
func index(request: Request) throws -> ResponseRepresentable{
return try JSON(node: [
"message": "Hello, welcome!"
])
}
}
extension Date {
/*
* Based on http://stackoverflow.com/questions/36861732/swift-convert-string-to-date
*/
func getCurrentDate() -> String{
// get current date
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let date_of_treatment = dateFormatter.string(from: currentDate) // use current time
return date_of_treatment
}
func convertStringToDate(dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
print("received \(dateString)")
let newDate = dateFormatter.date(from: dateString)
// print("date is \(newDate)")
return newDate!
}
func convertFullStringToDate(dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("received \(dateString)")
let newDate = dateFormatter.date(from: dateString)
// print("date is \(newDate)")
return newDate!
}
}
/*
* categorise data based on
* http://stackoverflow.com/questions/31220002/how-to-group-by-the-elements-of-an-array-in-swift
*/
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
}
}
| mit | 61e54d8c33e5465e284848139d4997ac | 33.121519 | 181 | 0.556908 | 4.709294 | false | false | false | false |
jegumhon/URWeatherView | URWeatherView/Effect/UREffectLightningNode.swift | 1 | 6690 | //
// UREffectLightningNode.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 5. 26..
// Copyright © 2017년 zigbang. All rights reserved.
//
import SpriteKit
/// the default is .topLeft
enum UREffectLigthningPosition {
case `default`
case topLeft
case topCenter
case topRight
case centerLeft
case centerRight
case bottomLeft
case bottomCenter
case bottomRight
var position: CGPoint {
switch self {
case .topLeft:
return CGPoint(x: 0.0, y: 1.0)
case .topCenter:
return CGPoint(x: 0.5, y: 1.0)
case .topRight:
return CGPoint(x: 1.0, y: 1.0)
case .centerLeft:
return CGPoint(x: 0.0, y: 0.5)
case .centerRight:
return CGPoint(x: 1.0, y: 0.5)
case .bottomLeft:
return CGPoint(x: 0.0, y: 0.0)
case .bottomCenter:
return CGPoint(x: 0.5, y: 0.0)
case .bottomRight:
return CGPoint(x: 1.0, y: 0.0)
default:
return CGPoint(x: 0.0, y: 1.0)
}
}
}
public struct UREffectLightningOption: UREffectOption {
var timeIntervalBetweenLightning = 0.15
var lightningLifetimeCoefficient = 0.1
var lightningDisappeartime = 0.2
var lineDrawDelay = 0.00275
var lineThickness = 1.3
var branchDepthLimit: Int = 3
// 0.0 - the bolt will be a straight line. >1.0 - the bolt will look unnatural
let displaceCoefficient = 0.25
// Make bigger if you want bigger line lenght and vice versa
let lineRangeCoefficient = 1.8
public init(lineThickness: Double = 1.3) {
self.lineThickness = lineThickness
}
}
class UREffectLigthningNode: SKSpriteNode {
var option: UREffectLightningOption = UREffectLightningOption()
private var _startPoint: CGPoint = .zero
private var startPoint: CGPoint {
get {
return self._startPoint
}
set {
self._startPoint = CGPoint(x: self.size.width * newValue.x, y: self.size.height * newValue.y)
}
}
private var _endPoint: CGPoint = .zero
private var endPoint: CGPoint {
get {
return self._endPoint
}
set {
self._endPoint = CGPoint(x: self.size.width * newValue.x, y: self.size.height * newValue.y)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init(frame: CGRect, startPosition: UREffectLigthningPosition = .default, targetPosition: UREffectLigthningPosition = .bottomRight) {
self.init(texture: nil, color: .clear, size: frame.size)
self.anchorPoint = .zero
self.position = frame.origin
self.startPoint = startPosition.position
self.endPoint = targetPosition.position
}
func startLightning(isInfinite: Bool = false) {
let wait = SKAction.wait(forDuration: self.option.timeIntervalBetweenLightning)
let addLightning = SKAction.run {
self.addLightning()
}
// draw lightning
if !isInfinite {
self.run(SKAction.sequence([addLightning, wait]), withKey: "lightning")
} else {
self.run(SKAction.repeatForever(SKAction.sequence([addLightning, wait])), withKey: "lightning")
}
}
func stopLightning() {
self.removeAction(forKey: "lightning")
}
var bolts: [UREffectLightningBoltNode] = [UREffectLightningBoltNode]()
func addLightning() {
let mainBolt = UREffectLightningBoltNode(start: self.startPoint, end: self.endPoint)
self.bolts.append(mainBolt)
self.addChild(mainBolt)
self.addLightningBranch(parentBolt: mainBolt)
}
func addLightningBranch(parentBolt: UREffectLightningBoltNode) {
let branchDepth = parentBolt.depth + 1
if branchDepth < parentBolt.option.branchDepthLimit {
let numberOfBranches: Int = Int(arc4random_uniform(3))
var branchPositions: [Double] = [Double](repeating: 0.0, count: numberOfBranches)
for i in 0 ..< numberOfBranches {
branchPositions[i] = drand48()
}
for i in 0 ..< branchPositions.count {
let branchPosition = branchPositions[i]
guard let branchStartPoint: CGPoint = parentBolt.pointOnBoltPath(position: branchPosition) else { break }
// 30도 각도 * (index % 2) == 0 ? 1 : -1 -> radian으로 바꿔서, z축 기준으로 회전을 얻어온 후, 메인 번개에 해당 브랜치 번개 시작점부터 종료점까지 회전을 적용해서 브랜치 번개의 종료 목표 CGPoint를 얻는다.
let degreeOfBranch: CGFloat = 30.0 * ((i % 2) == 0 ? 1 : -1)
let branchEndPoint = parentBolt.endPoint.rotateAround(point: branchStartPoint, degree: degreeOfBranch)
// 시작 점과 종료 점으로 bolt를 추가로 생성한다.
let branchBolt = UREffectLightningBoltNode(start: branchStartPoint, end: branchEndPoint, option: UREffectLightningOption(lineThickness: parentBolt.option.lineThickness * 0.6))
branchBolt.depth = branchDepth
self.bolts.append(branchBolt)
self.addChild(branchBolt)
self.addLightningBranch(parentBolt: branchBolt)
}
}
}
}
extension CGPoint {
func rotateAround(point: CGPoint, degree: CGFloat) -> CGPoint {
// translation to the zero point
let translationToPoint = CGAffineTransform(translationX: -point.x, y: -point.y)
let rotationByDegree = CGAffineTransform(rotationAngle: degree.degreesToRadians)
let translationRollback = CGAffineTransform(translationX: point.x, y: point.y)
return self.applying(translationToPoint.concatenating(rotationByDegree).concatenating(translationRollback))
}
func rotateAround(point: CGPoint, angle: CGFloat) -> CGPoint {
// translation to the zero point
let translationToPoint = CGAffineTransform(translationX: -point.x, y: -point.y)
let rotationByAngle = CGAffineTransform(rotationAngle: angle)
let translationRollback = CGAffineTransform(translationX: point.x, y: point.y)
return self.applying(translationToPoint.concatenating(rotationByAngle).concatenating(translationRollback))
}
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
| mit | 19254de76b78c2d942bde59bed2e63f7 | 33.172775 | 191 | 0.638119 | 3.989609 | false | false | false | false |
andrzejsemeniuk/ASToolkit | ASToolkit/Variable.swift | 1 | 9684 | //
// Variable.swift
// ASToolkit
//
// Created by andrzej semeniuk on 7/13/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
public protocol Variable {
var value : Double { get set }
}
public protocol VariableWithDefaultValue : Variable {
var value0 : Double { get }
}
public protocol VariableWithRange : Variable {
var lowerbound : Double { get }
var upperbound : Double { get }
var range : Double { get }
}
public class VariableWithImmutableRange : VariableWithRange
{
// enabled?
// fixed?
// priority?
public let lowerbound : Double
public let upperbound : Double
public let range : Double
public var value : Double {
didSet {
if value < lowerbound {
value = lowerbound
}
else if upperbound < value {
value = upperbound
}
}
}
public var lerp : Double {
return range != 0 ? value.lerp(from:lowerbound, to:upperbound) : 0
}
public var description : String { return "[\(lowerbound),\(upperbound)=\(value)]" }
public init (lowerbound l:Double, upperbound u:Double, value v:Double)
{
self.lowerbound = min(l,u)
self.upperbound = max(l,u)
self.range = upperbound-lowerbound
self.value = max(lowerbound,min(upperbound,v))
}
public convenience init (_ lowerbound:Double, _ upperbound:Double, _ value:Double)
{
self.init(lowerbound:lowerbound, upperbound:upperbound, value:value)
}
public func set (value:Double) { self.value = value }
public func setValueTo (_ value:Double) { self.value = value }
public func setValueFrom (ratio:Double) { self.value = lowerbound+ratio*range }
public func setValueToLowerbound() { self.value = lowerbound }
public func setValueToUpperbound() { self.value = upperbound }
}
public class Variable01 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:1,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable02 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:2,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable03 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:3,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable010 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:10,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable0100 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:100,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable01000 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:0,upperbound:1000,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable0n : VariableWithImmutableRange
{
public init(n:Double,value v:Double = 0) {
super.init(lowerbound:0,upperbound:max(0,n),value:v)
}
public init(upperbound n:Double,value v:Double = 0) {
super.init(lowerbound:0,upperbound:max(0,n),value:v)
}
}
typealias VariableZeroToUpperbound = Variable0n
typealias VariableZeroToN = Variable0n
public class Variable11 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:-1,upperbound:1,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class Variable22 : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:-2,upperbound:2,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
public class VariableHalfHalf : VariableWithImmutableRange
{
public init(_ v:Double = 0) { super.init(lowerbound:-0.5,upperbound:0.5,value:v) }
public convenience init(value:Double = 0) { self.init(value) }
}
typealias VariableHH = VariableHalfHalf
public class VariableNN : VariableWithImmutableRange
{
public init(_ N:Double, _ v:Double = 0) { super.init(lowerbound:-abs(N),upperbound:abs(N),value:v) }
public convenience init(N:Double, value:Double = 0) { self.init(N, value) }
}
public class VariableWithMutableRange : VariableWithRange
{
public var lowerbound : Double {
didSet {
if value < lowerbound {
value = lowerbound
}
}
}
public var upperbound : Double {
didSet {
if upperbound < value {
value = upperbound
}
}
}
public var range : Double {
return upperbound - lowerbound
}
public var value : Double {
didSet {
if value < lowerbound {
value = lowerbound
}
else if upperbound < value {
value = upperbound
}
}
}
public var lerp : Double {
return range != 0 ? value.lerp(from:lowerbound, to:upperbound) : 0
}
public var description : String { return "[\(lowerbound),\(upperbound)=\(value)]" }
public init (lowerbound l:Double, upperbound u:Double, value v:Double)
{
self.lowerbound = min(l,u)
self.upperbound = max(l,u)
self.value = max(lowerbound,min(upperbound,v))
}
public convenience init (_ lowerbound:Double,_ upperbound:Double,_ value:Double)
{
self.init(lowerbound:lowerbound,upperbound:upperbound,value:value)
}
public func set (value:Double) { self.value = value }
public func setValueTo (_ value:Double) { self.value = value }
public func setValueFrom (ratio:Double) { self.value = lowerbound+ratio*range }
public func setValueToLowerbound() { self.value = lowerbound }
public func setValueToUpperbound() { self.value = upperbound }
public func set (lowerbound l:Double,upperbound u:Double,value v:Double) {
self.lowerbound = min(l,u)
self.upperbound = max(l,u)
self.value = v
}
public func set (lowerbound l:Double,upperbound u:Double) {
let v = self.value
self.lowerbound = min(l,u)
self.upperbound = max(l,u)
self.value = v
}
}
public class VariableWithImmutableRangeAndDefaultValue : VariableWithImmutableRange, VariableWithDefaultValue {
public let value0 : Double
override public init (lowerbound:Double, upperbound:Double, value:Double)
{
self.value0 = value
super.init(lowerbound: lowerbound, upperbound: upperbound, value: value)
}
public init (lowerbound:Double, upperbound:Double, value0:Double, value:Double)
{
self.value0 = value0
super.init(lowerbound: lowerbound, upperbound: upperbound, value: value)
}
public convenience init (_ lowerbound:Double, _ upperbound:Double,_ value:Double)
{
self.init(lowerbound:lowerbound,upperbound:upperbound,value:value)
}
public convenience init (_ lowerbound:Double, _ upperbound:Double, _ value0:Double, _ value:Double)
{
self.init(lowerbound:lowerbound, upperbound:upperbound, value0:value0, value:value)
}
}
public class VariableWithMutableRangeAndDefaultValue : VariableWithMutableRange, VariableWithDefaultValue {
public let value0 : Double
override public init (lowerbound:Double, upperbound:Double, value:Double)
{
self.value0 = value
super.init(lowerbound: lowerbound, upperbound: upperbound, value: value)
}
public init (lowerbound:Double, upperbound:Double, value0:Double, value:Double)
{
self.value0 = value0
super.init(lowerbound: lowerbound, upperbound: upperbound, value: value)
}
public convenience init (_ lowerbound:Double, _ upperbound:Double,_ value:Double)
{
self.init(lowerbound:lowerbound,upperbound:upperbound,value:value)
}
public convenience init (_ lowerbound:Double, _ upperbound:Double, _ value0:Double, _ value:Double)
{
self.init(lowerbound:lowerbound, upperbound:upperbound, value0:value0, value:value)
}
}
| mit | 6341e9e5ecd5a9db94103a910df81259 | 32.389655 | 139 | 0.569865 | 4.250658 | false | false | false | false |
swift-lang/swift-k | tests/stress/IO/beagle/stage_from_remoteNx2.swift | 2 | 475 | type file;
file script <"filemaker.sh">;
app (file out, file log) remote_driver (file run, int size)
{
bash @run size @out stdout=@filename(log);
}
file driver_out[] <simple_mapper; prefix="driver", suffix=".out">;
file driver_log[] <simple_mapper; prefix="driver", suffix=".log">;
int filesize = @toInt(@arg("size","10"));
int loop = @toInt(@arg("loops","0"));
foreach item,i in [0:loop] {
(driver_out[i], driver_log[i]) = remote_driver(script, filesize);
} | apache-2.0 | bf0b5094359c0e72a5fb1e6f221ab8b1 | 27 | 73 | 0.644211 | 3.084416 | false | false | true | false |
zhxnlai/ZLSwipeableViewSwift | ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/MenuTableViewController.swift | 1 | 2521 | //
// MenuTableViewController.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 5/25/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
let demoViewControllers = [("Default", ZLSwipeableViewController.self),
("Custom Animation", CustomAnimationDemoViewController.self),
("Custom Swipe", CustomSwipeDemoViewController.self),
("Allowed Direction", CustomDirectionDemoViewController.self),
("History", HistoryDemoViewController.self),
("Previous View", PreviousViewDemoViewController.self),
("Should Swipe", ShouldSwipeDemoViewController.self),
("Always Swipe", AlwaysSwipeDemoViewController.self)]
override func viewDidLoad() {
super.viewDidLoad()
title = "ZLSwipeableView"
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoViewControllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = String(format: "s%li-r%li", indexPath.section, indexPath.row)
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.text = titleForRowAtIndexPath(indexPath)
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let title = titleForRowAtIndexPath(indexPath)
let vc = viewControllerForRowAtIndexPath(indexPath)
vc.title = title
navigationController?.pushViewController(vc, animated: true)
}
func titleForRowAtIndexPath(_ indexPath: IndexPath) -> String {
let (title, _) = demoViewControllers[indexPath.row]
return title
}
func viewControllerForRowAtIndexPath(_ indexPath: IndexPath) -> ZLSwipeableViewController {
let (_, vc) = demoViewControllers[indexPath.row]
return vc.init()
}
}
| mit | f50dbc2f6e01fb676ddfa05d09cbaad3 | 38.390625 | 109 | 0.643792 | 5.78211 | false | false | false | false |
kaneshin/IcoMoonKit | Source/IcoMoonKit.swift | 1 | 6385 | // IcoMoonKit.swift
//
// Copyright (c) 2015 Shintaro Kaneko
//
// 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
#if os(iOS)
import UIKit
#else
import AppKit
#endif
import CoreText
typealias GlyphString = NSMutableAttributedString
extension GlyphString {
private var range: NSRange {
return NSMakeRange(0, self.length ?? 0)
}
private func attributedText() -> NSAttributedString {
return self.copy() as! NSAttributedString
}
private func attribute(attrName: String) -> AnyObject? {
return self.attribute(attrName, atIndex: 0, effectiveRange: nil)
}
private func addAttribute(name: String, value: AnyObject) {
self.addAttribute(name, value: value, range: self.range)
}
private func removeAttribute(name: String) {
self.removeAttribute(name, range: self.range)
}
}
public class Glyph: NSObject {
private var glyphString: GlyphString?
public var attributedText: NSAttributedString? {
return self.glyphString?.attributedText()
}
public var code: String? {
return self.glyphString?.string
}
public var font: Font? {
return self.glyphString?.attribute(FontAttributeName) as? Font
}
public var size: CGFloat {
return self.font?.pointSize ?? 0
}
public var color: Color? {
didSet {
self.glyphString?.removeAttribute(ForegroundColorAttributeName)
self.glyphString?.addAttribute(ForegroundColorAttributeName, value: self.color!)
}
}
public var backgroundColor: Color? {
didSet {
self.glyphString?.removeAttribute(BackgroundColorAttributeName)
self.glyphString?.addAttribute(BackgroundColorAttributeName, value: self.backgroundColor!)
}
}
public var image: Image {
return self.image(size: CGSize(width: self.size, height: self.size))
}
/**
Designated Initializer
Creates glyph instance with setting character code, size and color.
:param: code
:param: size
:param: color
*/
public init(code: String, size: CGFloat, color: Color) {
super.init()
self.setup(font: self.font(size: size), code: code, color: color)
}
convenience public init(code: String, size: CGFloat) {
self.init(code: code, size: size, color: Color.blackColor())
}
/**
Set attributes for a glyph.
:param: font
:param: code
:param: color
*/
private func setup(#font: Font, code: String, color: Color) {
let attributes = [
BackgroundColorAttributeName: Color.clearColor(),
FontAttributeName: font,
ForegroundColorAttributeName: color
]
self.glyphString = NSMutableAttributedString(string: code, attributes: attributes)
}
private func setup(#font: Font, code: String) {
self.setup(font: font, code: code, color: self.color!)
}
// MARK: - Sets Glyph Font
public func fontName() -> String {
assert(false, "ERROR: [\(__FUNCTION__)] => This method must be overridden in subclasse.")
return ""
}
public func fontResource() -> (String, NSBundle?) {
assert(false, "ERROR: [\(__FUNCTION__)] => This method must be overridden in subclasse.")
return ("", nil)
}
private func font(#size: CGFloat) -> Font {
if let font = Font(name: self.fontName(), size: size) as Font? {
return font
}
var (resource, bundle) = self.fontResource()
bundle = bundle ?? NSBundle.mainBundle()
let filename = resource.stringByDeletingPathExtension
let ext = resource.pathExtension
let url = bundle!.URLForResource(filename, withExtension: ext)
Glyph.registerGraphicsFont(url)
return font(size: size)
}
private class func registerGraphicsFont(url: NSURL?) {
assert(url != nil, "Font file doesn't exist.")
let fontDataProvider = CGDataProviderCreateWithURL(url)
let font = CGFontCreateWithDataProvider(fontDataProvider)
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
println(error)
}
}
/**
Creates an image of the glyph.
:param: size The size of the image.
:returns: An image of the glyph.
*/
public func image(#size: CGSize) -> Image {
#if os(iOS)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
let glyphSize = self.glyphString!.size()
#else
var glyphImage = NSImage(size: size)
glyphImage.lockFocus()
let context = NSGraphicsContext.currentContext()?.graphicsPort
let glyphSize = self.glyphString!.size
#endif
let offsetX = 0.5 * (size.width - glyphSize.width)
let offsetY = 0.5 * (size.height - glyphSize.height)
let offset = CGPointMake(offsetX, offsetY)
let rect = CGRect(origin: offset, size: size)
self.glyphString!.drawInRect(rect)
#if os(iOS)
var glyphImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
#else
// glyphImage.unlockFocus()
#endif
return glyphImage
}
}
| mit | a34cc99ebb43078d0d7944b32c9cf16b | 31.085427 | 102 | 0.652467 | 4.65379 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/Calculator/VCalculator.swift | 1 | 5520 | import UIKit
class VCalculator:VView
{
weak var viewHistory:VCalculatorHistory!
weak var viewText:VCalculatorText!
weak var viewFunctions:VCalculatorFunctions!
private weak var controller:CCalculator!
private weak var viewBar:VCalculatorBar!
private weak var layoutTextHeight:NSLayoutConstraint!
private weak var layoutBarBottom:NSLayoutConstraint!
private let kBarHeight:CGFloat = 48
private let kFunctionsHeight:CGFloat = 86
private let kHistoryTop:CGFloat = 1
private let kTextMaxHeight:CGFloat = 125
private let kTextMinHeight:CGFloat = 65
private let kTextBorderHeight:CGFloat = 1
private let kAnimationDuration:TimeInterval = 0.35
private let kAnimationFastDuration:TimeInterval = 0.1
override init(controller:CController)
{
super.init(controller:controller)
self.controller = controller as? CCalculator
let viewBar:VCalculatorBar = VCalculatorBar(
controller:self.controller)
self.viewBar = viewBar
let viewText:VCalculatorText = VCalculatorText(
controller:self.controller)
self.viewText = viewText
let viewHistory:VCalculatorHistory = VCalculatorHistory(
controller:self.controller)
self.viewHistory = viewHistory
let viewFunctions:VCalculatorFunctions = VCalculatorFunctions(
controller:self.controller)
self.viewFunctions = viewFunctions
let textBorder:VBorder = VBorder(color:UIColor.black)
addSubview(textBorder)
addSubview(viewHistory)
addSubview(viewText)
addSubview(viewFunctions)
addSubview(viewBar)
layoutBarBottom = NSLayoutConstraint.bottomToBottom(
view:viewBar,
toView:self)
NSLayoutConstraint.height(
view:viewBar,
constant:kBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:self)
NSLayoutConstraint.topToTop(
view:viewText,
toView:self)
layoutTextHeight = NSLayoutConstraint.height(
view:viewText)
NSLayoutConstraint.equalsHorizontal(
view:viewText,
toView:self)
NSLayoutConstraint.topToBottom(
view:viewHistory,
toView:viewText,
constant:kHistoryTop)
NSLayoutConstraint.bottomToTop(
view:viewHistory,
toView:viewBar)
NSLayoutConstraint.equalsHorizontal(
view:viewHistory,
toView:self)
NSLayoutConstraint.height(
view:viewFunctions,
constant:kFunctionsHeight)
NSLayoutConstraint.bottomToTop(
view:viewFunctions,
toView:viewBar)
NSLayoutConstraint.equalsHorizontal(
view:viewFunctions,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:textBorder,
toView:viewText)
NSLayoutConstraint.height(
view:textBorder,
constant:kTextBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:textBorder,
toView:self)
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedKeyboardChanged(sender:)),
name:NSNotification.Name.UIKeyboardWillChangeFrame,
object:nil)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
//MARK: notifications
func notifiedKeyboardChanged(sender notification:Notification)
{
guard
let userInfo:[AnyHashable:Any] = notification.userInfo,
let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue
else
{
return
}
let keyRect:CGRect = keyboardFrameValue.cgRectValue
let yOrigin = keyRect.origin.y
let height:CGFloat = bounds.maxY
let keyboardHeight:CGFloat
if yOrigin < height
{
keyboardHeight = height - yOrigin
}
else
{
keyboardHeight = 0
}
layoutBarBottom.constant = -keyboardHeight
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
//MARK: private
private func resizeField()
{
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let textHeight:CGFloat
if height >= width
{
textHeight = kTextMaxHeight
}
else
{
textHeight = kTextMinHeight
}
layoutTextHeight.constant = textHeight
UIView.animate(
withDuration:kAnimationFastDuration,
animations:
{ [weak self] in
self?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
let _:Bool? = self?.viewText.becomeFirstResponder()
}
}
//MARK: public
func viewAppeared()
{
resizeField()
viewFunctions.refresh()
}
func orientationChange()
{
resizeField()
}
}
| mit | 500241f1dbfd45fc837b4340fd81f8f1 | 26.738693 | 96 | 0.588406 | 5.661538 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteAuth/route.AuthUpdateEmail.swift | 1 | 4572 | import Foundation
import PerfectLib
import PerfectHTTP
import OpenbuildExtensionCore
import OpenbuildExtensionPerfect
import OpenbuildMysql
import OpenbuildRepository
import OpenbuildRouteRegistry
import OpenbuildSingleton
public class RequestAuthUpdateEmail: OpenbuildExtensionPerfect.RequestProtocol {
public var method: String
public var uri: String
public var description: String = "Allows the user to update their email address."
public var validation: OpenbuildExtensionPerfect.RequestValidation
public init(method: String, uri: String){
self.method = method
self.uri = uri
self.validation = OpenbuildExtensionPerfect.RequestValidation()
self.validation.addValidators(validators: [
ValidateBodyUsername,
ValidateBodyEmail,
ValidateBodyPassword,
ValidateBodyNewEmail
])
}
}
public let handlerRouteAuthUpdateEmail = { (request: HTTPRequest, response: HTTPResponse) in
guard let handlerResponse = RouteRegistry.getHandlerResponse(
uri: request.path.lowercased(),
method: request.method,
response: response
) else {
return
}
do {
var repository = try RepositoryAuth()
guard let user = try repository.getByUsernameEmailPassword(
username: request.validatedRequestData?.validated["username"] as! String,
email: request.validatedRequestData?.validated["email"] as! String,
password: request.validatedRequestData?.validated["password"] as! String
) else {
//422 Unprocessable Entity
handlerResponse.complete(
status: 422,
model: ResponseModel422(
validation: request.validatedRequestData!,
messages: [
"invalid_login": true,
"message": "username/password not found."
]
)
)
return
}
if user.passwordUpdate {
//422 Unprocessable Entity - requires a password update
handlerResponse.complete(
status: 422,
model: ResponseModel422(
validation: request.validatedRequestData!,
messages: [
"invalid_login": true,
"message": "Password requires an update.",
"nextUri": "/api/auth/update/password",
"nextMethod": "put"
]
)
)
return
}
let security = OpenbuildSingleton.Manager.getSecurity()
user.email = security.encrypt(
toEncrypt: request.validatedRequestData?.validated["new_email"] as! String
)!
var updatedUser = repository.updateEmail(
model: user
)
if updatedUser.errors.isEmpty {
handlerResponse.complete(
status: 200,
model: ModelAuthUpdateEmail200Messages(messages: [
"updated": true,
"message": "User email has been updated."
])
)
} else {
//422 Unprocessable Entity
handlerResponse.complete(
status: 422,
model: ResponseModel422(
validation: request.validatedRequestData!,
messages: [
"updated": false,
"errors": updatedUser.errors
]
)
)
}
} catch {
print(error)
handlerResponse.complete(
status: 500,
model: ResponseModel500Messages(messages: [
"message": "Failed to generate a successful response."
])
)
}
}
public class RouteAuthUpdateEmail: OpenbuildRouteRegistry.FactoryRoute {
override public func route() -> NamedRoute? {
let handlerResponse = ResponseDefined()
handlerResponse.register(status: 200, model: "RouteAuth.ModelAuthUpdateEmail200Messages")
handlerResponse.register(status: 422)
handlerResponse.register(status: 500)
return NamedRoute(
handlerRequest: RequestAuthUpdateEmail(
method: "put",
uri: "/api/auth/update/email"
),
handlerResponse: handlerResponse,
handlerRoute: handlerRouteAuthUpdateEmail
)
}
} | gpl-2.0 | da17e06c9941c9e352c52c17e4d629d2 | 27.055215 | 97 | 0.565617 | 5.589242 | false | false | false | false |
danfsd/FolioReaderKit | Source/FolioReaderAudioPlayer.swift | 1 | 16981 | //
// FolioReaderAudioPlayer.swift
// FolioReaderKit
//
// Created by Kevin Jantzer on 1/4/16.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
open class FolioReaderAudioPlayer: NSObject {
var isTextToSpeech = false
var synthesizer: AVSpeechSynthesizer!
var playing = false
var player: AVAudioPlayer?
var currentHref: String!
var currentFragment: String!
var currentSmilFile: FRSmilFile!
var currentAudioFile: String!
var currentBeginTime: Double!
var currentEndTime: Double!
var playingTimer: Timer!
var registeredCommands = false
var completionHandler: () -> Void = {}
var utteranceRate: Float = 0
// MARK: Init
override init() {
super.init()
UIApplication.shared.beginReceivingRemoteControlEvents()
// this is needed to the audio can play even when the "silent/vibrate" toggle is on
let session:AVAudioSession = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
updateNowPlayingInfo()
}
deinit {
UIApplication.shared.endReceivingRemoteControlEvents()
}
// MARK: Reading speed
func setRate(_ rate: Int) {
if let player = player {
switch rate {
case 0:
player.rate = 0.5
break
case 1:
player.rate = 1.0
break
case 2:
player.rate = 1.5
break
case 3:
player.rate = 2
break
default:
break
}
updateNowPlayingInfo()
}
if synthesizer != nil {
// Need to change between version IOS
// http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue
if #available(iOS 9, *) {
switch rate {
case 0:
utteranceRate = 0.42
break
case 1:
utteranceRate = 0.5
break
case 2:
utteranceRate = 0.53
break
case 3:
utteranceRate = 0.56
break
default:
break
}
} else {
switch rate {
case 0:
utteranceRate = 0
break
case 1:
utteranceRate = 0.06
break
case 2:
utteranceRate = 0.15
break
case 3:
utteranceRate = 0.23
break
default:
break
}
}
updateNowPlayingInfo()
}
}
// MARK: Play, Pause, Stop controls
func stop(immediate: Bool = false) {
playing = false
if !isTextToSpeech {
if let player = player , player.isPlaying {
player.stop()
}
} else {
stopSynthesizer(immediate: immediate, completion: nil)
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
func stopSynthesizer(immediate: Bool = false, completion: (() -> Void)? = nil) {
synthesizer.stopSpeaking(at: immediate ? .immediate : .word)
completion?()
}
func pause() {
playing = false
if !isTextToSpeech {
if let player = player , player.isPlaying {
player.pause()
}
} else {
if synthesizer.isSpeaking {
synthesizer.pauseSpeaking(at: .word)
}
}
// UIApplication.sharedApplication().idleTimerDisabled = false
}
open func togglePlay() {
isPlaying() ? pause() : play()
}
open func play() {
if book.hasAudio() {
guard let currentPage = FolioReader.sharedInstance.readerCenter?.currentPage else { return }
currentPage.webView.js("playAudio()")
} else {
readCurrentSentence()
}
// UIApplication.sharedApplication().idleTimerDisabled = true
}
open func isPlaying() -> Bool {
return playing
}
/**
Play Audio (href/fragmentID)
Begins to play audio for the given chapter (href) and text fragment.
If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter
*/
func playAudio(_ href: String, fragmentID: String) {
isTextToSpeech = false
stop()
let smilFile = book.smilFileForHref(href)
// if no smil file for this href and the same href is being requested, we've hit the end. stop playing
if smilFile == nil && currentHref != nil && href == currentHref {
return
}
playing = true
currentHref = href
currentFragment = "#"+fragmentID
currentSmilFile = smilFile
// if no smil file, delay for a second, then move on to the next chapter
if smilFile == nil {
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false)
return
}
let fragment = smilFile?.parallelAudioForFragment(currentFragment)
if fragment != nil {
if _playFragment(fragment) {
startPlayerTimer()
}
}
}
func _autoPlayNextChapter() {
// if user has stopped playing, dont play the next chapter
if isPlaying() == false { return }
playNextChapter()
}
func playPrevChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter?.changePageToPrevious {
if self.isPlaying() {
self.play()
} else {
self.pause()
}
}
}
func playNextChapter() {
stopPlayerTimer()
// Wait for "currentPage" to update, then request to play audio
FolioReader.sharedInstance.readerCenter?.changePageToNext {
if self.isPlaying() {
self.play()
}
}
}
/**
Play Fragment of audio
Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects
the audio is out of the fragment timeframe.
*/
@discardableResult fileprivate func _playFragment(_ smil: FRSmilElement!) -> Bool {
if smil == nil {
print("no more parallel audio to play")
stop()
return false
}
let textFragment = smil.textElement().attributes["src"]
let audioFile = smil.audioElement().attributes["src"]
currentBeginTime = smil.clipBegin()
currentEndTime = smil.clipEnd()
// new audio file to play, create the audio player
if player == nil || (audioFile != nil && audioFile != currentAudioFile) {
currentAudioFile = audioFile
let fileURL = currentSmilFile.resource.basePath() + ("/"+audioFile!)
let audioData = try? Data(contentsOf: URL(fileURLWithPath: fileURL))
do {
player = try AVAudioPlayer(data: audioData!)
guard let player = player else { return false }
setRate(FolioReader.sharedInstance.currentAudioRate)
player.enableRate = true
player.prepareToPlay()
player.delegate = self
updateNowPlayingInfo()
} catch {
print("could not read audio file:", audioFile)
return false
}
}
// if player is initialized properly, begin playing
guard let player = player else { return false }
// the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe
// this is done to mitigate milisecond skips in the audio when changing fragments
if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) {
player.currentTime = currentBeginTime;
updateNowPlayingInfo()
}
player.play()
// get the fragment ID so we can "mark" it in the webview
let textParts = textFragment!.components(separatedBy: "#")
let fragmentID = textParts[1];
FolioReader.sharedInstance.readerCenter?.audioMark(href: currentHref, fragmentID: fragmentID)
return true
}
/**
Next Audio Fragment
Gets the next audio fragment in the current smil file, or moves on to the next smil file
*/
fileprivate func nextAudioFragment() -> FRSmilElement! {
let smilFile = book.smilFileForHref(currentHref)
if smilFile == nil { return nil }
let smil = currentFragment == nil ? smilFile?.parallelAudioForFragment(nil) : smilFile?.nextParallelAudioForFragment(currentFragment)
if smil != nil {
currentFragment = smil?.textElement().attributes["src"]
return smil
}
currentHref = book.spine.nextChapter(currentHref)!.href
currentFragment = nil
currentSmilFile = smilFile
if currentHref == nil {
return nil
}
return nextAudioFragment()
}
func playText(_ href: String, text: String) {
isTextToSpeech = true
playing = true
currentHref = href
if synthesizer == nil {
synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
setRate(FolioReader.sharedInstance.currentAudioRate)
}
let utterance = AVSpeechUtterance(string: text)
utterance.rate = utteranceRate
utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language)
if synthesizer.isSpeaking {
stopSynthesizer()
}
synthesizer.speak(utterance)
updateNowPlayingInfo()
}
// MARK: TTS Sentence
func speakSentence() {
guard let
readerCenter = FolioReader.sharedInstance.readerCenter,
let currentPage = readerCenter.currentPage else {
return
}
let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass()!)')")
if sentence != nil {
let chapter = readerCenter.getCurrentChapter()
let href = chapter != nil ? chapter!.href : "";
playText(href!, text: sentence!)
} else {
if readerCenter.isLastPage() {
stop()
} else {
readerCenter.changePageToNext()
}
}
}
func readCurrentSentence() {
guard synthesizer != nil else { return speakSentence() }
if synthesizer.isPaused {
playing = true
synthesizer.continueSpeaking()
} else {
if synthesizer.isSpeaking {
stopSynthesizer(immediate: false, completion: {
if let currentPage = FolioReader.sharedInstance.readerCenter?.currentPage {
currentPage.webView.js("resetCurrentSentenceIndex()")
}
self.speakSentence()
})
} else {
speakSentence()
}
}
}
// MARK: - Audio timing events
fileprivate func startPlayerTimer() {
// we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview
playingTimer = Timer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true)
RunLoop.current.add(playingTimer, forMode: RunLoopMode.commonModes)
}
fileprivate func stopPlayerTimer() {
if playingTimer != nil {
playingTimer.invalidate()
playingTimer = nil
}
}
func playerTimerObserver() {
guard let player = player else { return }
if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime {
_playFragment(nextAudioFragment())
}
}
// MARK: - Now Playing Info and Controls
/**
Update Now Playing info
Gets the book and audio information and updates on Now Playing Center
*/
func updateNowPlayingInfo() {
var songInfo = [String: AnyObject]()
// Get book Artwork
if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) {
let albumArt = MPMediaItemArtwork(image: artwork)
songInfo[MPMediaItemPropertyArtwork] = albumArt
}
// Get book title
if let title = book.title() {
songInfo[MPMediaItemPropertyAlbumTitle] = title as AnyObject?
}
// Get chapter name
if let chapter = getCurrentChapterName() {
songInfo[MPMediaItemPropertyTitle] = chapter as AnyObject?
}
// Get author name
if let author = book.metadata.creators.first {
songInfo[MPMediaItemPropertyArtist] = author.name as AnyObject?
}
// Set player times
if let player = player , !isTextToSpeech {
songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration as AnyObject?
songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate as AnyObject?
songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime as AnyObject?
}
// Set Audio Player info
MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo
registerCommandsIfNeeded()
}
/**
Get Current Chapter Name
This is done here and not in ReaderCenter because even though `currentHref` is accurate,
the `currentPage` in ReaderCenter may not have updated just yet
*/
func getCurrentChapterName() -> String? {
guard let chapter = FolioReader.sharedInstance.readerCenter?.getCurrentChapter() else {
return nil
}
currentHref = chapter.href
for item in book.flatTableOfContents {
if let resource = item.resource , resource.href == currentHref {
return item.title
}
}
return nil
}
/**
Register commands if needed, check if it's registered to avoid register twice.
*/
func registerCommandsIfNeeded() {
guard !registeredCommands else { return }
let command = MPRemoteCommandCenter.shared()
command.previousTrackCommand.isEnabled = true
command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter))
command.nextTrackCommand.isEnabled = true
command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter))
command.pauseCommand.isEnabled = true
command.pauseCommand.addTarget(self, action: #selector(pause))
command.playCommand.isEnabled = true
command.playCommand.addTarget(self, action: #selector(play))
command.togglePlayPauseCommand.isEnabled = true
command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay))
registeredCommands = true
}
}
// MARK: AVSpeechSynthesizerDelegate
extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate {
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
completionHandler()
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
if isPlaying() {
readCurrentSentence()
}
}
}
// MARK: AVAudioPlayerDelegate
extension FolioReaderAudioPlayer: AVAudioPlayerDelegate {
public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
_playFragment(nextAudioFragment())
}
}
| bsd-3-clause | 6dfb909ee78ecd985b390cdab58a7223 | 31.160985 | 141 | 0.562334 | 5.719434 | false | false | false | false |
EgeTart/ImageClip | ImageClip/HTTPSecurity.swift | 1 | 8008 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// HTTPSecurity.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 5/13/15.
// Copyright (c) 2015 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import Security
public class HTTPSSLCert {
var certData: NSData?
var key: SecKeyRef?
/**
Designated init for certificates
- parameter data: is the binary data of the certificate
- returns: a representation security object to be used with
*/
public init(data: NSData) {
self.certData = data
}
/**
Designated init for public keys
- parameter key: is the public key to be used
- returns: a representation security object to be used with
*/
public init(key: SecKeyRef) {
self.key = key
}
}
public class HTTPSecurity {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
var pubKeys: [SecKeyRef]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
Use certs from main app bundle
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
var collect = Array<HTTPSSLCert>()
for path in paths {
if let d = NSData(contentsOfFile: path as String) {
collect.append(HTTPSSLCert(data: d))
}
}
self.init(certs:collect, usePublicKeys: usePublicKeys)
}
/**
Designated init
- parameter keys: is the certificates or public keys to use
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public init(certs: [HTTPSSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
var collect = Array<SecKeyRef>()
for cert in certs {
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let k = cert.key {
collect.append(k)
}
}
self.pubKeys = collect
self.isReady = true
})
} else {
var collect = Array<NSData>()
for cert in certs {
if let d = cert.certData {
collect.append(d)
}
}
self.certificates = collect
self.isReady = true
}
}
/**
Valid the trust and domain name.
- parameter trust: is the serverTrust to validate
- parameter domain: is the CN domain to validate
- returns: if the key was successfully validated
*/
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
var trustedCount = 0
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
trustedCount++
break
}
}
}
if trustedCount == serverPubKeys.count {
return true
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
var collect = Array<SecCertificate>()
for cert in certs {
if let c = SecCertificateCreateWithData(nil,cert) {
collect.append(c)
}
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
/**
Get the public key from a certificate data
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKey(data: NSData) -> SecKeyRef? {
let possibleCert = SecCertificateCreateWithData(nil,data)
if let cert = possibleCert {
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
}
return nil
}
/**
Get the public key from a certificate
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
var secTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &secTrust)
if let trust = secTrust {
var result: SecTrustResultType = 0
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
return nil
}
/**
Get the certificate chain for the trust
- parameter trust: is the trust to lookup the certificate chain for
- returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
var collect = Array<NSData>()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
if let cert = SecTrustGetCertificateAtIndex(trust,i) {
collect.append(SecCertificateCopyData(cert))
}
}
return collect
}
/**
Get the public key chain for the trust
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
- returns: the public keys from the certifcate chain for the trust
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
var collect = Array<SecKeyRef>()
let policy = SecPolicyCreateBasicX509()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
if let cert = SecTrustGetCertificateAtIndex(trust,i) {
if let key = extractPublicKeyFromCert(cert, policy: policy) {
collect.append(key)
}
}
}
return collect
}
}
| mit | 18f0369f83570dd40ee7f1003c73ce82 | 31.819672 | 121 | 0.539336 | 5.568846 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | HTWDresden/HTWDresden/Cell/GradeExtendedCell.swift | 2 | 1072 | //
// GradeExtendedCell.swift
// HTWGrades
//
// Created by Benjamin Herzog on 08/12/15.
// Copyright © 2015 HTW Dresden. All rights reserved.
//
import UIKit
class GradeExtendedCell: GradeCell {
@IBOutlet private weak var numberLabel: UILabel?
@IBOutlet weak var subjectLabel: UILabel?
@IBOutlet weak var stateLabel: UILabel?
@IBOutlet weak var creditsLabel: UILabel?
@IBOutlet weak var gradeLabel: UILabel?
@IBOutlet weak var semesterLabel: UILabel?
override func setupFromGrade(grade: Grade?) {
guard let grade = grade else {
for view in contentView.subviews {
if let label = view as? UILabel {
label.text = nil
}
}
return
}
numberLabel?.text = grade.nr.description
subjectLabel?.text = grade.subject
stateLabel?.text = grade.state
creditsLabel?.text = grade.credits.description
gradeLabel?.text = grade.grade.description
semesterLabel?.text = grade.semester
}
}
| gpl-2.0 | 3a60f20fbb34d62d2fc45104f8d89591 | 27.945946 | 54 | 0.622782 | 4.636364 | false | false | false | false |
doctorn/hac-website | Sources/HaCWebsiteLib/GitUtils.swift | 1 | 2729 | import Foundation
public struct GitUtils {
/**
Runs a `git clone` command at the specified path, cloning into the specified directory
- parameters:
- repoURL: The URL to the Git repository to clone
- localPath: The local path in which to run the `clone`
- directory: The directory name to clone the repository into
*/
public static func shallowBranchClone(
repoURL: String,
in localPath: String,
directory: String,
branch: String = "master"
) {
let repoPath = localPath + "/" + directory
shell(args: "git", "clone", "--depth", "1", repoURL, repoPath, "--branch", branch, "--single-branch")
}
/**
Runs a `git pull` command at the specified path
- parameters:
- in: The path to the local repository in which to pull
- remote: The name of the remote to pull from
- branch: The name of the branch on the remote to pull from
*/
public static func pull(in localRepoPath: String, remote: String = "origin", branch: String = "master") {
// Note the -C argument which tells Git to move to the following directory before doing anything
shell(args: "git", "-C", localRepoPath, "pull", remote, branch)
}
/**
Clones a Git repository if it doesn't already exist at the specified location, updating it otherwise
- parameters:
- repoURL: The URL to the Git repository
- localPath: The local path to the parent directory of the repository
- directory: The directory name to clone or pull the repository into
*/
public static func cloneOrPull(repoURL: String, in localPath: String, directory: String) {
let localRepoPath = localPath + "/" + directory
guard directoryExists(atPath: localRepoPath) else {
shallowBranchClone(
repoURL: "https://github.com/hackersatcambridge/workshops.git",
in: localPath,
directory: directory
)
return
}
pull(in: localRepoPath)
}
}
/**
Executes a shell command synchronously, returning the exit code
- parameters:
- args: The arguments to the shell command, starting with the command itself
- returns:
The exit code of the command
*/
@discardableResult
private func shell(args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
private func directoryExists(atPath: String) -> Bool {
// Note the Objective-C gunk here, an unfortunate part of this API
var isDirectory: ObjCBool = ObjCBool(false)
let fileExists = FileManager.default.fileExists(atPath: atPath, isDirectory: &isDirectory)
return fileExists && isDirectory.description == "true"
}
| mit | f910f724d1122d451dfb1c2e998373f7 | 31.488095 | 107 | 0.681202 | 4.311216 | false | false | false | false |
KinoAndWorld/DailyMood | DailyMood/Controller/AddDailyVC.swift | 1 | 11608 | //
// AddDailyVC.swift
// DailyMood
//
// Created by kino on 14-7-12.
// Copyright (c) 2014 kino. All rights reserved.
//
import UIKit
import QuartzCore
class AddDailyVC: BaseViewController , UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate{
@IBOutlet var containerScrollView : UIScrollView
@IBOutlet var dailyTextView : UITextView
@IBOutlet var moodButton : UIButton
@IBOutlet var pictureButton : UIButton
@IBOutlet var locationButton : UIButton
@IBOutlet var weatherButton : UIButton
var dailyModel:Daily = Daily.MR_createEntity(){
willSet{
if dailyModel != nil{
dailyModel.MR_deleteEntity()
currentType = EditType.EditDaily
}
}
}
var isShouldSave:Bool = false
var isShouldBack = true
enum EditType{
case AddDaily, EditDaily
}
var currentType = EditType.AddDaily
func constructViewByUpdateState(model:Daily){
println("model = \(model)")
dailyTextView.text = model.content
let mood = Mood.moodByIndex(model.moodType.integerValue)
moodButton.setImage(UIImage(named: mood.crrentType.getImageName()),
forState: UIControlState.Normal)
let weather = Weather.weatherByStateIndex(model.weatherState.integerValue)
weatherButton.setImage(UIImage(named: weather.weatherState?.getImageName()),
forState: UIControlState.Normal)
if let backImage = model.backImage as NSData?{
pictureButton.setImage(UIImage(data: backImage),
forState: UIControlState.Normal)
}
}
@IBAction func finishDailyAction(sender : AnyObject) {
}
func checkDailyVaild()->String?{
if countElements(dailyModel.content) == 0 {return "The Daily Content can no be blank"}
return nil
}
///life circle
override func viewDidLoad() {
super.viewDidLoad()
initDataAndViews()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillShow:",
name:UIKeyboardWillShowNotification,
object:nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillhide:",
name: UIKeyboardWillHideNotification,
object: nil)
isShouldBack = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
dailyTextView.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
if isShouldSave == false &&
isShouldBack &&
currentType == EditType.AddDaily{
dailyModel.MR_deleteEntity()
}
}
///
func initDataAndViews(){
self.setRightSaveItem()
dailyTextView.font = dailyFont(18.0)
if currentType == EditType.EditDaily{
constructViewByUpdateState(dailyModel)
}
}
override func saveItemAction() {
dailyModel.content = dailyTextView.text
dailyModel.time = NSDate()
let col = CIColor(CGColor: UIColor.whiteColor().CGColor)
dailyModel.contentColor = col.stringRepresentation()
if dailyModel.location == nil{
dailyModel.location = DailyLocation.defaultLocaion
}
//done some thing
if let error:String = checkDailyVaild(){
let alert = UIAlertView(title: error,
message: "",
delegate: nil,
cancelButtonTitle: "Well")
alert.show()
}else{
isShouldSave = true
self.navigationController.popToRootViewControllerAnimated(true)
switch currentType{
case .EditDaily:
NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait()
case .AddDaily:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.dailyModel.calcTextColor()
NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait()
})
}
}
}
///keyboard
func keyboardWillShow(notif:NSNotification){
updateScrollViewByNotif(notif)
}
func keyboardWillhide(notif:NSNotification){
updateScrollViewByNotif(notif)
}
func updateScrollViewByNotif(notif:NSNotification){
let value:NSValue = notif.userInfo![UIKeyboardFrameEndUserInfoKey] as NSValue
var keyboardSize:CGSize = value.CGRectValue().size
containerScrollView.height = UIScreen.mainScreen().bounds.height - keyboardSize.height - containerScrollView.top - 5
}
//DashBoard
enum Component:Int{
case Mood = 0, Picture, Location, Weather
}
var component:AddDailyComponent? = nil
@IBAction func addComponentAction(sender : AnyObject) {
var tag4Component:Component = Component.fromRaw(sender.tag!)!
self.view.endEditing(true)
switch tag4Component{
case .Mood:
println("mood")
// component = MoodComponent(controller: self)
let moodChose = MoodChoseVC()
self.useBlurForPopup = true
self.presentPopupViewController(moodChose, animated: true, completion: nil)
moodChose.moodFinishBlock = { mood, cellFrame in
self.dailyModel.moodType = mood.moodType
//animation
let realFrame = CGRect(origin: CGPoint(x: cellFrame.origin.x + moodChose.view.left,
y: cellFrame.origin.y + moodChose.view.top),
size: cellFrame.size)
var moveView:UIView? = UIView(frame: realFrame)
// println("left:\(cellFrame.origin.x) top:\(cellFrame.origin.y)")
// moveView.backgroundColor = UIColor.yellowColor()
var moodImageView = UIImageView(image: UIImage(named: mood.crrentType.getImageName()))
moodImageView.frame = CGRect(x: 16, y: 7, width: 32, height: 32)
moveView!.addSubview(moodImageView)
self.view.addSubview(moveView)
self.dismissPopupViewControllerAnimated(true, completion: {
var moveAnim = POPSpringAnimation(propertyNamed: kPOPLayerPosition)
moveAnim.springBounciness = 12
moveAnim.toValue = NSValue(CGPoint: CGPoint(x: self.moodButton.left + self.containerScrollView.left + self.moodButton.width/2, y: self.containerScrollView.top + self.moodButton.top + self.moodButton.height/2))
moveView!.layer.pop_addAnimation(moveAnim, forKey: "moveMood")
moveAnim.completionBlock = { popAnim , finish in
if finish {
self.moodButton.setImage(moodImageView.image, forState: UIControlState.Normal)
moveView!.hidden = true
moveView = nil
}
}
});
}
case .Picture:
isShouldBack = false
println("pic")
var finishBlock:(UIImage)->Void = {[weak self] image in
println("The finish Image \(image.description)")
if let weakSelf = self{
// var fixedImage:UIImage? = image.resizedImage(CGSize(width: weakSelf.pictureButton.size.width, height: weakSelf.pictureButton.size.height), interpolationQuality: kCGInterpolationHigh)
// if (fixedImage != nil){
weakSelf.pictureButton.setImage(image, forState: UIControlState.Normal)
weakSelf.dailyModel.backImage = UIImagePNGRepresentation(image)
// }
}
}
component = PictureComponent(controller: self, pictureFinish: finishBlock)
component!.showComponent()
case .Location:
println("loca")
// (currentLocation:CLLocation?, status:LocationState, error:NSError?)->Void
var exist: AnyObject! = locationButton.layer.pop_animationForKey("rotateMe")
if exist { return }
var rotateAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPLayerRotation)
rotateAnim.duration = 20.0
rotateAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
rotateAnim.fromValue = NSNumber(double: 0.0)
rotateAnim.toValue = NSNumber(double: M_PI * 50.0)
// rotateAnim.toValue = NSNumber(float: UIScreen.mainScreen().bounds.height - bottomView.height)
// rotateAnim.springBounciness = 15
// upAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
locationButton.layer.pop_addAnimation(rotateAnim, forKey: "rotateMe")
KOLocationManager.sharedInstance.requestLocation(20.0, block: {currentLocation, state, err in
self.locationButton.layer.transform = CATransform3DIdentity
self.locationButton.layer.pop_removeAllAnimations()
switch(state){
case .Succeed:
println("Succeed")
self.dailyModel.connectLocation(currentLocation!)
let alert = UIAlertView(title: "Locate Succeed",
message: "Address:\(currentLocation?.detailAddress)",
delegate: nil,
cancelButtonTitle: "Well")
alert.show()
default:
println("eeeee")
let alert = UIAlertView(title: "定位失败",
message: "网络错误或者定位未开启哦",
delegate: nil,
cancelButtonTitle: "Well")
alert.show()
}
})
case .Weather:
let weatherChose = WeatherChoseVC()
self.useBlurForPopup = true
self.presentPopupViewController(weatherChose, animated: true, completion: nil)
weatherChose.weatherFinishBlock = { weather in
// dailyModel
var weatherIcon:String? = weather.weatherState?.getImageName()
if let iconImage:UIImage? = UIImage(named: weatherIcon) as UIImage? {
self.weatherButton.setImage(iconImage, forState: UIControlState.Normal)
self.dailyModel.weatherState = NSNumber(integer: weather.weatherState!.toRaw())
self.dismissPopupViewControllerAnimated(true, completion: nil)
}
}
default:
println("other")
}
}
}
| mit | 5c1d729b66ab6aba18ddd20aca5c516c | 37.976431 | 229 | 0.576192 | 5.488857 | false | false | false | false |
nerdycat/Cupcake | Cupcake-Demo/Cupcake-Demo/EnhancementViewController.swift | 1 | 2158 | //
// EnhancementViewController.swift
// Cupcake-Demo
//
// Created by nerdycat on 2017/4/27.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
class EnhancementViewController: BaseViewController {
override func setupUI() {
//Label with lineSpacing and link
let str = "With #Cupcake, @Label now support lineSpacing and Link handling. Additionally, @TextField and @TextView both have the abilities to set max length and placeholder. "
let attStr = AttStr(str).select("Link handling", .hashTag, .nameTag).link()
let label = Label.str(attStr).lineGap(10).lines().onLink({ text in
print(text)
}).embedIn(self.view, 15, 15, 15)
//TextField with maxLength
let nameField = TextField.pin(40).padding(0, 8).border(1).maxLength(5).hint("normal")
let codeField = TextField.pin(40).padding(0, 8).border(1).maxLength(4).hint("secure").keyboard(.numberPad).secure()
nameField.makeCons({ make in
make.top.equal(label).bottom.offset(20)
make.left.offset(15)
}).onFinish({ _ in
codeField.becomeFirstResponder()
})
codeField.makeCons({ make in
make.top.equal(nameField)
make.left.equal(nameField).right.offset(10)
make.right.offset(-15)
make.width.equal(nameField)
}).onChange({ [unowned self] codeField in
if codeField.text?.count == 4 {
self.view.viewWithTag(101)?.becomeFirstResponder()
}
})
//TextView with placeholder and maxLength
let textView = TextView.padding(8).maxLength(40).border(1).makeCons({ make in
make.left.right.offset(15, -15)
make.top.equal(nameField).bottom.offset(10)
make.height.equal(100)
}).hint("comment")
textView.tag = 101
self.view.addSubviews(nameField, codeField, textView)
self.view.onClick({ view in
view.endEditing(true)
})
}
}
| mit | 9a6637b9a6e932ea7520673eef919ad4 | 31.19403 | 183 | 0.579045 | 4.331325 | false | false | false | false |
MrAlek/JSQDataSourcesKit | Tests/CollectionViewDataSourceTests.swift | 1 | 10206 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import UIKit
import XCTest
import JSQDataSourcesKit
final class CollectionViewDataSourceTests: XCTestCase {
private let fakeCellReuseId = "fakeCellId"
private let fakeSupplementaryViewReuseId = "fakeSupplementaryId"
private let fakeCollectionView = FakeCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 600), collectionViewLayout: FakeFlowLayout())
private let dequeueCellExpectationName = "collectionview_dequeue_cell_expectation"
private let dequeueSupplementaryViewExpectationName = "collectionview_dequeue_supplementaryview_expectation"
override func setUp() {
super.setUp()
fakeCollectionView.registerClass(FakeCollectionCell.self,
forCellWithReuseIdentifier: fakeCellReuseId)
fakeCollectionView.registerClass(FakeCollectionSupplementaryView.self,
forSupplementaryViewOfKind: FakeSupplementaryViewKind,
withReuseIdentifier: fakeSupplementaryViewReuseId)
}
func test_ThatCollectionViewDataSource_ReturnsExpectedData_ForSingleSection() {
// GIVEN: a single section with data items
let expectedModel = FakeViewModel()
let expectedIndexPath = NSIndexPath(forRow: 3, inSection: 0)
let section0 = Section(items: FakeViewModel(), FakeViewModel(), FakeViewModel(), expectedModel, FakeViewModel())
let allSections = [section0]
let cellFactoryExpectation = expectationWithDescription(#function)
fakeCollectionView.dequeueCellExpectation = expectationWithDescription(dequeueCellExpectationName + #function)
// GIVEN: a cell factory
let cellFactory = CellFactory(reuseIdentifier: fakeCellReuseId) { (cell, model: FakeViewModel, collectionView, indexPath) -> FakeCollectionCell in
XCTAssertEqual(cell.reuseIdentifier!, self.fakeCellReuseId, "Dequeued cell should have expected identifier")
XCTAssertEqual(model, expectedModel, "Model object should equal expected value")
XCTAssertEqual(collectionView, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
XCTAssertEqual(indexPath, expectedIndexPath, "IndexPath should equal expected value")
cellFactoryExpectation.fulfill()
return cell
}
// GIVEN: a data source provider
typealias Factory = SupplementaryViewFactory<FakeViewModel, FakeCollectionSupplementaryView>
typealias Provider = CollectionViewDataSourceProvider<Section<FakeViewModel>, CellFactory<FakeViewModel, FakeCollectionCell>, Factory>
let dataSourceProvider: Provider = CollectionViewDataSourceProvider(sections: allSections, cellFactory: cellFactory, collectionView: fakeCollectionView)
let dataSource = dataSourceProvider.dataSource
// WHEN: we call the collection view data source methods
let numSections = dataSource.numberOfSectionsInCollectionView?(fakeCollectionView)
let numRows = dataSource.collectionView(fakeCollectionView, numberOfItemsInSection: 0)
let cell = dataSource.collectionView(fakeCollectionView, cellForItemAtIndexPath: expectedIndexPath)
// THEN: we receive the expected return values
XCTAssertNotNil(numSections, "Number of sections should not be nil")
XCTAssertEqual(numSections!, dataSourceProvider.sections.count, "Data source should return expected number of sections")
XCTAssertEqual(numRows, section0.count, "Data source should return expected number of rows for section 0")
XCTAssertEqual(cell.reuseIdentifier!, fakeCellReuseId, "Data source should return cells with the expected identifier")
// THEN: the collectionView calls `dequeueReusableCellWithReuseIdentifier`
// THEN: the cell factory calls its `ConfigurationHandler`
waitForExpectationsWithTimeout(defaultTimeout, handler: { (error) -> Void in
XCTAssertNil(error, "Expectation should not error")
})
}
func test_ThatCollectionViewDataSource_ReturnsExpectedData_ForMultipleSections() {
// GIVEN: some collection view sections
let section0 = Section(items: FakeViewModel(), FakeViewModel(), FakeViewModel(), FakeViewModel(), FakeViewModel(), FakeViewModel())
let section1 = Section(items: FakeViewModel(), FakeViewModel())
let section2 = Section(items: FakeViewModel(), FakeViewModel(), FakeViewModel(), FakeViewModel())
let allSections = [section0, section1, section2]
var cellFactoryExpectation = expectationWithDescription("cell_factory_\(#function)")
// GIVEN: a cell factory
let cellFactory = CellFactory(reuseIdentifier: fakeCellReuseId) { (cell, model: FakeViewModel, collectionView, indexPath) -> FakeCollectionCell in
XCTAssertEqual(cell.reuseIdentifier!, self.fakeCellReuseId, "Dequeued cell should have expected identifier")
XCTAssertEqual(model, allSections[indexPath.section][indexPath.item], "Model object should equal expected value")
XCTAssertEqual(collectionView, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
cellFactoryExpectation.fulfill()
return cell
}
var supplementaryFactoryExpectation = expectationWithDescription("supplementary_factory_\(#function)")
// GIVEN: a supplementary view factory
let supplementaryViewFactory = SupplementaryViewFactory(reuseIdentifier: fakeSupplementaryViewReuseId, kind: self.fakeSupplementaryViewReuseId)
{ (view, model: FakeViewModel?, kind, collectionView, indexPath) -> FakeCollectionSupplementaryView in
XCTAssertEqual(view.reuseIdentifier!, self.fakeSupplementaryViewReuseId, "Dequeued supplementary view should have expected identifier")
XCTAssertEqual(model, allSections[indexPath.section][indexPath.item], "Model object should equal expected value")
XCTAssertEqual(kind, FakeSupplementaryViewKind, "View kind should have expected kind")
XCTAssertEqual(collectionView, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
supplementaryFactoryExpectation.fulfill()
return view
}
// GIVEN: a data source provider
let dataSourceProvider = CollectionViewDataSourceProvider(
sections: allSections,
cellFactory: cellFactory,
supplementaryViewFactory: supplementaryViewFactory,
collectionView: fakeCollectionView)
let dataSource = dataSourceProvider.dataSource
// WHEN: we call the collection view data source methods
let numSections = dataSource.numberOfSectionsInCollectionView?(fakeCollectionView)
// THEN: we receive the expected return values
XCTAssertNotNil(numSections, "Number of sections should not be nil")
XCTAssertEqual(numSections!, dataSourceProvider.sections.count, "Data source should return expected number of sections")
for sectionIndex in 0..<dataSourceProvider.sections.count {
for rowIndex in 0..<dataSourceProvider[sectionIndex].items.count {
let expectationName = "\(#function)_\(sectionIndex)_\(rowIndex)"
fakeCollectionView.dequeueCellExpectation = expectationWithDescription(dequeueCellExpectationName + expectationName)
fakeCollectionView.dequeueSupplementaryViewExpectation = expectationWithDescription(dequeueSupplementaryViewExpectationName + expectationName)
let indexPath = NSIndexPath(forItem: rowIndex, inSection: sectionIndex)
// WHEN: we call the collection view data source methods
let numRows = dataSource.collectionView(fakeCollectionView, numberOfItemsInSection: sectionIndex)
let cell = dataSource.collectionView(fakeCollectionView, cellForItemAtIndexPath: indexPath)
let supplementaryView = dataSource.collectionView?(fakeCollectionView, viewForSupplementaryElementOfKind: FakeSupplementaryViewKind, atIndexPath: indexPath)
// THEN: we receive the expected return values
XCTAssertEqual(numRows, dataSourceProvider[sectionIndex].count, "Data source should return expected number of rows for section \(sectionIndex)")
XCTAssertEqual(cell.reuseIdentifier!, fakeCellReuseId, "Data source should return cells with the expected identifier")
XCTAssertNotNil(supplementaryView, "Supplementary view should not be nil")
XCTAssertEqual(supplementaryView!.reuseIdentifier!, fakeSupplementaryViewReuseId, "Data source should return supplementary views with the expected identifier")
// THEN: the collectionView calls `dequeueReusableCellWithReuseIdentifier`
// THEN: the cell factory calls its `ConfigurationHandler`
// THEN: the collectionView calls `dequeueReusableSupplementaryViewOfKind`
// THEN: the supplementary view factory calls its `ConfigurationHandler`
waitForExpectationsWithTimeout(defaultTimeout, handler: { (error) -> Void in
XCTAssertNil(error, "Expections should not error")
})
// reset expectation names for next loop, ignore last item
if !(sectionIndex == dataSourceProvider.sections.count - 1 && rowIndex == dataSourceProvider[sectionIndex].count - 1) {
cellFactoryExpectation = expectationWithDescription("cell_factory_" + expectationName)
supplementaryFactoryExpectation = expectationWithDescription("supplementary_factory_" + expectationName)
}
}
}
}
}
| mit | 3764b2355c196793fdcd40f7fc9d9a4d | 53.865591 | 175 | 0.721411 | 6.237775 | false | false | false | false |
stevewight/DetectorKit | DetectorKit/Models/Filters/Masker.swift | 1 | 1014 | //
// Masker.swift
// Sherlock
//
// Created by Steve on 12/4/16.
// Copyright © 2016 Steve Wight. All rights reserved.
//
import UIKit
class Masker: NSObject {
var features:[CIFeature]!
init(_ features:[CIFeature]) {
super.init()
self.features = features
}
public func output(_ filter:CIFilter,_ image:CIImage)->CIImage {
let featuresMask = featuresToImage()
return filterMask(
featuresMask,
image: image,
filter: filter
)
}
private func featuresToImage()->CIImage {
var finalMask = CIImage()
for feature in features {
let maskFeature = MaskFeature(feature, finalMask)
finalMask = maskFeature.output()
}
return finalMask
}
private func filterMask(_ mask:CIImage,image:CIImage,filter:CIFilter)->CIImage {
let blendFilter = BlendMask(filter.outputImage!,image,mask)
return blendFilter.output()
}
}
| mit | c3554ddc0f1d3963f97102ab6a721be1 | 22.55814 | 84 | 0.5923 | 4.347639 | false | false | false | false |
codepgq/LearningSwift | CollectionViewAnimation/CollectionViewAnimation/ViewController.swift | 1 | 4345 | //
// ViewController.swift
// CollectionViewAnimation
//
// Created by ios on 16/9/27.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
// MARK: - category方法
extension Array {
//判断是否在下标区间内,在就返回值 否则返回空
func safeIndex(i: Int) -> Element? {
return i < self.count && i >= 0 ? self[i] : nil
}
}
//Xib
private struct Storyboard{
static let CellIdentifier = String(AnimationCollectionViewCell)
static let NibName = String(AnimationCollectionViewCell)
}
//动画
private struct Constans {
static let Duration : Double = 0.5
static let Delay : Double = 0.0
static let SpringDamping : CGFloat = 1.0
static let SpringVelocity : CGFloat = 1.0
}
class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{
//数据源
private var imageCollection = AnimationImageCollection()
//懒加载collectionview
private lazy var collectionView: UICollectionView! = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 260 )
let coll = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: flowLayout)
coll.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
return coll
}()
// 加载CollectionView
override func viewDidLoad() {
super.viewDidLoad()
//register 提前注册
collectionView.registerNib(UINib(nibName: Storyboard.NibName, bundle: nil), forCellWithReuseIdentifier: Storyboard.CellIdentifier)
//设置代理
collectionView.delegate = self
collectionView.dataSource = self
//加载View
view.addSubview(collectionView)
}
// 设置系统状态栏样式
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
// MARK: - 这里是Collectionview的代理 Datasource delegate
extension ViewController{
// 返回有多少个cell
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageCollection.images.count ?? 0
}
// 设置每个cell的样式
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//这里要满足两个条件
guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as? AnimationCollectionViewCell, viewModel = imageCollection.images.safeIndex(indexPath.row) else {
return UICollectionViewCell()
}
cell.prepareCell(viewModel)
return cell
}
// cell 被点击是调用
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? AnimationCollectionViewCell else{
print("拿不到Cell")
return
}
//调用动画方法
cellAnimationWith(cell, collectionView: collectionView)
}
private func cellAnimationWith(cell : AnimationCollectionViewCell,collectionView : UICollectionView){
// 设置为选中状态
cell.handleCellSelected()
//保存闭包代码
cell.backButtonTapped = {
guard let indexPaths = self.collectionView.indexPathsForSelectedItems() else{
return
}
collectionView.scrollEnabled = true
collectionView.reloadItemsAtIndexPaths(indexPaths)
}
// 设置动画
let animation : () -> () = {
//设置大小
cell.frame = collectionView.bounds
}
//动画结束又可以滑动了
let completion : (fnished : Bool) -> () = { _ in
collectionView.scrollEnabled = false
}
//开始动画
UIView.animateWithDuration(Constans.Duration, delay: Constans.Delay, usingSpringWithDamping: Constans.SpringDamping, initialSpringVelocity: Constans.SpringVelocity, options: [], animations: animation, completion: completion)
}
}
| apache-2.0 | fb40a4c892a70d07ff240b9b6cfa593c | 30.890625 | 232 | 0.66389 | 5.233333 | false | false | false | false |
SimonFairbairn/Stormcloud | Sources/Stormcloud/Stormcloud+Environment.swift | 1 | 1383 | //
// Stormcloud+Environment.swift
// Stormcloud
//
// Created by Simon Fairbairn on 21/09/2017.
// Copyright © 2017 Voyage Travel Apps. All rights reserved.
//
import Foundation
// A simple protocol with an implementation in an extension that will help us manage the environment
public protocol StormcloudEnvironmentVariable {
func stringValue() -> String
}
public extension StormcloudEnvironmentVariable {
func isEnabled() -> Bool {
let env = ProcessInfo.processInfo.environment
if let _ = env[self.stringValue()] {
return true
} else {
return false
}
}
}
/**
A list of environment variables that you can use for debugging purposes.
Usage:
1. `Product -> Scheme -> Edit Scheme...`
2. Under `Environment variables` tap the `+` icon
3. Add `Stormcloud` + the enum case (e.g. `StormcloudMangleDelete`) as the name field. No value is required.
Valid variables:
- **`StormcloudMangleDelete`** : Mangles a delete so you can test your apps response to errors correctly
- **`StormcloudVerboseLogging`** : More verbose output to see what's happening within Stormcloud
*/
public enum StormcloudEnvironment : String, StormcloudEnvironmentVariable {
case MangleDelete = "StormcloudMangleDelete"
case VerboseLogging = "StormcloudVerboseLogging"
case DelayLocal = "StormcloudDelayLocalFiles"
public func stringValue() -> String {
return self.rawValue
}
}
| mit | 8e9ebf06187888205f04ba137473ddc3 | 27.204082 | 108 | 0.74602 | 3.903955 | false | false | false | false |
gregomni/swift | test/Sanitizers/tsan/racy_actor_counters.swift | 2 | 2384 | // RUN: %target-swiftc_driver %s -parse-as-library %import-libdispatch -target %sanitizers-target-triple -g -sanitize=thread -o %t
// RUN: %target-codesign %t
// RUN: env %env-TSAN_OPTIONS="abort_on_error=0" not %target-run %t 2>&1 | %swift-demangle --simplified | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// REQUIRES: tsan_runtime
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// rdar://75365575 (Failing to start atos external symbolizer)
// UNSUPPORTED: OS=watchos
// REQUIRES: rdar76542113
var globalCounterValue = 0
@available(SwiftStdlib 5.1, *)
actor Counter {
func next() -> Int {
let current = globalCounterValue
globalCounterValue += 1
return current
}
}
@available(SwiftStdlib 5.1, *)
func worker(identity: Int, counters: [Counter], numIterations: Int) async {
for _ in 0..<numIterations {
let counterIndex = Int.random(in: 0 ..< counters.count)
let counter = counters[counterIndex]
let nextValue = await counter.next()
print("Worker \(identity) calling counter \(counterIndex) produced \(nextValue)")
}
}
@available(SwiftStdlib 5.1, *)
func runTest(numCounters: Int, numWorkers: Int, numIterations: Int) async {
// Create counter actors.
var counters: [Counter] = []
for _ in 0..<numCounters {
counters.append(Counter())
}
// Create a bunch of worker threads.
var workers: [Task.Handle<Void, Error>] = []
for i in 0..<numWorkers {
workers.append(
detach { [counters] in
await worker(identity: i, counters: counters, numIterations: numIterations)
}
)
}
// Wait until all of the workers have finished.
for worker in workers {
try! await worker.get()
}
print("DONE!")
}
@available(SwiftStdlib 5.1, *)
@main struct Main {
static func main() async {
// Useful for debugging: specify counter/worker/iteration counts
let args = CommandLine.arguments
let counters = args.count >= 2 ? Int(args[1])! : 10
let workers = args.count >= 3 ? Int(args[2])! : 10
let iterations = args.count >= 4 ? Int(args[3])! : 100
print("counters: \(counters), workers: \(workers), iterations: \(iterations)")
await runTest(numCounters: counters, numWorkers: workers, numIterations: iterations)
}
}
// CHECK: ThreadSanitizer: {{(Swift access|data)}} race
// CHECK: Location is global 'globalCounterValue'
| apache-2.0 | 3007220f7a3a776e9076a5711b794566 | 29.177215 | 131 | 0.678272 | 3.707621 | false | false | false | false |
MaddTheSane/Simple-Comic | Classes/Session/TSSTSessionWindowController+NSToolbarDelegate.swift | 1 | 1166 | //
// TSSTSessionWindowController+NSToolbarDelegate.swift
// Simple Comic
//
// Created by J-rg on 13.09.21.
// Copyright © 2021 Dancing Tortoise Software. All rights reserved.
//
import Cocoa
private extension NSToolbarItem.Identifier {
static let turnPage = NSToolbarItem.Identifier("ADD2836D-8728-474F-9355-80FA8EA9972C")
static let pageOrder = NSToolbarItem.Identifier("9C25BD8E-6129-4874-917D-C4C5F75BD24F")
static let pageLayout = NSToolbarItem.Identifier("57633342-20D2-433A-9828-1C85F79205A8")
static let pageScaling = NSToolbarItem.Identifier("E33C7D17-8160-4B40-8EDF-78600C84FE8C")
static let thumbnails = NSToolbarItem.Identifier("AB4BCD46-EE79-45CC-9A97-733E3740BA34")
}
extension TSSTSessionWindowController: NSToolbarDelegate {
public func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
if #available(macOS 11.0, *) {
return [
.turnPage,
.pageOrder,
.pageLayout,
.pageScaling,
.flexibleSpace,
.thumbnails,
]
} else {
return [
.turnPage,
.space,
.pageOrder,
.pageLayout,
.pageScaling,
.flexibleSpace,
.thumbnails,
]
}
}
}
| mit | 74f2570b526b75e526c5be4e0a6c3fab | 26.093023 | 96 | 0.724464 | 2.994859 | false | false | false | false |
ksco/swift-algorithm-club-cn | Binary Tree/BinaryTree.swift | 1 | 1543 | /*
A general-purpose binary tree.
Nodes don't have a reference to their parent.
*/
public indirect enum BinaryTree<T> {
case Node(BinaryTree<T>, T, BinaryTree<T>)
case Empty
public var count: Int {
switch self {
case let .Node(left, _, right):
return left.count + 1 + right.count
case .Empty:
return 0
}
}
}
extension BinaryTree: CustomStringConvertible {
public var description: String {
switch self {
case let .Node(left, value, right):
return "value: \(value), left = [" + left.description + "], right = [" + right.description + "]"
case .Empty:
return ""
}
}
}
extension BinaryTree {
public func traverseInOrder(@noescape process: T -> Void) {
if case let .Node(left, value, right) = self {
left.traverseInOrder(process)
process(value)
right.traverseInOrder(process)
}
}
public func traversePreOrder(@noescape process: T -> Void) {
if case let .Node(left, value, right) = self {
process(value)
left.traversePreOrder(process)
right.traversePreOrder(process)
}
}
public func traversePostOrder(@noescape process: T -> Void) {
if case let .Node(left, value, right) = self {
left.traversePostOrder(process)
right.traversePostOrder(process)
process(value)
}
}
}
extension BinaryTree {
func invert() -> BinaryTree {
if case let .Node(left, value, right) = self {
return .Node(right.invert(), value, left.invert())
} else {
return .Empty
}
}
}
| mit | 39807a59984f1b561498048e83019469 | 22.738462 | 102 | 0.625405 | 3.896465 | false | false | false | false |
SocialObjects-Software/AMSlideMenu | AMSlideMenu/Animation/Animators/AMSlidingShadowAnimator.swift | 1 | 2506 | //
// AMSlidingShadowAnimator.swift
// AMSlideMenu
//
// The MIT License (MIT)
//
// Created by : arturdev
// Copyright (c) 2020 arturdev. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import UIKit
open class AMSlidingShadowAnimator: AMSlidingAnimatorProtocol {
open var duration: TimeInterval = 0.25
open func animate(leftMenuView: UIView, contentView: UIView, progress: CGFloat, animated: Bool, completion: (() -> Void)?) {
leftMenuView.layer.shadowColor = UIColor(red: 8/255.0, green: 46/255.0, blue: 88/255.0, alpha: 0.28).cgColor
leftMenuView.layer.shadowOffset = CGSize(width: 1, height: 0)
leftMenuView.layer.shadowRadius = 5
UIView.animate(withDuration: animated ? duration : 0, animations: {
leftMenuView.layer.shadowOpacity = Float(progress)
}) { (_) in
completion?()
}
}
open func animate(rightMenuView: UIView, contentView: UIView, progress: CGFloat = 1, animated: Bool = true, completion: (() -> Void)? = nil) {
rightMenuView.layer.shadowColor = UIColor(red: 8/255.0, green: 46/255.0, blue: 88/255.0, alpha: 0.28).cgColor
rightMenuView.layer.shadowOffset = CGSize(width: -1, height: 0)
rightMenuView.layer.shadowRadius = 5
UIView.animate(withDuration: animated ? duration : 0, animations: {
rightMenuView.layer.shadowOpacity = Float(progress)
}) { (_) in
completion?()
}
}
}
| mit | 72540411188bd35792153ecfaf1bf3bf | 44.563636 | 143 | 0.701516 | 4.22597 | false | false | false | false |
atuooo/notGIF | notGIF/Controllers/Drawer/DrawerViewController.swift | 1 | 6023 | //
// DrawerViewController.swift
// notGIF
//
// Created by ooatuoo on 2017/6/1.
// Copyright © 2017年 xyz. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
fileprivate let sideBarWidth: CGFloat = Config.sideBarWidth
fileprivate let scaleFactor: CGFloat = 80 / kScreenHeight
fileprivate let animDuration: TimeInterval = 0.6
class DrawerViewController: UIViewController {
@IBOutlet var dissmisTapGes: UITapGestureRecognizer!
@IBOutlet var sidePanGes: UIPanGestureRecognizer!
@IBOutlet weak var sideBarContainer: UIView!
@IBOutlet weak var mainContainer: UIView! {
didSet {
mainContainer.layer.shadowColor = UIColor.black.cgColor
mainContainer.layer.shadowOffset = CGSize(width: -2.0, height: -2.0)
mainContainer.layer.shadowOpacity = 0.33
}
}
fileprivate var shouldHideStatusBar: Bool = false
fileprivate var gesBeginOffsetX: CGFloat = 0
fileprivate var isShowing: Bool = false {
didSet {
dissmisTapGes.isEnabled = isShowing
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(DrawerViewController.setStatusBarHidden(noti:)), name: .hideStatusBar, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Update Status Bar
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var prefersStatusBarHidden: Bool {
return shouldHideStatusBar
}
func setStatusBarHidden(noti: Notification) {
guard let shouldHide = noti.object as? Bool else { return }
shouldHideStatusBar = shouldHide
setNeedsStatusBarAppearanceUpdate()
}
// MARK: - Gesture Handler
@IBAction func sidePanGesHandler(_ sender: UIPanGestureRecognizer) {
let transitionX = sender.translation(in: view).x
let offsetX = max(min(kScreenWidth, gesBeginOffsetX + transitionX), 0)
switch sender.state {
case .began:
gesBeginOffsetX = mainContainer.frame.origin.x
case .changed:
let scale = 1 - (offsetX / kScreenWidth) * scaleFactor
mainContainer.transform = CGAffineTransform(translationX: offsetX, y: 0)
.scaledBy(x: 1, y: scale)
case .cancelled, .ended, .failed:
let velocity = sender.velocity(in: view)
endMoveSideBar(with: offsetX, velocityX: velocity.x)
default:
break
}
}
@IBAction func dismissTapGesHandler(_ sender: UITapGestureRecognizer) {
dismissSideBar()
}
// MARK: - Show & Dismiss
fileprivate func endMoveSideBar(with offset: CGFloat, velocityX: CGFloat) {
if isShowing {
if offset <= sideBarWidth*0.7 || velocityX < -500 {
dismissSideBar(with: offset, velocityX: velocityX)
} else {
showSideBar(with: offset, velocityX: velocityX)
}
} else {
if offset >= sideBarWidth*0.3 || velocityX > 500 {
showSideBar(with: offset, velocityX: velocityX)
} else {
dismissSideBar(with: offset, velocityX: velocityX)
}
}
}
public func showSideBar(with offset: CGFloat = 0, velocityX: CGFloat = 0) {
let xDiff = abs(offset - sideBarWidth)
var velocity = xDiff == 0 ? 0 : abs(velocityX) / xDiff
if velocity < 10 { velocity = 0.6 }
let finalScale = 1 - (sideBarWidth / kScreenWidth) * scaleFactor
UIView.animate(withDuration: animDuration,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: velocity,
options: [.curveEaseIn],
animations: {
self.mainContainer.transform = CGAffineTransform(translationX: sideBarWidth, y: 0)
.scaledBy(x: 1, y: finalScale)
}) { _ in
self.mainContainer.isUserInteractionEnabled = false
self.isShowing = true
}
}
public func dismissSideBar(with offset: CGFloat = sideBarWidth, velocityX: CGFloat = 0) {
let velocity = offset == 0 ? 0 : abs(velocityX) / abs(offset)
UIView.animate(withDuration: animDuration*0.8,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: velocity,
options: [],
animations: {
self.mainContainer.transform = .identity
}) { _ in
self.mainContainer.isUserInteractionEnabled = true
self.isShowing = false
}
}
public func showOrDissmissSideBar() {
isShowing ? dismissSideBar() : showSideBar()
}
}
// MARK: - Gesture Delegate
extension DrawerViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard !IQKeyboardManager.sharedManager().keyboardShowing else { return false}
if gestureRecognizer === sidePanGes {
if isShowing {
let location = sidePanGes.location(in: view)
return mainContainer.frame.contains(location)
} else {
return sidePanGes.velocity(in: mainContainer).x > 0
}
} else if gestureRecognizer === dissmisTapGes {
let tapLocation = dissmisTapGes.location(in: view)
return isShowing && mainContainer.frame.contains(tapLocation)
}
return true
}
}
| mit | fad3445d6487c9320f3a8906ff4276fb | 32.444444 | 156 | 0.581728 | 5.257642 | false | false | false | false |
28stephlim/Heartbeat-Analyser | VoiceMemos/Controller/AorticSitConditionViewController.swift | 2 | 7880 | //
// AorticSitConditionViewController.swift
// VoiceMemos
//
// Created by Stepanie Lim on 07/10/2016.
// Copyright © 2016 Zhouqi Mo. All rights reserved.
//
import UIKit
class AorticSitConditionViewController: UIViewController {
//Global variables
@IBOutlet weak var waveform: FDWaveformView!
var condition = String()
var details = String ()
var diagnosis = String ()
var siteclicked = String ()
var googlesite = String ()
var mayosite = String ()
var medlinesite = String ()
var URL : NSURL!
//unwind segue
@IBAction func unwindtoAOSCond(segue: UIStoryboardSegue){
}
//Target Connection
@IBOutlet weak var labelname: UILabel!
@IBOutlet weak var labeldetail: UILabel!
@IBOutlet weak var image: UIImageView!
@IBAction func aosweb(sender: AnyObject) {
// Create the alert controller
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
alert.addAction(UIAlertAction(title: "Google", style: UIAlertActionStyle.Default, handler: { alertAction in
self.siteclicked = self.googlesite
self.performSegueWithIdentifier("aossegue", sender:true)
}))
alert.addAction(UIAlertAction(title: "Mayoclinic", style: UIAlertActionStyle.Default, handler: {
alertAction in
self.siteclicked = self.mayosite
self.performSegueWithIdentifier("aossegue", sender: true)
}))
alert.addAction(UIAlertAction(title: "MedlinePlus", style: UIAlertActionStyle.Default, handler: {
alertAction in
self.siteclicked = self.medlinesite
self.performSegueWithIdentifier("aossegue", sender: true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//sending segue to display selected webpage
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "aossegue") {
let aosweb = segue.destinationViewController as! AoSWebViewController
aosweb.AoSweb = self.siteclicked}
}
override func viewDidLoad() {
super.viewDidLoad()
detailscond()
self.waveform.audioURL = URL
self.waveform.progressSamples = 0
self.waveform.doesAllowScroll = true
self.waveform.doesAllowStretch = true
self.waveform.doesAllowScrubbing = false
self.waveform.wavesColor = UIColor.darkGrayColor()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
labelname.text = diagnosis
labeldetail.text = details
}
func detailscond(){
if condition == "AoS-EDM"{
//referenced from http://patient.info/health/aortic-regurgitation-leaflet
self.image.image = UIImage(named:"AoS-EDM")
diagnosis = "Aortic Regurgitation"
details = "Aortic regurgitation is a condition in which blood leaks back through the aortic valve. This is because the valve does not close properly."+"\n"+"There would be no symptoms if the leak is small. However, if the backflow of blood becomes worse, the symptoms are:"+"\n"+"1. Dizziness"+"\n"+"2. Chest pain"+"\n"+"3. Forceful thumping heartbeats"
googlesite = "https://www.google.com.au/#q=Aortic+Regurgitation%27"
mayosite = "http://www.mayoclinic.org/diseases-conditions/aortic-valve-regurgitation/basics/definition/con-20022523"
medlinesite = "https://medlineplus.gov/ency/article/000179.htm"
}
else if condition == "AoS-Normal"{
self.image.image = UIImage(named:"AoS-Normal")
diagnosis = "Normal"
details = "This person has a normal heartsound. No heart issues is found."
mayosite = "http://www.mayoclinic.org/diseases-conditions/heart-disease/in-depth/heart-disease-prevention/art-20046502"
googlesite = "https://www.google.com.au/#q=keep+a+healthy+heart"
medlinesite = "https://medlineplus.gov/magazine/issues/winter10/articles/winter10pg8.html"
}
else if condition == "AoS-SMwAS2"{
//referenced from http://www.heart.org/HEARTORG/Conditions/More/HeartValveProblemsandDisease/Problem-Aortic-Valve-Stenosis_UCM_450437_Article.jsp#.V_kllGVKCAY
self.image.image = UIImage(named:"AoS-SMwAS2")
diagnosis = "Severe Aortic Stenosis"
details = "Aortic stenosis is a narrowing of the aortic valve opening. Aortic stenosis restricts the blood flow from the left ventricle to the aorta and may also affect the pressure in the left atrium. The amount of the blood flow is significantly reduced."+"\n\n"+"The symptoms are:"+"\n"+"1. Breathlessness"+"\n"+"2. Chest pain, or feeling pressure or tightness in the heart"+"\n"+"3. Fainting"+"\n"+"4. Palpitations or a feeling of heavy, pounding, or noticeable heartbeats"+"\n"+"5. Decline in activity level or reduced ability to do normal activities requiring mild exertion"
googlesite = "https://www.google.com.au/webhp?hl=en&sa=X&ved=0ahUKEwjU-rq_jdfPAhVoxlQKHWr9CR4QPAgD#hl=en&q=Severe+Aortic+Stenosis"
mayosite = "http://www.mayoclinic.org/diseases-conditions/aortic-stenosis/basics/definition/con-20026329"
medlinesite = "https://medlineplus.gov/ency/article/000178.htm"
}
else if condition == "AoS-SnDM"{
//referenced from https://www.heart.org/idc/groups/heart-public/@wcm/@hcm/documents/downloadable/ucm_307677.pdf
self.image.image = UIImage(named:"AoS-SnDM")
diagnosis = "Combined Aortic Stenosis and Regurgitation"
details = "This condition occurs when there is an obstruction to the aortic valve and leakage of valve as it closes after heartbeat."+"\n"+"There is little symptoms that occur for patients with mild obstruction. The most common symptoms are:"+"\n"+"1. Shortness of breath with exertion"+"\n"+"2. Chest pain"+"\n"+"3. Lightheadedness"+"\n"+"4. Fainting"+"\n"+"5. Reccurent fever (if the valve of the heart has become infected)"
googlesite = "https://www.google.com.au/search?client=safari&rls=en&q=Combined+Aortic+Stenosis+and+Regurgitation+-+Google+Search&ie=UTF-8&oe=UTF-8&gfe_rd=cr&ei=4CP_V6vbNrLr8Afylae4Cg"
medlinesite = "https://medlineplus.gov/ency/article/000179.htm"
mayosite = "http://www.mayoclinic.org/diseases-conditions/aortic-valve-regurgitation/basics/definition/con-20022523"
}
else {
diagnosis = "This sound file is corrupted"
self.image.image = UIImage(named:"error")
details = "Error!"+"\n"+"Please re-record a new sound file."+"\n\n\n"+"Notice:"+"\n"+"Please ensure patient is not talking and breathing normally when heart sound is taken."
googlesite = "http://www.wikihow.com/Take-Your-Own-Pulse-With-a-Stethoscope"
mayosite = "http://www.livestrong.com/article/252191-how-to-listen-to-a-heartbeat/"
medlinesite = "http://www.livestrong.com/article/252191-how-to-listen-to-a-heartbeat/"
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 36a0094b17607ed0d9fc13bdb4b412d0 | 50.496732 | 592 | 0.670517 | 3.817345 | false | false | false | false |
qRoC/Loobee | Sources/Loobee/Library/AssertionConcern/Assertion/EmptyAssertions.swift | 1 | 1512 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
/// The default message in notifications from `isEmpty` assertions.
@usableFromInline internal let kIsEmptyDefaultMessage: StaticString = """
The value must be empty.
"""
/// The default message in notifications from `isNotEmpty` assertions.
@usableFromInline internal let kIsNotEmptyDefaultMessage: StaticString = """
The value cannot be empty.
"""
/// Determines if the `value` is empty.
@inlinable
public func assert<T: Collection>(
isEmpty value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(!value.isEmpty) {
return .create(
message: message() ?? kIsEmptyDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is not empty.
@inlinable
public func assert<T: Collection>(
isNotEmpty value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value.isEmpty) {
return .create(
message: message() ?? kIsNotEmptyDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
| mit | e50ff6e46f67ee1f14d8b88e05f14173 | 27 | 76 | 0.65873 | 4.295455 | false | false | false | false |
mariopavlovic/codility-lessons | codility-lessons/codility-lessons/Lesson8.swift | 1 | 1797 | import Foundation
public class Lesson8 {
public func numEquiLeader(A: [Int]) -> Int {
guard let leader = findLeader(A) else {
return 0
}
var count = 0
var stack = [Int]()
var rest = A
for item in A {
stack.append(item)
rest.removeFirst()
if checkLeader(stack, candidate: leader) && checkLeader(rest, candidate: leader) {
count += 1
}
}
return count
}
func findLeader(A: [Int]) -> Int? {
var stack = [Int]()
for item in A {
stack.append(item)
guard stack.count > 1 else {
continue
}
//take last two elements of the stack
let last = stack[stack.count - 1]
let nextToLast = stack[stack.count - 2]
//see if they are different
if last != nextToLast {
//if so remove them
stack.popLast()
stack.popLast()
}
}
guard let leaderCandidate = stack.first else {
return nil
}
return checkLeader(A, candidate: leaderCandidate) ? leaderCandidate : nil
}
func checkLeader(A: [Int], candidate: Int) -> Bool {
var count = 0
for item in A {
if item == candidate {
count += 1
}
}
return count > (A.count / 2)
}
public func dominatorIndex(A: [Int]) -> Int {
guard let dominator = findLeader(A) else {
return -1
}
return A.startIndex.distanceTo(A.indexOf(dominator)!)
}
} | mit | e724b06f897672d5caa362930975b97a | 23.630137 | 94 | 0.446299 | 4.856757 | false | false | false | false |
OneupNetwork/SQRichTextEditor | Example/SQRichTextEditor/EFColorPicker/EFColorWheelView.swift | 1 | 9104 | //
// EFColorWheelView.swift
// EFColorPicker
//
// Created by EyreFree on 2017/9/29.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreGraphics
// The color wheel view.
public class EFColorWheelView: UIControl {
var isTouched = false
var wheelImage: CGImage?
// The hue value.
var hue: CGFloat = 0.0 {
didSet {
self.setSelectedPoint(point: ef_selectedPoint())
self.setNeedsDisplay()
}
}
// The saturation value.
var saturation: CGFloat = 0.0 {
didSet {
self.setSelectedPoint(point: ef_selectedPoint())
self.setNeedsDisplay()
}
}
// The saturation value.
var brightness: CGFloat = 1.0 {
didSet {
self.setSelectedPoint(point: ef_selectedPoint())
if oldValue != brightness {
drawWheelImage()
}
}
}
private lazy var indicatorLayer: CALayer = {
let dimension: CGFloat = 33
let edgeColor = UIColor(white: 0.9, alpha: 0.8)
let indicatorLayer = CALayer()
indicatorLayer.cornerRadius = dimension / 2
indicatorLayer.borderColor = edgeColor.cgColor
indicatorLayer.borderWidth = 2
indicatorLayer.backgroundColor = UIColor.white.cgColor
indicatorLayer.bounds = CGRect(x: 0, y: 0, width: dimension, height: dimension)
indicatorLayer.position = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
indicatorLayer.shadowColor = UIColor.black.cgColor
indicatorLayer.shadowOffset = CGSize.zero
indicatorLayer.shadowRadius = 1
indicatorLayer.shadowOpacity = 0.5
return indicatorLayer
}()
override open class var requiresConstraintBasedLayout: Bool {
get {
return true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.accessibilityLabel = "color_wheel_view"
self.layer.delegate = self
self.layer.addSublayer(self.indicatorLayer)
// [self setSelectedPoint:CGPointMake(dimension / 2, dimension / 2)];
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.isTouched = true
if let position: CGPoint = touches.first?.location(in: self) {
self.onTouchEventWithPosition(point: position)
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let position: CGPoint = touches.first?.location(in: self) {
self.onTouchEventWithPosition(point: position)
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.isTouched = false
if let position: CGPoint = touches.first?.location(in: self) {
self.onTouchEventWithPosition(point: position)
}
}
func onTouchEventWithPosition(point: CGPoint) {
let radius: CGFloat = self.bounds.width / 2
let mx = Double(radius - point.x)
let my = Double(radius - point.y)
let dist: CGFloat = CGFloat(sqrt(mx * mx + my * my))
if dist <= radius {
self.ef_colorWheelValueWithPosition(position: point, hue: &hue, saturation: &saturation)
self.setSelectedPoint(point: point)
self.sendActions(for: UIControl.Event.valueChanged)
}
}
func setSelectedPoint(point: CGPoint) {
let selectedColor: UIColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.indicatorLayer.position = point
self.indicatorLayer.backgroundColor = selectedColor.cgColor
CATransaction.commit()
}
// MARK:- CALayerDelegate methods
override public func display(_ layer: CALayer) {
guard wheelImage == nil else { return }
drawWheelImage()
}
override public func layoutSublayers(of layer: CALayer) {
if layer == self.layer {
self.setSelectedPoint(point: self.ef_selectedPoint())
self.layer.setNeedsDisplay()
}
}
// MARK:- Private methods
private func drawWheelImage() {
let dimension: CGFloat = min(self.frame.width, self.frame.height)
guard let bitmapData = CFDataCreateMutable(nil, 0) else {
return
}
CFDataSetLength(bitmapData, CFIndex(dimension * dimension * 4))
self.ef_colorWheelBitmap(
bitmap: CFDataGetMutableBytePtr(bitmapData),
withSize: CGSize(width: dimension, height: dimension)
)
if let image = self.ef_imageWithRGBAData(data: bitmapData, width: Int(dimension), height: Int(dimension)) {
wheelImage = image
self.layer.contents = wheelImage
}
}
private func ef_selectedPoint() -> CGPoint {
let dimension: CGFloat = min(self.frame.width, self.frame.height)
let radius: CGFloat = saturation * dimension / 2
let x: CGFloat = dimension / 2 + radius * CGFloat(cos(Double(hue) * Double.pi * 2.0))
let y: CGFloat = dimension / 2 + radius * CGFloat(sin(Double(hue) * Double.pi * 2.0))
return CGPoint(x: x, y: y)
}
private func ef_colorWheelBitmap(bitmap: UnsafeMutablePointer<UInt8>?, withSize size: CGSize) {
if size.width <= 0 || size.height <= 0 {
return
}
for y in 0 ..< Int(size.width) {
for x in 0 ..< Int(size.height) {
var hue: CGFloat = 0, saturation: CGFloat = 0, a: CGFloat = 0.0
self.ef_colorWheelValueWithPosition(position: CGPoint(x: x, y: y), hue: &hue, saturation: &saturation)
var rgb: RGB = RGB(1, 1, 1, 1)
if saturation < 1.0 {
// Antialias the edge of the circle.
if saturation > 0.99 {
a = (1.0 - saturation) * 100
} else {
a = 1.0
}
let hsb: HSB = HSB(hue, saturation, brightness, a)
rgb = EFHSB2RGB(hsb: hsb)
}
let i: Int = 4 * (x + y * Int(size.width))
bitmap?[i] = UInt8(rgb.red * 0xff)
bitmap?[i + 1] = UInt8(rgb.green * 0xff)
bitmap?[i + 2] = UInt8(rgb.blue * 0xff)
bitmap?[i + 3] = UInt8(rgb.alpha * 0xff)
}
}
}
private func ef_colorWheelValueWithPosition(position: CGPoint, hue: inout CGFloat, saturation: inout CGFloat) {
let c: Int = Int(self.bounds.width / 2)
let dx: CGFloat = (position.x - CGFloat(c)) / CGFloat(c)
let dy: CGFloat = (position.y - CGFloat(c)) / CGFloat(c)
let d: CGFloat = CGFloat(sqrt(Double(dx * dx + dy * dy)))
saturation = d
if d == 0 {
hue = 0
} else {
hue = acos(dx / d) / CGFloat.pi / 2.0
if dy < 0 {
hue = 1.0 - hue
}
}
}
private func ef_imageWithRGBAData(data: CFData, width: Int, height: Int) -> CGImage? {
guard let dataProvider = CGDataProvider(data: data) else {
return nil
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let imageRef = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
provider: dataProvider,
decode: nil,
shouldInterpolate: false,
intent: CGColorRenderingIntent.defaultIntent
)
return imageRef
}
}
| mit | 36834897808d54b959fea370d3e77b94 | 34.286822 | 118 | 0.602812 | 4.428016 | false | false | false | false |
StephenMIMI/U17Comics | U17Comics/U17Comics/classes/HomePage/main/Views/HomeHeaderView.swift | 1 | 5027 | //
// HomeHeaderView.swift
// U17Comics
//
// Created by qianfeng on 16/10/27.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
class HomeHeaderView: UIView {
//点击事件
var jumpClosure: HomeJumpClosure?
var listModel: HomeComicList? {
didSet {
configHeader(listModel!)
}
}
private var bgView: UIView?//白色背景
private var imageView: UIImageView?//头部视图图片
private var titleLabel: UILabel?//头部视图标题
private var moreLabel: UILabel?//头部视图跳转提示文字
private var moreIcon: UIImageView?
//左右的间距
private var space: CGFloat = 10
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.9, alpha: 1.0)
bgView = UIView.createView()
bgView?.backgroundColor = customBgColor
addSubview(bgView!)
//添加bgView的约束
bgView?.snp_makeConstraints(closure: { (make) in
make.left.right.bottom.equalToSuperview()
make.height.equalTo(44)
})
imageView = UIImageView()
imageView?.contentMode = .ScaleAspectFit
bgView!.addSubview(imageView!)
imageView!.snp_makeConstraints { (make) in
make.left.equalTo(bgView!).offset(5)
make.top.equalTo(bgView!).offset(4)
make.bottom.equalTo(bgView!).offset(-4)
make.width.equalTo(35)//头部图片视图大小39x42
}
titleLabel = UILabel.createLabel(nil, textAlignment: .Left, font: UIFont.systemFontOfSize(16))
bgView!.addSubview(titleLabel!)
moreLabel = UILabel.createLabel(nil, textAlignment: .Right, font: UIFont.systemFontOfSize(12))
bgView!.addSubview(moreLabel!)
let g = UITapGestureRecognizer(target: self, action: #selector(tapAction))
bgView!.addGestureRecognizer(g)
}
func tapAction() {
//更多跳转参数:argValue=8&argName=topic&argCon=2&page=1
if jumpClosure != nil {
if listModel!.argValue != nil && listModel!.argName != nil {
let tmpUrl = String(format: homeMoreUrl, ((listModel?.argValue)!).intValue, (listModel?.argName)!,2)
jumpClosure!(tmpUrl,nil,listModel?.itemTitle)
}else {
jumpClosure!(homeUnknownMoreUrl,nil,listModel?.itemTitle)
}
}
}
private func configHeader(model: HomeComicList) {
if let tmpurl = model.titleIconUrl {
let url = NSURL(string: tmpurl)
imageView?.kf_setImageWithURL(url)
}
titleLabel?.text = model.itemTitle
let str = NSString(string: model.itemTitle!)
let maxWidth = screenWidth-2*space-100
let attr = [NSFontAttributeName: UIFont.systemFontOfSize(16)]
let width = str.boundingRectWithSize(CGSizeMake(maxWidth, 44), options: .UsesLineFragmentOrigin, attributes: attr, context: nil).size.width
titleLabel?.frame = CGRectMake(50, 0, width, 44)
if listModel?.itemTitle == "今日限免" || listModel?.itemTitle == "排行" || listModel?.itemTitle == "不知道什么鬼" {
moreLabel?.text = nil
}else {
moreLabel?.text = model.description1
}
//排行和每日限免的右侧视图不同,init的时候listModel为nil
if listModel?.itemTitle == "每日限免" {
moreIcon = UIImageView(image: UIImage(named: "freeLook"))
moreIcon!.contentMode = .ScaleAspectFill
moreIcon!.clipsToBounds = true
bgView!.addSubview(moreIcon!)
moreIcon!.snp_makeConstraints { (make) in
make.centerY.equalTo(bgView!)
make.right.equalTo(bgView!).offset(-10)
make.width.equalTo(50)
make.height.equalTo(15)//头部更多icon大小11x21
}
}else if listModel?.itemTitle == "排行" || listModel?.itemTitle == "不知道什么鬼"{
moreIcon?.hidden = true
}else {
moreIcon = UIImageView(image: UIImage(named: "recommendview_icon_more_5x10_"))
moreIcon!.contentMode = .ScaleAspectFill
moreIcon!.clipsToBounds = true
bgView!.addSubview(moreIcon!)
moreIcon!.snp_makeConstraints { (make) in
make.centerY.equalTo(bgView!)
make.right.equalTo(bgView!).offset(-10)
make.width.equalTo(11)
make.height.equalTo(15)//头部更多icon大小11x21
}
moreLabel?.snp_makeConstraints(closure: { (make) in
make.right.equalTo(moreIcon!.snp_left)
make.top.bottom.equalTo(bgView!)
make.width.equalTo(50)//给了更多label 50的宽度
})
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | b9aef576c7a49d67100a48e0d2a8c89c | 36.147287 | 147 | 0.594533 | 4.408464 | false | false | false | false |
ahoppen/swift | test/IRGen/prespecialized-metadata/struct-outmodule-1argument-1distinct_use-struct-inmodule.swift | 19 | 4319 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s8Argument03OneA0Vy4main03TheA0VGMN" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// : i8** getelementptr inbounds (
// : %swift.vwtable,
// : %swift.vwtable* @"
// CHECK-SAME: $s8Argument03OneA0Vy4main03TheA0VGWV
// : ",
// : i32 0,
// : i32 0
// : ),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: $s8Argument03OneA0VMn
// CHECK-SAME: %swift.type* bitcast (
// CHECK-SAME: [[INT]]* getelementptr inbounds (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: <{
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32
// CHECK-SAME: }>*,
// CHECK-SAME: i32,
// : [
// : 4 x i8
// : ],
// CHECK-SAME: i64
// CHECK-SAME: }>,
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: <{
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32
// CHECK-SAME: }>*,
// CHECK-SAME: i32,
// : [
// : 4 x i8
// : ],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main11TheArgumentVMf",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ) to %swift.type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{8|4}},
// TRAILING FLAGS: ...01
// ^ statically specialized canonical (false)
// ^ statically specialized (true)
// CHECK-SAME: i64 1
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Argument
struct TheArgument {
let value: Int
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[CANONICALIZED_METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @swift_getCanonicalSpecializedMetadata(
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s8Argument03OneA0Vy4main03TheA0VGMN" to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: %swift.type** @"$s8Argument03OneA0Vy4main03TheA0VGMJ"
// CHECK-SAME: )
// CHECK-NEXT: [[CANONICALIZED_METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[CANONICALIZED_METADATA_RESPONSE]], 0
// CHECK-NEXT: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[CANONICALIZED_METADATA]]
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( OneArgument(TheArgument(value: 13)) )
}
doit()
| apache-2.0 | e146d4577aa54830edb3e9f14b696486 | 34.113821 | 278 | 0.536698 | 3.111671 | false | false | false | false |
yanagiba/swift-ast | Sources/AST/Statement/DoStatement.swift | 2 | 2161 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class DoStatement : ASTNode, Statement {
public struct CatchClause {
public let pattern: Pattern?
public let whereExpression: Expression?
public let codeBlock: CodeBlock
public init(
pattern: Pattern? = nil,
whereExpression: Expression? = nil,
codeBlock: CodeBlock
) {
self.pattern = pattern
self.whereExpression = whereExpression
self.codeBlock = codeBlock
}
}
public let codeBlock: CodeBlock
public private(set) var catchClauses: [CatchClause]
public init(codeBlock: CodeBlock, catchClauses: [CatchClause] = []) {
self.codeBlock = codeBlock
self.catchClauses = catchClauses
}
// MARK: - Node Mutations
public func replaceCatchClause(at index: Int, with catchClause: CatchClause) {
guard index >= 0 && index < catchClauses.count else { return }
catchClauses[index] = catchClause
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
return (["do \(codeBlock.textDescription)"] +
catchClauses.map({ $0.textDescription })).joined(separator: " ")
}
}
extension DoStatement.CatchClause : ASTTextRepresentable {
public var textDescription: String {
var patternText = ""
if let pattern = pattern {
patternText = " \(pattern.textDescription)"
}
var whereText = ""
if let whereExpr = whereExpression {
whereText = " where \(whereExpr.textDescription)"
}
return "catch\(patternText)\(whereText) \(codeBlock.textDescription)"
}
}
| apache-2.0 | 5b625f15561693ebaa37aef7c819ab6a | 30.318841 | 85 | 0.705229 | 4.637339 | false | false | false | false |
fredrikcollden/LittleMaestro | NightLevel.swift | 1 | 7515 | //
// NightLevel.swift
// MaestroLevel
//
// Created by Fredrik Colldén on 2015-11-17.
// Copyright © 2015 Marie. All rights reserved.
//
import SpriteKit
protocol LevelDelegate {
func playAll()
}
class NightLevel: SKNode {
var movables: [SK3DNode] = []
let zFactor = 2
var mainLayer = SKSpriteNode()
var backLayer1 = SKSpriteNode()
var backLayer2 = SKSpriteNode() //stand still
var frontLayer1 = SKSpriteNode()
var fl1z = CGFloat(2)
var mz = CGFloat(1)
var bl1z = CGFloat(0.1)
var bl2z = CGFloat(0)
var levelDelegate: LevelDelegate?
var numberOfBars: Int
var sceneSize: CGSize
init (numberOfBars:Int, sceneSize:CGSize) {
self.sceneSize = sceneSize
self.numberOfBars = numberOfBars
let skyTexture = SKTexture(imageNamed: "nightsky")
let moonTexture = SKTexture(imageNamed: "moon")
let pole = SKTexture(imageNamed: "pole")
let wire = SKTexture(imageNamed: "wire")
let fence = SKTexture(imageNamed: "fence")
let cloud1 = SKTexture(imageNamed: "cloud1")
print("scenesize: \(sceneSize)")
let wireOffset = GameData.sharedInstance.noteHeight*1
let wireSpacing = GameData.sharedInstance.noteHeight*2
for i in 0 ... 4{
let wire = SKSpriteNode(texture: wire)
wire.size.width = sceneSize.width * CGFloat(numberOfBars)
print("wiresize \(wire.size.width)")
wire.anchorPoint.x = 0
wire.position.y = sceneSize.height - (wireSpacing*CGFloat(i) + wireOffset)
wire.position.x = 0
wire.zPosition = 10
self.mainLayer.addChild(wire)
}
for i in 0 ... numberOfBars{
let poleLeft = SKSpriteNode(texture: pole)
poleLeft.zPosition = 11
poleLeft.anchorPoint = CGPoint(x: 1, y: 1)
poleLeft.position = CGPoint(x: (sceneSize.width * CGFloat(i))-20, y: (sceneSize.height*0.96))
self.mainLayer.addChild(poleLeft)
}
for _ in 0 ... 2{
let cloud1 = SKSpriteNode(texture: cloud1)
cloud1.size.height *= GameData.sharedInstance.deviceScale
cloud1.size.width *= GameData.sharedInstance.deviceScale
cloud1.anchorPoint = CGPoint(x: 0, y: 1)
let cloudX = (CGFloat(arc4random_uniform(UInt32(sceneSize.width))))/(1-bl1z)
let cloudY = sceneSize.height - (CGFloat(arc4random_uniform(UInt32(sceneSize.height*0.3))))
cloud1.zPosition = 5
cloud1.position = CGPoint(x: cloudX, y: cloudY)
let randomMovement = CGFloat(arc4random_uniform(UInt32(200))+400)
let randomTime = Double(arc4random_uniform(UInt32(10))+60)
let animIn = SKAction.moveByX(-randomMovement, y: 0, duration: randomTime)
let animOut = animIn.reversedAction()
let actionAnim = SKAction.repeatActionForever(SKAction.sequence([animIn, animOut]))
cloud1.runAction(actionAnim)
self.backLayer1.addChild(cloud1)
}
self.mainLayer.size.width = sceneSize.width * CGFloat(numberOfBars)
self.mainLayer.size.height = sceneSize.height
let sky = SKSpriteNode(texture: skyTexture)
sky.zPosition = 1
sky.anchorPoint = CGPointZero
sky.size = sceneSize
sky.position = CGPoint(x: (0), y: 0)
self.backLayer2.addChild(sky)
let moon = SKSpriteNode(texture: moonTexture)
moon.zPosition = 2
moon.anchorPoint = CGPoint(x: 0, y: 0.5)
moon.size.height *= GameData.sharedInstance.deviceScale
moon.size.width *= GameData.sharedInstance.deviceScale
moon.position = CGPoint(x: (0), y: sceneSize.height*0.9)
self.backLayer2.addChild(moon)
print("\(numberOfBars) --- \(numberOfBars*Int(fl1z))")
for i in 0 ... (numberOfBars*Int(fl1z)-2){
let fence = SKSpriteNode(texture: fence)
fence.size.width = sceneSize.width
fence.zPosition = 21
fence.anchorPoint = CGPoint(x: 0, y: 1)
fence.position = CGPoint(x: (sceneSize.width * CGFloat(i)), y: 100*GameData.sharedInstance.deviceScale)
self.frontLayer1.addChild(fence)
print("add fence \(fence.position)")
}
super.init()
self.zPosition = 0
mainLayer.zPosition = 10
backLayer2.zPosition = 1
backLayer1.zPosition = 5
frontLayer1.zPosition = 20
self.addChild(self.mainLayer)
self.addChild(self.backLayer2)
self.addChild(self.backLayer1)
self.addChild(self.frontLayer1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveTo(barNum: Int, playWholeSong: Bool){
let myDuration = Double(4)
let moveLeft = SKAction.moveToX(-(self.sceneSize.width * CGFloat(barNum)), duration: myDuration)
let moveLeftReverse = SKAction.moveToX((self.sceneSize.width * CGFloat(barNum)), duration: myDuration)
let moveLeftFront1 = SKAction.moveToX((1-fl1z)*(self.sceneSize.width * CGFloat(barNum)), duration: myDuration)
let moveLeftBack1 = SKAction.moveToX((1-bl1z)*(self.sceneSize.width * CGFloat(barNum)), duration: myDuration)
moveLeft.timingMode = SKActionTimingMode.EaseInEaseOut
moveLeftReverse.timingMode = SKActionTimingMode.EaseInEaseOut
moveLeftFront1.timingMode = SKActionTimingMode.EaseInEaseOut
moveLeftBack1.timingMode = SKActionTimingMode.EaseInEaseOut
if playWholeSong {
self.runAction(moveLeft, completion: playAll)
self.backLayer2.runAction(moveLeftReverse)
self.frontLayer1.runAction(moveLeftFront1)
self.backLayer1.runAction(moveLeftBack1)
} else {
self.runAction(moveLeft)
self.backLayer2.runAction(moveLeftReverse)
self.frontLayer1.runAction(moveLeftFront1)
self.backLayer1.runAction(moveLeftBack1)
}
}
func moveWhole(tempo:CGFloat) {
let moveAll = SKAction.moveToX(-(sceneSize.width * CGFloat(self.numberOfBars-1)), duration:
Double(tempo/1200*CGFloat(self.numberOfBars*32)))
let moveAllReverse = SKAction.moveToX((sceneSize.width * CGFloat(self.numberOfBars-1)), duration:
Double(tempo/1200*CGFloat(self.numberOfBars*32)))
let moveAllFront1 = SKAction.moveToX((1-fl1z)*(sceneSize.width * CGFloat(self.numberOfBars-1)), duration:
Double(tempo/1200*CGFloat(self.numberOfBars*32)))
let moveAllBack1 = SKAction.moveToX((1-bl1z)*(sceneSize.width * CGFloat(self.numberOfBars-1)), duration:
Double(tempo/1200*CGFloat(self.numberOfBars*32)))
moveAll.timingMode = SKActionTimingMode.EaseInEaseOut
moveAllReverse.timingMode = SKActionTimingMode.EaseInEaseOut
moveAllFront1.timingMode = SKActionTimingMode.EaseInEaseOut
moveAllBack1.timingMode = SKActionTimingMode.EaseInEaseOut
self.backLayer2.runAction(moveAllReverse)
self.backLayer1.runAction(moveAllBack1)
self.frontLayer1.runAction(moveAllFront1)
self.runAction(moveAll)
}
func playAll(){
levelDelegate?.playAll()
}
}
| lgpl-3.0 | 736ab39f0c0ecfb9b5bba0ca50aed14f | 38.962766 | 118 | 0.630108 | 4.121229 | false | false | false | false |
Genhain/OAuth-Moya-Promise | OAuth-Moya-Promise/Classes/OAuthMoyaPromise.swift | 1 | 3435 |
import Foundation
import Moya
import Moya_ObjectMapper
import ObjectMapper
import PromiseKit
public class OAuthMoyaPromise<Target>: MoyaProvider<Target> where Target: TargetType {
private(set) var oAuth: OAuth
public init(oAuth: OAuth,
endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(),
plugins: [PluginType] = []) {
self.oAuth = oAuth
let requesPromisetClosure: RequestClosure = { endpoint, requestResult in
requestClosure(endpoint, requestResult)
if let request = endpoint.urlRequest {
oAuth.authenticateRequest(request) { result in
switch result {
case .success(let request):
requestResult(.success(request))
case .failure(let error):
requestResult(.failure(MoyaError.underlying(error)))
}
}
} else {
requestResult(.failure(MoyaError.requestMapping(endpoint.url)))
}
}
super.init(endpointClosure: endpointClosure,
requestClosure: requesPromisetClosure,
stubClosure: stubClosure,
manager: manager,
plugins: [NetworkLoggerPlugin(verbose: true)])
}
}
public extension MoyaProvider {
public func requestPromise<T: BaseMappable>(_ target: Target, type: T.Type, atKeyPath keyPath: String? = nil) -> Promise<T> {
return Promise<T> { [weak self] fulfill, reject in
self?.request(target) { result in
switch result {
case .success(var response):
do {
response = try response.filterSuccessfulStatusAndRedirectCodes()
fulfill(try response.mapObject(T.self, withKeyPath: keyPath))
} catch let error {
reject(error)
}
case .failure(let error):
reject(error)
}
}
}
}
public func requestPromiseForCollection<T: BaseMappable>(_ target: Target, type: T.Type, atKeyPath keyPath: String? = nil) -> Promise<[T]> {
return Promise<[T]> { [weak self] fulfill, reject in
self?.request(target) { result in
switch result {
case .success(var response):
do {
response = try response.filterSuccessfulStatusAndRedirectCodes()
fulfill(try response.mapArray(T.self, withKeyPath: keyPath))
} catch let error {
reject(error)
}
case .failure(let error):
reject(error)
}
}
}
}
}
extension Moya.Response {
typealias JSON = [String: Any]
func mapObject<T: BaseMappable>(_ type: T.Type = T.self, withKeyPath keyPath: String?) throws -> T {
if let keyPath = keyPath {
guard let JSONObject = try self.mapJSON() as? JSON,
let JSONForKeyPath = JSONObject[keyPath] as? JSON,
let parsedJSONObject = Mapper<T>().map(JSON:JSONForKeyPath) else {
throw MoyaError.jsonMapping(self)
}
return parsedJSONObject
} else {
return try self.mapObject(T.self)
}
}
func mapArray<T: BaseMappable>(_ type: T.Type = T.self, withKeyPath keyPath: String?) throws -> [T] {
if let keyPath = keyPath {
guard let JSONObject = try self.mapJSON() as? JSON,
let JSONForKeyPath = JSONObject[keyPath],
let parsedJSONObject = Mapper<T>().mapArray(JSONObject: JSONForKeyPath) else {
throw MoyaError.jsonMapping(self)
}
return parsedJSONObject
} else {
return try self.mapArray(T.self)
}
}
}
| mit | 690ef27bc8e15662422f7839e0113318 | 29.39823 | 141 | 0.68559 | 3.975694 | false | false | false | false |
HIIT/JustUsed | JustUsed/DiMe Data/Location.swift | 1 | 3718 | //
// Copyright (c) 2015 Aalto University
//
// 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 CoreLocation
struct Location: Dictionariable, Equatable, Hashable {
let latitude: Double
let longitude: Double
let altitude: Double?
let horizAccuracy: Double
let vertAccuracy: Double?
let bearing: Double?
let speed: Double?
var descriptionLine: String? // not initialized, can be changed later
var hashValue: Int { get {
var outH = latitude.hashValue
outH ^= longitude.hashValue
if let al = altitude {
outH ^= al.hashValue
}
return outH
} }
init(fromCLLocation loc: CLLocation) {
latitude = loc.coordinate.latitude
longitude = loc.coordinate.longitude
horizAccuracy = loc.horizontalAccuracy
if loc.verticalAccuracy > 0 {
vertAccuracy = loc.verticalAccuracy
altitude = loc.altitude
} else {
vertAccuracy = nil
altitude = nil
}
if loc.speed > 0 {
speed = loc.speed
} else {
speed = nil
}
if loc.course > 0 {
bearing = loc.course
} else {
bearing = nil
}
}
init(fromJSON json: JSON) {
latitude = json["latitude"].doubleValue
longitude = json["longitude"].doubleValue
altitude = json["altitude"].double
horizAccuracy = json["horizAccuracy"].doubleValue
vertAccuracy = json["vertAccuracy"].double
bearing = json["bearing"].double
speed = json["speed"].double
descriptionLine = json["descriptionLine"].string
}
/// Returns itself in a (json-able) dict
func getDict() -> [String: Any] {
var retDict = [String: Any]()
retDict["latitude"] = latitude
retDict["longitude"] = longitude
retDict["horizAccuracy"] = horizAccuracy
if let altit = altitude {
retDict["altitude"] = altit
retDict["vertAccuracy"] = vertAccuracy
}
if let sp = speed {
retDict["speed"] = sp
}
if let be = bearing {
retDict["bearing"] = be
}
if let desc = descriptionLine {
retDict["descriptionLine"] = desc
}
return retDict
}
}
func ==(rhs: Location, lhs: Location) -> Bool {
if let ralt = rhs.altitude, let lalt = lhs.altitude {
return ralt == lalt && rhs.latitude == lhs.latitude && rhs.longitude == lhs.longitude
} else {
return rhs.latitude == lhs.latitude && rhs.longitude == lhs.longitude
}
}
| mit | c6fe872dd80b8744126cebe21d26872c | 32.196429 | 93 | 0.62184 | 4.624378 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Utility/Views/AttributedText.swift | 2 | 2545 | //
// AttributedText.swift
// Neocom
//
// Created by Artem Shimanski on 12/3/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import SwiftUI
struct AttributedText: View {
private var text: NSAttributedString
private var preferredMaxLayoutWidth: CGFloat
init(_ text: NSAttributedString, preferredMaxLayoutWidth: CGFloat) {
self.text = text
self.preferredMaxLayoutWidth = preferredMaxLayoutWidth
}
var body: some View {
AttributedTextView(text: text, preferredMaxLayoutWidth: preferredMaxLayoutWidth)
}
}
fileprivate struct AttributedTextView: UIViewRepresentable {
var text: NSAttributedString
var preferredMaxLayoutWidth: CGFloat
class Coordinator: NSObject, UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
func makeUIView(context: UIViewRepresentableContext<AttributedTextView>) -> SelfSizedTextView {
let view = SelfSizedTextView()
view.delegate = context.coordinator
view.attributedText = text
view.translatesAutoresizingMaskIntoConstraints = false
view.isScrollEnabled = false
view.backgroundColor = .clear
view.textContainerInset = .zero
view.textContainer.lineFragmentPadding = 0
view.layoutManager.usesFontLeading = false
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.setContentHuggingPriority(.defaultHigh, for: .vertical)
view.isEditable = false
return view
}
func updateUIView(_ uiView: SelfSizedTextView, context: UIViewRepresentableContext<AttributedTextView>) {
uiView.attributedText = text
uiView.style = .preferredMaxLayoutWidth(preferredMaxLayoutWidth)
}
}
struct AttributedTextPreview: View {
@State var text: NSAttributedString = NSAttributedString(string: repeatElement("Hello World ", count: 50).joined())
var body: some View {
GeometryReader { geometry in
VStack {
AttributedText(self.text, preferredMaxLayoutWidth: geometry.size.width - 30)
.background(Color.gray)
}.padding().background(Color.green)
}
}
}
struct AttributedText_Previews: PreviewProvider {
static var previews: some View {
AttributedTextPreview()
}
}
| lgpl-2.1 | f05a2447f0172d4219174b8902ec9fb0 | 32.038961 | 148 | 0.690252 | 5.530435 | false | false | false | false |
tuannme/Up | Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorViewable.swift | 2 | 3622 | //
// NVActivityIndicatorViewable.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/**
* UIViewController conforms this protocol to be able to display NVActivityIndicatorView as UI blocker.
*
* This extends abilities of UIViewController to display and remove UI blocker.
*/
public protocol NVActivityIndicatorViewable { }
public extension NVActivityIndicatorViewable where Self: UIViewController {
/**
Display UI blocker.
Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params.
- parameter size: size of activity indicator view.
- parameter message: message displayed under activity indicator view.
- parameter messageFont: font of message displayed under activity indicator view.
- parameter type: animation type.
- parameter color: color of activity indicator view.
- parameter padding: padding of activity indicator view.
- parameter displayTimeThreshold: display time threshold to actually display UI blocker.
- parameter minimumDisplayTime: minimum display time of UI blocker.
*/
public final func startAnimating(
_ size: CGSize? = nil,
message: String? = nil,
messageFont: UIFont? = nil,
type: NVActivityIndicatorType? = nil,
color: UIColor? = nil,
padding: CGFloat? = nil,
displayTimeThreshold: Int? = nil,
minimumDisplayTime: Int? = nil,
backgroundColor: UIColor? = nil,
textColor: UIColor? = nil) {
let activityData = ActivityData(size: size,
message: message,
messageFont: messageFont,
type: type,
color: color,
padding: padding,
displayTimeThreshold: displayTimeThreshold,
minimumDisplayTime: minimumDisplayTime,
backgroundColor: backgroundColor,
textColor: textColor)
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)
}
/**
Remove UI blocker.
*/
public final func stopAnimating() {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
}
}
| mit | 7a8d085e519265ab985933163239fa72 | 42.119048 | 104 | 0.64053 | 5.694969 | false | false | false | false |
tzef/BunbunuCustom | BunbunuCustom/BunbunuCustom/ImageView/CircleImageView.swift | 1 | 2205 | //
// CircleImageView.swift
// BunbunuCustom
//
// Created by LEE ZHE YU on 2016/7/7.
// Copyright © 2016年 LEE ZHE YU. All rights reserved.
//
import UIKit
@IBDesignable
class CircleImageView: UIView {
var imgRatio: CGFloat = 1
var imgSize = CGSizeZero
@IBInspectable var image: UIImage? {
didSet {
if let w = image?.size.width, let h = image?.size.height {
imgRatio = w / h
imgSize = CGSize(width: w, height: h)
}
self.setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
var size = CGSize(width: imgSize.width, height: imgSize.height)
var imgRect = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
let rectRatio = rect.width / rect.height
switch contentMode {
case .ScaleAspectFill:
if rectRatio > imgRatio {
size = CGSize(width: rect.width, height: rect.width / imgRatio)
imgRect = CGRect(x: 0, y: (rect.height - size.height) / 2, width: size.width, height: size.height)
} else {
size = CGSize(width: rect.height * imgRatio, height: rect.height)
imgRect = CGRect(x: (rect.width - size.width) / 2, y: 0, width: size.width, height: size.height)
}
case .ScaleAspectFit:
if rectRatio > imgRatio {
size = CGSize(width: rect.height * imgRatio, height: rect.height)
imgRect = CGRect(x: (rect.width - size.width) / 2, y: 0, width: size.width, height: size.height)
} else {
size = CGSize(width: rect.width, height: rect.width / imgRatio)
imgRect = CGRect(x: 0, y: (rect.height - size.height) / 2, width: size.width, height: size.height)
}
default:
break
}
image?.drawInRect(imgRect)
let circleShapeLayer = CAShapeLayer()
circleShapeLayer.path = UIBezierPath(ovalInRect: rect).CGPath
self.layer.mask = circleShapeLayer
}
override var contentMode: UIViewContentMode {
didSet {
self.setNeedsDisplay()
}
}
}
| mit | 32b584ea37012f0d96f2a03389a737e4 | 34.516129 | 114 | 0.56267 | 4.115888 | false | false | false | false |
threemonkee/VCLabs | VCLabs/UIKit Catalog/Source Code/AlertControllerViewController.swift | 1 | 12653 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The view controller that demonstrates how to use UIAlertController.
*/
import UIKit
class AlertControllerViewController : UITableViewController {
// MARK: Properties
weak var secureTextAlertAction: UIAlertAction?
/*
A matrix of closures that should be invoked based on which table view
cell is tapped (index by section, row).
*/
var actionMap: [[(selectedIndexPath: NSIndexPath) -> Void]] {
return [
// Alert style alerts.
[
showSimpleAlert,
showOkayCancelAlert,
showOtherAlert,
showTextEntryAlert,
showSecureTextEntryAlert
],
// Action sheet style alerts.
[
showOkayCancelActionSheet,
showOtherActionSheet
]
]
}
// MARK: UIAlertControllerStyleAlert Style Alerts
/// Show an alert with an "Okay" button.
func showSimpleAlert(_: NSIndexPath) {
let title = NSLocalizedString("A Short Title is Best", comment: "")
let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert's cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
/// Show an alert with an "Okay" and "Cancel" button.
func showOkayCancelAlert(_: NSIndexPath) {
let title = NSLocalizedString("A Short Title is Best", comment: "")
let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitle = NSLocalizedString("OK", comment: "")
let alertCotroller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { _ in
NSLog("The \"Okay/Cancel\" alert's cancel action occured.")
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { _ in
NSLog("The \"Okay/Cancel\" alert's other action occured.")
}
// Add the actions.
alertCotroller.addAction(cancelAction)
alertCotroller.addAction(otherAction)
presentViewController(alertCotroller, animated: true, completion: nil)
}
/// Show an alert with two custom buttons.
func showOtherAlert(_: NSIndexPath) {
let title = NSLocalizedString("A Short Title is Best", comment: "")
let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitleOne = NSLocalizedString("Choice One", comment: "")
let otherButtonTitleTwo = NSLocalizedString("Choice Two", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The \"Other\" alert's cancel action occured.")
}
let otherButtonOneAction = UIAlertAction(title: otherButtonTitleOne, style: .Default) { _ in
NSLog("The \"Other\" alert's other button one action occured.")
}
let otherButtonTwoAction = UIAlertAction(title: otherButtonTitleTwo, style: .Default) { _ in
NSLog("The \"Other\" alert's other button two action occured.")
}
// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(otherButtonOneAction)
alertController.addAction(otherButtonTwoAction)
presentViewController(alertController, animated: true, completion: nil)
}
/// Show a text entry alert with two custom buttons.
func showTextEntryAlert(_: NSIndexPath) {
let title = NSLocalizedString("A Short Title is Best", comment: "")
let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Add the text field for text entry.
alertController.addTextFieldWithConfigurationHandler { textField in
// If you need to customize the text field, you can do so here.
}
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { _ in
NSLog("The \"Text Entry\" alert's cancel action occured.")
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { _ in
NSLog("The \"Text Entry\" alert's other action occured.")
}
// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(otherAction)
presentViewController(alertController, animated: true, completion: nil)
}
/// Show a secure text entry alert with two custom buttons.
func showSecureTextEntryAlert(_: NSIndexPath) {
let title = NSLocalizedString("A Short Title is Best", comment: "")
let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Add the text field for the secure text entry.
alertController.addTextFieldWithConfigurationHandler { textField in
/*
Listen for changes to the text field's text so that we can toggle the current
action's enabled property based on whether the user has entered a sufficiently
secure entry.
*/
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
textField.secureTextEntry = true
}
/*
Stop listening for text change notifications on the text field. This
closure will be called in the two action handlers.
*/
let removeTextFieldObserver: Void -> Void = {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields!.first)
}
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { _ in
NSLog("The \"Secure Text Entry\" alert's cancel action occured.")
removeTextFieldObserver()
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { _ in
NSLog("The \"Secure Text Entry\" alert's other action occured.")
removeTextFieldObserver()
}
// The text field initially has no text in the text field, so we'll disable it.
otherAction.enabled = false
/*
Hold onto the secure text alert action to toggle the enabled / disabled
state when the text changed.
*/
secureTextAlertAction = otherAction
// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(otherAction)
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: UIAlertControllerStyleActionSheet Style Alerts
/// Show a dialog with an "Okay" and "Cancel" button.
func showOkayCancelActionSheet(selectedIndexPath: NSIndexPath) {
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "OK")
let destructiveButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { _ in
NSLog("The \"Okay/Cancel\" alert action sheet's cancel action occured.")
}
let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { _ in
NSLog("The \"Okay/Cancel\" alert action sheet's destructive action occured.")
}
// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(destructiveAction)
// Configure the alert controller's popover presentation controller if it has one.
if let popoverPresentationController = alertController.popoverPresentationController {
// This method expects a valid cell to display from.
let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)!
popoverPresentationController.sourceRect = selectedCell.frame
popoverPresentationController.sourceView = view
popoverPresentationController.permittedArrowDirections = .Up
}
presentViewController(alertController, animated: true, completion: nil)
}
/// Show a dialog with two custom buttons.
func showOtherActionSheet(selectedIndexPath: NSIndexPath) {
let destructiveButtonTitle = NSLocalizedString("Destructive Choice", comment: "")
let otherButtonTitle = NSLocalizedString("Safe Choice", comment: "")
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
// Create the actions.
let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { _ in
NSLog("The \"Other\" alert action sheet's destructive action occured.")
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { _ in
NSLog("The \"Other\" alert action sheet's other action occured.")
}
// Add the actions.
alertController.addAction(destructiveAction)
alertController.addAction(otherAction)
// Configure the alert controller's popover presentation controller if it has one.
if let popoverPresentationController = alertController.popoverPresentationController {
// This method expects a valid cell to display from.
let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)!
popoverPresentationController.sourceRect = selectedCell.frame
popoverPresentationController.sourceView = view
popoverPresentationController.permittedArrowDirections = .Up
}
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: UITextFieldTextDidChangeNotification
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
let textField = notification.object as! UITextField
// Enforce a minimum length of >= 5 characters for secure text alerts.
if let text = textField.text {
secureTextAlertAction!.enabled = text.characters.count >= 5
}
else {
secureTextAlertAction!.enabled = false
}
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let action = actionMap[indexPath.section][indexPath.row]
action(selectedIndexPath: indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| gpl-2.0 | cb39d8c51e8a0b5e5386200d323f0e00 | 42.325342 | 184 | 0.647933 | 5.919981 | false | false | false | false |
codelynx/silvershadow | Silvershadow/RenderContext.swift | 1 | 4630 | //
// RenderContext.swift
// Silvershadow
//
// Created by Kaz Yoshikawa on 12/12/16.
// Copyright © 2016 Electricwoods LLC. All rights reserved.
//
import Foundation
import MetalKit
import GLKit
//
// RenderContextState
//
struct RenderContextState {
var renderPassDescriptor: MTLRenderPassDescriptor
var commandQueue: MTLCommandQueue
var contentSize: CGSize
var deviceSize: CGSize // eg. MTKView's size, offscreen bitmap's size etc.
var transform: GLKMatrix4
var zoomScale: CGFloat
}
struct Stack<Element> {
private var content : [Element]
init() {
content = []
}
mutating
func push(_ element: Element) {
content.append(element)
}
mutating
func pop() -> Element? {
guard let l = content.last else { return nil }
defer {
content.removeLast()
}
return l
}
}
//
// RenderContext
//
class RenderContext {
var current: RenderContextState
private var contextStack = Stack<RenderContextState>()
var renderPassDescriptor: MTLRenderPassDescriptor {
get { return current.renderPassDescriptor }
set { current.renderPassDescriptor = newValue }
}
var commandQueue: MTLCommandQueue {
get { return current.commandQueue }
set { self.current.commandQueue = newValue }
}
var contentSize: CGSize {
get { return current.contentSize }
set { self.current.contentSize = newValue }
}
var deviceSize: CGSize { // eg. MTKView's size, offscreen bitmap's size etc.
get { return current.deviceSize }
set { self.current.deviceSize = newValue }
}
var transform: GLKMatrix4 {
get { return current.transform }
set { self.current.transform = newValue }
}
var zoomScale: CGFloat {
get { return current.zoomScale }
set {}
}
var device: MTLDevice { return commandQueue.device }
//
lazy var shadingTexture: MTLTexture = {
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .`default`,
width: Int(self.deviceSize.width), height: Int(self.deviceSize.height), mipmapped: false)
descriptor.usage = [.shaderRead, .renderTarget]
return self.device.makeTexture(descriptor: descriptor)!
}()
lazy var brushShape: MTLTexture = {
return self.device.texture(of: XImage(named: "Particle")!)!
}()
lazy var brushPattern: MTLTexture = {
return self.device.texture(of: XImage(named: "Pencil")!)!
}()
init(
renderPassDescriptor: MTLRenderPassDescriptor,
commandQueue: MTLCommandQueue,
contentSize: CGSize,
deviceSize: CGSize,
transform: GLKMatrix4,
zoomScale: CGFloat = 1
) {
self.current = RenderContextState(
renderPassDescriptor: renderPassDescriptor, commandQueue: commandQueue,
contentSize: contentSize, deviceSize: deviceSize, transform: transform, zoomScale: zoomScale)
}
func makeCommandBuffer() -> MTLCommandBuffer {
return commandQueue.makeCommandBuffer()!
}
// MARK: -
func pushContext() {
let copiedState = self.current
let copiedRenderpassDescriptor = self.current.renderPassDescriptor.copy() as! MTLRenderPassDescriptor
self.current.renderPassDescriptor = copiedRenderpassDescriptor
self.contextStack.push(copiedState)
}
func popContext() {
guard let current = contextStack.pop() else { fatalError("cannot pop") }
self.current = current
}
}
extension RenderContext {
func widthCGContext(_ closure: (CGContext) -> ()) {
let (width, height, bytesPerRow) = (Int(contentSize.width), Int(contentSize.height), Int(contentSize.width) * 4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow,
space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return }
context.clear(CGRect(size:contentSize))
let transform = CGAffineTransform.identity
.translatedBy(x: 0, y: contentSize.height)
.scaledBy(x: 1, y: -1)
context.concatenate(transform)
context.saveGState()
#if os(iOS)
UIGraphicsPushContext(context)
#elseif os(macOS)
let savedContext = NSGraphicsContext.current
let graphicsContext = NSGraphicsContext(cgContext: context, flipped: false)
NSGraphicsContext.current = graphicsContext
#endif
closure(context)
#if os(iOS)
UIGraphicsPopContext()
#elseif os(macOS)
NSGraphicsContext.current = savedContext
#endif
context.restoreGState()
guard let cgImage = context.makeImage() else { fatalError("failed creating cgImage") }
guard let texture = self.device.texture(of: cgImage) else { fatalError("failed creating texture") }
self.render(texture: texture, in: Rect(0, 0, width, height))
}
}
| mit | 6a65deb37d2903aa601600d8d31acbda | 26.390533 | 119 | 0.731259 | 3.870401 | false | false | false | false |
srn214/Floral | Floral/Pods/WCDB.swift/swift/source/abstract/ColumnDef.swift | 1 | 3663 | /*
* Tencent is pleased to support the open source community by making
* WCDB available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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
public final class ColumnDef: Describable {
public private(set) var description: String
public init(with columnConvertible: ColumnConvertible, and optionalType: ColumnType? = nil) {
description = columnConvertible.asColumn().description
if let type = optionalType {
description.append(" \(type.description)")
}
}
@discardableResult
public func makePrimary(orderBy term: OrderTerm? = nil,
isAutoIncrement: Bool = false,
onConflict conflict: Conflict? = nil) -> ColumnDef {
description.append(" PRIMARY KEY")
if term != nil {
description.append(" \(term!.description)")
}
if isAutoIncrement {
description.append(" AUTOINCREMENT")
}
if conflict != nil {
description.append(" ON CONFLICT \(conflict!.description)")
}
return self
}
public enum DefaultType: Describable {
case null
case int32(Int32)
case int64(Int64)
case bool(Bool)
case text(String)
case float(Double)
case BLOB(Data)
case expression(Expression)
case currentTime
case currentDate
case currentTimestamp
public var description: String {
switch self {
case .null:
return "NULL"
case .int32(let value):
return LiteralValue(value).description
case .int64(let value):
return LiteralValue(value).description
case .bool(let value):
return LiteralValue(value).description
case .text(let value):
return LiteralValue(value).description
case .float(let value):
return LiteralValue(value).description
case .BLOB(let value):
return LiteralValue(value).description
case .expression(let value):
return value.description
case .currentDate:
return "CURRENT_DATE"
case .currentTime:
return "CURRENT_TIME"
case .currentTimestamp:
return "CURRENT_TIMESTAMP"
}
}
}
@discardableResult
public func makeDefault(to defaultValue: DefaultType) -> ColumnDef {
description.append(" DEFAULT \(defaultValue.description)")
return self
}
@discardableResult
public func makeNotNull() -> ColumnDef {
description.append(" NOT NULL")
return self
}
@discardableResult
public func makeUnique() -> ColumnDef {
description.append(" UNIQUE")
return self
}
@discardableResult
public func makeForeignKey(_ foreignKey: ForeignKey) -> ColumnDef {
description.append(" \(foreignKey.description)")
return self
}
}
| mit | ba467ca1b476bb1ca686848a35023d75 | 31.131579 | 97 | 0.606334 | 5.06639 | false | false | false | false |
Lebron1992/SlackTextViewController-Swift | SlackTextViewController-Swift/SlackTextViewController-Swift/Demo/MessageViewController.swift | 1 | 25565 | //
// MessageViewController.swift
// SlackTextViewController-Swift
//
// Created by Lebron on 21/08/2017.
// Copyright © 2017 hacknocraft. All rights reserved.
//
import UIKit
import LoremIpsum
let DEBUG_CUSTOM_TYPING_INDICATOR = false
class MessageViewController: SLKTextViewController {
var messages = [Message]()
var users = ["Allen", "Anna", "Alicia", "Arnold", "Armando", "Antonio", "Brad", "Catalaya", "Christoph", "Emerson", "Eric", "Everyone", "Steve"]
var channels = ["General", "Random", "iOS", "Bugs", "Sports", "Android", "UI", "SSB"]
var emojis = ["-1", "m", "man", "machine", "block-a", "block-b", "bowtie", "boar", "boat", "book", "bookmark", "neckbeard", "metal", "fu", "feelsgood"]
var commands = ["msg", "call", "text", "skype", "kick", "invite"]
var searchResult: [String]?
var pipWindow: UIWindow?
var editingMessage = Message(username: "", text: "")
override var tableView: UITableView? {
return super.tableView
}
// MARK: - Initialization
override func viewDidLoad() {
// Register a SLKTextView subclass, if you need any special appearance and/or behavior customisation.
registerClassForTextView(aClass: MessageTextView.self)
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
// Register a UIView subclass, subclass from SLKBaseTypingIndicatorView, to use a custom typing indicator view.
registerClassForTypingIndicatorView(aClass: TypingIndicatorView.self)
}
super.viewDidLoad()
commonInit()
// Example's configuration
configureDataSource()
configureActionItems()
// SLKTVC's configuration
bounces = true
shakeToClearEnabled = true
isKeyboardPanningEnabled = true
shouldScrollToBottomAfterKeyboardShows = false
isInverted = true
leftButton.setImage(UIImage(named: "icn_upload"), for: UIControlState())
leftButton.tintColor = UIColor.gray
rightButton.setTitle(NSLocalizedString("Send", comment: ""), for: UIControlState())
textInputbar.autoHideRightButton = true
textInputbar.maxCharCount = 256
textInputbar.counterStyle = .split
textInputbar.counterPosition = .top
textInputbar.editorTitle.textColor = UIColor.darkGray
textInputbar.editorLeftButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
textInputbar.editorRightButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
if DEBUG_CUSTOM_TYPING_INDICATOR == false {
typingIndicatorView!.canResignByTouch = true
}
tableView?.separatorStyle = .none
tableView?.register(MessageTableViewCell.self, forCellReuseIdentifier: MessageTableViewCell.kMessengerCellIdentifier)
autoCompletionView?.register(MessageTableViewCell.self, forCellReuseIdentifier: MessageTableViewCell.kAutoCompletionCellIdentifier)
registerPrefixesForAutoCompletion(prefixes: ["@", "#", ":", "+:", "/"])
textView.placeholder = "Message"
textView.registerMarkdownFormattingSymbol("*", title: "Bold")
textView.registerMarkdownFormattingSymbol("~", title: "Strike")
textView.registerMarkdownFormattingSymbol("`", title: "Code")
textView.registerMarkdownFormattingSymbol("```", title: "Preformatted")
textView.registerMarkdownFormattingSymbol(">", title: "Quote")
}
func commonInit() {
if let tableView = tableView {
NotificationCenter.default.addObserver(tableView, selector: #selector(UITableView.reloadData), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(MessageViewController.textInputbarDidMove(_:)), name: NSNotification.Name(rawValue: SLKTextInputbarDidMoveNotification), object: nil)
}
override class func tableViewStyle(for decoder: NSCoder) -> UITableViewStyle {
return .plain
}
// MARK: - Lifeterm
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Overriden Methods
override func ignoreTextInputbarAdjustment() -> Bool {
return super.ignoreTextInputbarAdjustment()
}
override func forceTextInputbarAdjustment(for responder: UIResponder!) -> Bool {
if #available(iOS 8.0, *) {
guard responder is UIAlertController else {
// On iOS 9, returning YES helps keeping the input view visible when the keyboard if presented from another app when using multi-tasking on iPad.
return UIDevice.current.userInterfaceIdiom == .pad
}
return true
} else {
return UIDevice.current.userInterfaceIdiom == .pad
}
}
// Notifies the view controller that the keyboard changed status.
override func didChangeKeyboardStatus(_ status: SLKKeyboardStatus) {
switch status {
case .willShow:
print("Will Show")
case .didShow:
print("Did Show")
case .willHide:
print("Will Hide")
case .didHide:
print("Did Hide")
default:
break
}
}
// Notifies the view controller that the text will update.
override func textWillUpdate() {
super.textWillUpdate()
}
// Notifies the view controller that the text did update.
override func textDidUpdate(animated: Bool) {
super.textDidUpdate(animated: animated)
}
// Notifies the view controller when the left button's action has been triggered, manually.
override func didPressLeftButton(sender: Any!) {
super.didPressLeftButton(sender: sender)
dismissKeyboard(animated: true)
// performSegue(withIdentifier: "Push", sender: nil)
}
// Notifies the view controller when the right button's action has been triggered, manually or by using the keyboard return key.
override func didPressRightButton(sender: Any!) {
// This little trick validates any pending auto-correction or auto-spelling just after hitting the 'Send' button
textView.refreshFirstResponder()
let message = Message(username: LoremIpsum.name(), text: textView.text)
let indexPath = IndexPath(row: 0, section: 0)
let rowAnimation: UITableViewRowAnimation = isInverted ? .bottom : .top
let scrollPosition: UITableViewScrollPosition = isInverted ? .bottom : .top
tableView?.beginUpdates()
messages.insert(message, at: 0)
tableView?.insertRows(at: [indexPath], with: rowAnimation)
tableView?.endUpdates()
tableView?.scrollToRow(at: indexPath, at: scrollPosition, animated: true)
// Fixes the cell from blinking (because of the transform, when using translucent cells)
// See https://github.com/slackhq/SlackTextViewController/issues/94#issuecomment-69929927
tableView?.reloadRows(at: [indexPath], with: .automatic)
super.didPressRightButton(sender: sender)
}
override func didPressArrowKey(keyCommand: UIKeyCommand?) {
guard let keyCommand = keyCommand else { return }
if keyCommand.input == UIKeyInputUpArrow && textView.text.characters.count == 0 {
editLastMessage(nil)
} else {
super.didPressArrowKey(keyCommand: keyCommand)
}
}
override func keyForTextCaching() -> String? {
return Bundle.main.bundleIdentifier
}
// Notifies the view controller when the user has pasted a media (image, video, etc) inside of the text view.
override func didPasteMediaContent(userInfo: [AnyHashable: Any]) {
super.didPasteMediaContent(userInfo: userInfo)
let mediaType = (userInfo[SLKTextViewPastedItemMediaType] as? NSNumber)?.intValue
let contentType = userInfo[SLKTextViewPastedItemContentType]
let data = userInfo[SLKTextViewPastedItemData]
print("didPasteMediaContent : \(String(describing: contentType)) (type = \(String(describing: mediaType)) | data : \(String(describing: data)))")
}
// Notifies the view controller when a user did shake the device to undo the typed text
override func willRequestUndo() {
super.willRequestUndo()
}
// Notifies the view controller when tapped on the right "Accept" button for commiting the edited text
override func didCommitTextEditing(sender: Any) {
editingMessage.text = textView.text
tableView?.reloadData()
super.didCommitTextEditing(sender: sender)
}
// Notifies the view controller when tapped on the left "Cancel" button
override func didCancelTextEditing(sender: Any) {
super.didCancelTextEditing(sender: sender)
}
override func canPressRightButton() -> Bool {
return super.canPressRightButton()
}
override func canShowTypingIndicator() -> Bool {
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
return true
} else {
return super.canShowTypingIndicator()
}
}
override func shouldProcessTextForAutoCompletion() -> Bool {
return true
}
override func didChangeAutoCompletion(prefix: String, word: String) {
var array: [String] = []
let wordPredicate = NSPredicate(format: "self BEGINSWITH[c] %@", word)
searchResult = nil
if prefix == "@" {
if word.characters.count > 0 {
array = users.filter { wordPredicate.evaluate(with: $0) }
} else {
array = users
}
} else if prefix == "#" {
if word.characters.count > 0 {
array = channels.filter { wordPredicate.evaluate(with: $0) }
} else {
array = channels
}
} else if (prefix == ":" || prefix == "+:") && word.characters.count > 0 {
array = emojis.filter { wordPredicate.evaluate(with: $0) }
} else if prefix == "/" && foundPrefixRange.location == 0 {
if word.characters.count > 0 {
array = commands.filter { wordPredicate.evaluate(with: $0) }
} else {
array = commands
}
}
var show = false
if array.count > 0 {
let sortedArray = array.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
searchResult = sortedArray
show = sortedArray.count > 0
}
showAutoCompletionView(show: show)
}
override func heightForAutoCompletionView() -> CGFloat {
guard let searchResult = searchResult else {
return 0
}
guard let autoCompletionView = self.autoCompletionView,
let cellHeight = autoCompletionView.delegate?.tableView?(autoCompletionView, heightForRowAt: IndexPath(row: 0, section: 0)) else {
return 0
}
return cellHeight * CGFloat(searchResult.count)
}
}
// MARK: - Example's Configuration
extension MessageViewController {
func configureDataSource() {
var array = [Message]()
for _ in 0..<100 {
let words = Int((arc4random() % 40)+1)
guard let name = LoremIpsum.name(),
let text = LoremIpsum.words(withNumber: words) else {
continue
}
let message = Message(username: name, text: text)
array.append(message)
}
let reversed = array.reversed()
messages.append(contentsOf: reversed)
}
func configureActionItems() {
let arrowItem = UIBarButtonItem(image: UIImage(named: "icn_arrow_down"), style: .plain, target: self, action: #selector(MessageViewController.hideOrShowTextInputbar(_:)))
let editItem = UIBarButtonItem(image: UIImage(named: "icn_editing"), style: .plain, target: self, action: #selector(MessageViewController.editRandomMessage(_:)))
let typeItem = UIBarButtonItem(image: UIImage(named: "icn_typing"), style: .plain, target: self, action: #selector(MessageViewController.simulateUserTyping(_:)))
let appendItem = UIBarButtonItem(image: UIImage(named: "icn_append"), style: .plain, target: self, action: #selector(MessageViewController.fillWithText(_:)))
let pipItem = UIBarButtonItem(image: UIImage(named: "icn_pic"), style: .plain, target: self, action: #selector(MessageViewController.togglePIPWindow(_:)))
navigationItem.rightBarButtonItems = [arrowItem, pipItem, editItem, appendItem, typeItem]
}
// MARK: - Action Methods
func hideOrShowTextInputbar(_ sender: AnyObject) {
guard let buttonItem = sender as? UIBarButtonItem else {
return
}
let hide = !isTextInputbarHidden
let image = hide ? UIImage(named: "icn_arrow_up") : UIImage(named: "icn_arrow_down")
setTextInputbarHidden(hide, animated: true)
buttonItem.image = image
}
func fillWithText(_ sender: AnyObject) {
if textView.text.characters.count == 0 {
var sentences = Int(arc4random() % 4)
if sentences <= 1 {
sentences = 1
}
textView.text = LoremIpsum.sentences(withNumber: sentences)
} else {
textView.slk_insertTextAtCaretRange(" " + LoremIpsum.word())
}
}
func simulateUserTyping(_ sender: AnyObject) {
if !canShowTypingIndicator() {
return
}
if DEBUG_CUSTOM_TYPING_INDICATOR == true {
guard let indicatorView = typingIndicatorProxyView as? TypingIndicatorView else {
return
}
let scale = UIScreen.main.scale
let imgSize = CGSize(width: kTypingIndicatorViewAvatarHeight * scale, height: kTypingIndicatorViewAvatarHeight * scale)
// This will cause the typing indicator to show after a delay ¯\_(ツ)_/¯
LoremIpsum.asyncPlaceholderImage(with: imgSize, completion: { (image) -> Void in
guard let cgImage = image?.cgImage else {
return
}
let thumbnail = UIImage(cgImage: cgImage, scale: scale, orientation: .up)
indicatorView.presentIndicator(name: LoremIpsum.name(), image: thumbnail)
})
} else {
typingIndicatorView?.insertUsername(LoremIpsum.name())
}
}
func didLongPressCell(_ gesture: UIGestureRecognizer) {
guard let view = gesture.view else {
return
}
if gesture.state != .began {
return
}
if #available(iOS 8, *) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.modalPresentationStyle = .popover
alertController.popoverPresentationController?.sourceView = view.superview
alertController.popoverPresentationController?.sourceRect = view.frame
alertController.addAction(UIAlertAction(title: "Edit Message", style: .default, handler: { [unowned self] (_) -> Void in
self.editCellMessage(gesture)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
navigationController?.present(alertController, animated: true, completion: nil)
} else {
editCellMessage(gesture)
}
}
func editCellMessage(_ gesture: UIGestureRecognizer) {
guard let messageCell = gesture.view as? MessageTableViewCell,
let indexPath = messageCell.indexPath else {
return
}
editingMessage = messages[indexPath.row]
editText(editingMessage.text)
tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
func editRandomMessage(_ sender: AnyObject) {
var sentences = Int(arc4random() % 10)
if sentences <= 1 {
sentences = 1
}
editText(LoremIpsum.sentences(withNumber: sentences))
}
func editLastMessage(_ sender: AnyObject?) {
if textView.text.characters.count > 0 {
return
}
guard let tableView = tableView,
textView.text.characters.count == 0 else {
return
}
let lastSectionIndex = tableView.numberOfSections-1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex)-1
let lastMessage = messages[lastRowIndex]
editText(lastMessage.text)
tableView.scrollToRow(at: IndexPath(row: lastRowIndex, section: lastSectionIndex), at: .bottom, animated: true)
}
func togglePIPWindow(_ sender: AnyObject) {
if pipWindow == nil {
showPIPWindow(sender)
} else {
hidePIPWindow(sender)
}
}
func showPIPWindow(_ sender: AnyObject) {
var frame = CGRect(x: view.frame.width - 60.0, y: 0.0, width: 50.0, height: 50.0)
frame.origin.y = textInputbar.frame.minY - 60.0
pipWindow = UIWindow(frame: frame)
pipWindow?.backgroundColor = UIColor.black
pipWindow?.layer.cornerRadius = 10
pipWindow?.layer.masksToBounds = true
pipWindow?.isHidden = false
pipWindow?.alpha = 0.0
UIApplication.shared.keyWindow?.addSubview(pipWindow!)
UIView.animate(withDuration: 0.25, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 1.0
})
}
func hidePIPWindow(_ sender: AnyObject) {
UIView.animate(withDuration: 0.3, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 0.0
}, completion: { [unowned self] (_) -> Void in
self.pipWindow?.isHidden = true
self.pipWindow = nil
})
}
func textInputbarDidMove(_ note: Notification) {
guard let pipWindow = pipWindow else {
return
}
guard let userInfo = (note as NSNotification).userInfo else {
return
}
guard let value = userInfo["origin"] as? NSValue else {
return
}
var frame = pipWindow.frame
frame.origin.y = value.cgPointValue.y - 60.0
pipWindow.frame = frame
}
}
// MARK: - UITableViewDataSource & UIScrollViewDelegate
extension MessageViewController {
// MARK: - UITableViewDataSource Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tableView {
return messages.count
} else {
if let searchResult = searchResult {
return searchResult.count
}
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableView {
return messageCellForRowAtIndexPath(indexPath)
} else {
return autoCompletionCellForRowAtIndexPath(indexPath)
}
}
func messageCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
guard let cell = tableView?.dequeueReusableCell(withIdentifier: MessageTableViewCell.kMessengerCellIdentifier) as? MessageTableViewCell else {
return MessageTableViewCell()
}
if cell.gestureRecognizers?.count == nil {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MessageViewController.didLongPressCell(_:)))
cell.addGestureRecognizer(longPress)
}
let message = messages[indexPath.row]
cell.titleLabel.text = message.username
cell.bodyLabel.text = message.text
cell.indexPath = indexPath
cell.isUsedForMessage = true
// Cells must inherit the table view's transform
// This is very important, since the main table view may be inverted
if let tableView = tableView {
cell.transform = tableView.transform
}
return cell
}
func autoCompletionCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
guard let cell = autoCompletionView?.dequeueReusableCell(withIdentifier: MessageTableViewCell.kAutoCompletionCellIdentifier) as? MessageTableViewCell else {
return MessageTableViewCell()
}
cell.indexPath = indexPath
cell.selectionStyle = .default
guard let searchResult = searchResult else {
return cell
}
guard let prefix = foundPrefix else {
return cell
}
var text = searchResult[(indexPath as NSIndexPath).row]
if prefix == "#" {
text = "# " + text
} else if prefix == ":" || prefix == "+:" {
text = ":\(text):"
}
cell.titleLabel.text = text
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == tableView {
let message = messages[(indexPath as NSIndexPath).row]
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
let pointSize = MessageTableViewCell.defaultFontSize
let attributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: pointSize),
NSParagraphStyleAttributeName: paragraphStyle
]
var width = tableView.frame.width-kMessageTableViewCellAvatarHeight
width -= 25.0
let titleBounds = (message.username as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let bodyBounds = (message.text as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
if message.text.isEmpty {
return 0
}
var height = titleBounds.height
height += bodyBounds.height
height += 40
if height < kMessageTableViewCellMinimumHeight {
height = kMessageTableViewCellMinimumHeight
}
return height
} else {
return kMessageTableViewCellMinimumHeight
}
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == autoCompletionView {
guard let searchResult = searchResult else {
return
}
var item = searchResult[(indexPath as NSIndexPath).row]
if foundPrefix == "@" && foundPrefixRange.location == 0 {
item += ":"
} else if foundPrefix == ":" || foundPrefix == "+:" {
item += ":"
}
item += " "
acceptAutoCompletion(string: item, keepPrefix: true)
}
}
}
// MARK: - UIScrollViewDelegate Methods
extension MessageViewController {
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
}
}
// MARK: - UITextViewDelegate Methods
extension MessageViewController {
override func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return true
}
override func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
// Since SLKTextViewController uses UIScrollViewDelegate to update a few things, it is important that if you override this method, to call super.
return true
}
override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return super.textView(textView, shouldChangeTextIn: range, replacementText: text)
}
override func textView(_ textView: SLKTextView, shouldOfferFormattingFor symbol: String) -> Bool {
if symbol == ">" {
let selection = textView.selectedRange
// The Quote formatting only applies new paragraphs
if selection.location == 0 && selection.length > 0 {
return true
}
// or older paragraphs too
let prevString = (textView.text as NSString).substring(with: NSRange(location: selection.location-1, length: 1))
if CharacterSet.newlines.contains(UnicodeScalar((prevString as NSString).character(at: 0))!) {
return true
}
return false
}
return super.textView(textView, shouldOfferFormattingFor: symbol)
}
override func textView(_ textView: SLKTextView, shouldInsertSuffixForFormattingWith symbol: String, prefixRange: NSRange) -> Bool {
if symbol == ">" {
return false
}
return super.textView(textView, shouldInsertSuffixForFormattingWith: symbol, prefixRange: prefixRange)
}
}
| mit | 278d322306288e63b8e18b103bc648cd | 33.216867 | 214 | 0.633646 | 5.051383 | false | false | false | false |
aschwaighofer/swift | test/stmt/foreach.swift | 2 | 6823 | // RUN: %target-typecheck-verify-swift
// Bad containers and ranges
struct BadContainer1 {
}
func bad_containers_1(bc: BadContainer1) {
for e in bc { } // expected-error{{for-in loop requires 'BadContainer1' to conform to 'Sequence'}}
}
struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}}
var generate : Int
}
func bad_containers_2(bc: BadContainer2) {
for e in bc { }
}
struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}}
func makeIterator() { } // expected-note{{candidate can not infer 'Iterator' = '()' because '()' is not a nominal type and so can't conform to 'IteratorProtocol'}}
}
func bad_containers_3(bc: BadContainer3) {
for e in bc { }
}
struct BadIterator1 {}
struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}}
typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'BadContainer4.Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}}
func makeIterator() -> BadIterator1 { }
}
func bad_containers_4(bc: BadContainer4) {
for e in bc { }
}
// Pattern type-checking
struct GoodRange<Int> : Sequence, IteratorProtocol {
typealias Element = Int
func next() -> Int? {}
typealias Iterator = GoodRange<Int>
func makeIterator() -> GoodRange<Int> { return self }
}
struct GoodTupleIterator: Sequence, IteratorProtocol {
typealias Element = (Int, Float)
func next() -> (Int, Float)? {}
typealias Iterator = GoodTupleIterator
func makeIterator() -> GoodTupleIterator {}
}
protocol ElementProtocol {}
func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) {
var sum : Int
var sumf : Float
for i : Int in gir { sum = sum + i }
for i in gir { sum = sum + i }
for f : Float in gir { sum = sum + f } // expected-error{{cannot convert sequence element type 'GoodRange<Int>.Element' (aka 'Int') to expected type 'Float'}}
for f : ElementProtocol in gir { } // expected-error {{sequence element type 'GoodRange<Int>.Element' (aka 'Int') does not conform to expected protocol 'ElementProtocol'}}
for (i, f) : (Int, Float) in gtr { sum = sum + i }
for (i, f) in gtr {
sum = sum + i
sumf = sumf + f
sum = sum + f // expected-error {{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
for (i, _) : (Int, Float) in gtr { sum = sum + i }
for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{cannot convert sequence element type 'GoodTupleIterator.Element' (aka '(Int, Float)') to expected type '(Int, Int)'}}
for (i, f) in gtr {}
}
func slices(i_s: [Int], ias: [[Int]]) {
var sum = 0
for i in i_s { sum = sum + i }
for ia in ias {
for i in ia {
sum = sum + i
}
}
}
func discard_binding() {
for _ in [0] {}
}
struct X<T> {
var value: T
}
struct Gen<T> : IteratorProtocol {
func next() -> T? { return nil }
}
struct Seq<T> : Sequence {
func makeIterator() -> Gen<T> { return Gen() }
}
func getIntSeq() -> Seq<Int> { return Seq() }
func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}}
func getGenericSeq<T>() -> Seq<T> { return Seq() }
func getXIntSeq() -> Seq<X<Int>> { return Seq() }
func getXIntSeqIUO() -> Seq<X<Int>>! { return nil }
func testForEachInference() {
for i in getIntSeq() { }
// Overloaded sequence resolved contextually
for i: Int in getOvlSeq() { }
for d: Double in getOvlSeq() { }
// Overloaded sequence not resolved contextually
for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}}
// Generic sequence resolved contextually
for i: Int in getGenericSeq() { }
for d: Double in getGenericSeq() { }
// Inference of generic arguments in the element type from the
// sequence.
for x: X in getXIntSeq() {
let z = x.value + 1
}
for x: X in getOvlSeq() {
let z = x.value + 1
}
// Inference with implicitly unwrapped optional
for x: X in getXIntSeqIUO() {
let z = x.value + 1
}
// Range overloading.
for i: Int8 in 0..<10 { }
for i: UInt in 0...10 { }
}
func testMatchingPatterns() {
// <rdar://problem/21428712> for case parse failure
let myArray : [Int?] = []
for case .some(let x) in myArray {
_ = x
}
// <rdar://problem/21392677> for/case/in patterns aren't parsed properly
class A {}
class B : A {}
class C : A {}
let array : [A] = [A(), B(), C()]
for case (let x as B) in array {
_ = x
}
}
// <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great
func testOptionalSequence() {
let array : [Int]?
for x in array { // expected-error {{for-in loop requires '[Int]?' to conform to 'Sequence'; did you mean to unwrap optional?}}
}
}
// Crash with (invalid) for each over an existential
func testExistentialSequence(s: Sequence) { // expected-error {{protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements}}
for x in s { // expected-error {{value of protocol type 'Sequence' cannot conform to 'Sequence'; only struct/enum/class types can conform to protocols}}
_ = x
}
}
// Conditional conformance to Sequence and IteratorProtocol.
protocol P { }
struct RepeatedSequence<T> {
var value: T
var count: Int
}
struct RepeatedIterator<T> {
var value: T
var count: Int
}
extension RepeatedIterator: IteratorProtocol where T: P {
typealias Element = T
mutating func next() -> T? {
if count == 0 { return nil }
count = count - 1
return value
}
}
extension RepeatedSequence: Sequence where T: P {
typealias Element = T
typealias Iterator = RepeatedIterator<T>
typealias SubSequence = AnySequence<T>
func makeIterator() -> RepeatedIterator<T> {
return Iterator(value: value, count: count)
}
}
extension Int : P { }
func testRepeated(ri: RepeatedSequence<Int>) {
for x in ri { _ = x }
}
// SR-12398: Poor pattern matching diagnostic: "for-in loop requires '[Int]' to conform to 'Sequence'"
func sr_12398(arr1: [Int], arr2: [(a: Int, b: String)]) {
for (x, y) in arr1 {}
// expected-error@-1 {{tuple pattern cannot match values of non-tuple type 'Int'}}
for (x, y, _) in arr2 {}
// expected-error@-1 {{pattern cannot match values of type '(a: Int, b: String)'}}
}
// rdar://62339835
func testForEachWhereWithClosure(_ x: [Int]) {
func foo<T>(_ fn: () -> T) -> Bool { true }
for i in x where foo({ i }) {}
for i in x where foo({ i.byteSwapped == 5 }) {}
for i in x where x.contains(where: { $0.byteSwapped == i }) {}
}
| apache-2.0 | 866c1025dd3939b1d9c66a2ed72e8489 | 27.429167 | 187 | 0.652792 | 3.52064 | false | false | false | false |
brokenhandsio/vapor-oauth | Sources/VaporOAuth/RouteHandlers/TokenHandlers/ClientCredentialsTokenHandler.swift | 1 | 3292 | import Vapor
struct ClientCredentialsTokenHandler {
let clientValidator: ClientValidator
let scopeValidator: ScopeValidator
let tokenManager: TokenManager
let tokenResponseGenerator: TokenResponseGenerator
func handleClientCredentialsTokenRequest(_ request: Request) throws -> Response {
guard let clientID = request.data[OAuthRequestParameters.clientID]?.string else {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidRequest,
description: "Request was missing the 'client_id' parameter")
}
guard let clientSecret = request.data[OAuthRequestParameters.clientSecret]?.string else {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidRequest,
description: "Request was missing the 'client_secret' parameter")
}
do {
try clientValidator.authenticateClient(clientID: clientID, clientSecret: clientSecret,
grantType: .clientCredentials, checkConfidentialClient: true)
} catch ClientError.unauthorized {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidClient,
description: "Request had invalid client credentials", status: .unauthorized)
} catch ClientError.notConfidential {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.unauthorizedClient,
description: "You are not authorized to use the Client Credentials grant type")
}
let scopeString = request.data[OAuthRequestParameters.scope]?.string
if let scopes = scopeString {
do {
try scopeValidator.validateScope(clientID: clientID, scopes: scopes.components(separatedBy: " "))
} catch ScopeError.invalid {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidScope,
description: "Request contained an invalid scope")
} catch ScopeError.unknown {
return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidScope,
description: "Request contained an unknown scope")
}
}
let expiryTime = 3600
let scopes = scopeString?.components(separatedBy: " ")
let (access, refresh) = try tokenManager.generateAccessRefreshTokens(clientID: clientID, userID: nil,
scopes: scopes,
accessTokenExpiryTime: expiryTime)
return try tokenResponseGenerator.createResponse(accessToken: access, refreshToken: refresh,
expires: expiryTime, scope: scopeString)
}
}
| mit | 50fd0c6166d1ede08781367b5b1b5563 | 59.962963 | 140 | 0.59842 | 6.531746 | false | false | false | false |
xwu/swift | test/SILGen/lexical_lifetime.swift | 1 | 5511 | // RUN: %target-swift-emit-silgen -enable-experimental-lexical-lifetimes -module-name borrow -parse-stdlib %s | %FileCheck %s
import Swift
////////////////////////////////////////////////////////////////////////////////
// Declarations {{
////////////////////////////////////////////////////////////////////////////////
final class C {
init() {}
init?(failably: ()) {}
}
struct S {
let c: C
}
struct Trivial {
let i: Int
}
enum E {
case e(C)
}
@_silgen_name("use_generic")
func use_generic<T>(_ t: T) {}
////////////////////////////////////////////////////////////////////////////////
// Declarations }}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Tests {{
////////////////////////////////////////////////////////////////////////////////
// let bindings:
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_let_class
// CHECK: [[INIT_C:%[^,]+]] = function_ref @$s6borrow1CCACycfC
// CHECK: [[INSTANCE:%[^,]+]] = apply [[INIT_C]]({{%[0-9]+}})
// CHECK: [[BORROW:%[^,]+]] = begin_borrow [lexical] [[INSTANCE]] : $C
// CHECK: end_borrow [[BORROW:%[^,]+]]
// CHECK-LABEL: } // end sil function 'lexical_borrow_let_class'
@_silgen_name("lexical_borrow_let_class")
func lexical_borrow_let_class() {
let c = C()
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_if_let_class
// CHECK: [[INIT_C:%[^,]+]] = function_ref @$s6borrow1CC8failablyACSgyt_tcfC
// CHECK: [[INSTANCE:%[^,]+]] = apply [[INIT_C]]({{%[^,]+}})
// CHECK: switch_enum [[INSTANCE]] : $Optional<C>, case #Optional.some!enumelt: [[BASIC_BLOCK2:bb[^,]+]], case #Optional.none!enumelt: {{bb[^,]+}}
// CHECK: [[BASIC_BLOCK2]]([[INSTANCE:%[^,]+]] : @owned $C):
// CHECK: [[BORROW:%[^,]+]] = begin_borrow [lexical] [[INSTANCE]] : $C
// CHECK: end_borrow [[BORROW]] : $C
// CHECK-LABEL: // end sil function 'lexical_borrow_if_let_class'
@_silgen_name("lexical_borrow_if_let_class")
func lexical_borrow_if_let_class() {
if let c = C(failably: ()) {
use_generic(())
}
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_let_class_in_struct
// CHECK: [[INIT_S:%[^,]+]] = function_ref @$s6borrow1SV1cAcA1CC_tcfC
// CHECK: [[INSTANCE:%[^,]+]] = apply [[INIT_S]]({{%[0-9]+}}, {{%[0-9]+}})
// CHECK: [[BORROW:%[^,]+]] = begin_borrow [lexical] [[INSTANCE]] : $S
// CHECK: end_borrow [[BORROW:%[^,]+]]
// CHECK-LABEL: } // end sil function 'lexical_borrow_let_class_in_struct'
@_silgen_name("lexical_borrow_let_class_in_struct")
func lexical_borrow_let_class_in_struct() {
let s = S(c: C())
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_let_class_in_enum
// CHECK: [[INSTANCE:%[^,]+]] = enum $E, #E.e!enumelt, {{%[0-9]+}} : $C
// CHECK: [[BORROW:%[^,]+]] = begin_borrow [lexical] [[INSTANCE]] : $E
// CHECK: end_borrow [[BORROW:%[^,]+]]
// CHECK-LABEL: } // end sil function 'lexical_borrow_let_class_in_enum'
@_silgen_name("lexical_borrow_let_class_in_enum")
func lexical_borrow_let_class_in_enum() {
let s = E.e(C())
}
// arguments:
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_arg_owned_class : $@convention(thin) (@owned C) -> () {
// CHECK: {{bb[^,]+}}([[INSTANCE:%[^,]+]] : @owned $C):
// CHECK: [[LIFETIME:%[^,]+]] = begin_borrow [lexical] [[INSTANCE]]
// CHECK: debug_value [[LIFETIME]]
// CHECK: [[ADDR:%[^,]+]] = alloc_stack $C
// CHECK: store_borrow [[LIFETIME]] to [[ADDR]]
// CHECK: [[USE_GENERIC:%[^,]+]] = function_ref @use_generic
// CHECK: [[REGISTER_6:%[^,]+]] = apply [[USE_GENERIC]]<C>([[ADDR]])
// CHECK: dealloc_stack [[ADDR]]
// CHECK: end_borrow [[LIFETIME]]
// CHECK: [[RETVAL:%[^,]+]] = tuple ()
// CHECK: return [[RETVAL]]
// CHECK-LABEL: } // end sil function 'lexical_borrow_arg_owned_class'
@_silgen_name("lexical_borrow_arg_owned_class")
func lexical_borrow_arg_owned_class(_ c: __owned C) {
use_generic(c)
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_arg_guaranteed_class : $@convention(thin) (@guaranteed C) -> () {
// CHECK: {{bb[^,]+}}([[INSTANCE:%[^,]+]] : @guaranteed $C):
// CHECK-NOT: begin_borrow [lexical]
// CHECK-LABEL: } // end sil function 'lexical_borrow_arg_guaranteed_class'
@_silgen_name("lexical_borrow_arg_guaranteed_class")
func lexical_borrow_arg_guaranteed_class(_ c: C) {
use_generic(c)
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_arg_class_addr : $@convention(thin) (@inout C) -> () {
// CHECK-NOT: begin_borrow [lexical]
// CHECK-LABEL: } // end sil function 'lexical_borrow_arg_class_addr'
@_silgen_name("lexical_borrow_arg_class_addr")
func lexical_borrow_arg_class_addr(_ c: inout C) {
use_generic(c)
}
// CHECK-LABEL: sil hidden [ossa] @lexical_borrow_arg_trivial : $@convention(thin) (Trivial) -> () {
// CHECK-NOT: begin_borrow [lexical]
// CHECK-LABEL: } // end sil function 'lexical_borrow_arg_trivial'
@_silgen_name("lexical_borrow_arg_trivial")
func lexical_borrow_arg_trivial(_ trivial: Trivial) {
use_generic(trivial)
}
////////////////////////////////////////////////////////////////////////////////
// Test }}
////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | 46d7a200be0759d381ba7479593b4e1a | 39.822222 | 148 | 0.501179 | 3.666667 | false | false | false | false |
jnwagstaff/PutItOnMyTabBar | Example/PutItOnMyTabBar/BackgroundTabBarController.swift | 1 | 2919 | //
// BackgroundTabBarController.swift
// PutItOnMyTabBar
//
// Created by Jacob Wagstaff on 8/18/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import PutItOnMyTabBar
class BackgroundTabBarController: PutItOnMyTabBarController{
override func viewDidLoad() {
super.viewDidLoad()
//Home Tab
let home = HomeViewController()
let homeNav = UINavigationController()
homeNav.viewControllers = [home]
//Excursion Tab
let excursion = ExcursionViewController()
let excursionNav = UINavigationController()
excursionNav.viewControllers = [excursion]
//Record Tab
let record = RecordViewController()
let recordNav = UINavigationController()
recordNav.viewControllers = [record]
//Map Tab
let map = MapViewController()
let mapNav = UINavigationController()
mapNav.viewControllers = [map]
//Tackle Tab
let tackle = TackleViewController()
let tackleNav = UINavigationController()
tackleNav.viewControllers = [tackle]
viewControllers = [homeNav, excursionNav, recordNav, mapNav, tackleNav]
}
// MARK: Overrides for PutItOnMyTabBar
override func numberOfTabs() -> Int {
return 5
}
override func highLightedImages() -> [UIImage] {
return [#imageLiteral(resourceName: "homeSelected"), #imageLiteral(resourceName: "excursionSelected"), #imageLiteral(resourceName: "recordSelected"), #imageLiteral(resourceName: "mapSelected"), #imageLiteral(resourceName: "tackleSelected")]
}
override func unHighlightedImages() -> [UIImage] {
return [#imageLiteral(resourceName: "home"), #imageLiteral(resourceName: "excursion"), #imageLiteral(resourceName: "record"), #imageLiteral(resourceName: "map"), #imageLiteral(resourceName: "tackle")]
}
override func backgroundColor() -> UIColor{
return UIColor.fromHex(rgbValue: 0xF2E9DE, alpha: 0.95)
}
override func sliderColor() -> UIColor {
return .white
}
override func sliderHeightMultiplier() -> CGFloat {
return 1
}
override func sliderWidthMultiplier() -> CGFloat {
return 1
}
override func animationDuration() -> Double {
return 0.0
}
// MARK: Titles Defaults to none
override func tabBarType() -> TabBarItemType {//Return .label
return .label
}
override func titles() -> [String] {
return ["Home", "Excursions", "Record", "Map", "TackleBox"]
}
override func titleColors() -> (UIColor, UIColor) {
return (UIColor.fromHex(rgbValue: 0xF2E9DE, alpha: 0.95), .darkGray)
}
override func fontForTitles() -> UIFont {
return UIFont.systemFont(ofSize: 10)
}
}
| mit | 271aa3a0d8265b927f0075c19f9b24be | 29.715789 | 248 | 0.634339 | 4.676282 | false | false | false | false |
diegoreymendez/CreedShrink | CreedShrink/GapRemover.swift | 1 | 1374 | import Foundation
class GapRemover {
func removeGaps(values : [Int]) -> (result : [Int], gaps : [Int]) {
var shiftedAscii = values
var gaps = [Int]()
for var minValue = values.minElement(), i = 0; minValue != nil; minValue = nextMinValue(shiftedAscii, previousMinValue: i), i++ {
shiftedAscii = shiftedAscii.map { (element) -> Int in
if element >= minValue! {
return (element - minValue!) + i
} else {
return element
}
}
gaps.append(minValue!)
}
return (shiftedAscii, gaps)
}
func restoreGaps(values: [Int], gaps: [Int]) -> [Int] {
assert(values.count > 0)
var restoredValues = [Int]()
for value in values {
var restoredValue = value
for i in 0...value {
let gap = gaps[i]
restoredValue += (gap - i)
}
restoredValues.append(restoredValue)
}
return restoredValues
}
private func nextMinValue(ascii : [Int], previousMinValue : Int) -> Int? {
return ascii.filter({ return $0 > previousMinValue }).minElement()
}
} | apache-2.0 | 1c775ff39d28f51cb2b9093fdb43ba49 | 26.5 | 137 | 0.461426 | 5.070111 | false | false | false | false |
vi4m/Zewo | Modules/Venice/Sources/Venice/Select/Select.swift | 1 | 10585 | import CLibvenice
protocol SelectCase {
func register(_ clause: UnsafeMutableRawPointer, index: Int)
func execute()
}
final class ChannelReceiveCase<T> : SelectCase {
let channel: Channel<T>
let closure: (T) -> Void
init(channel: Channel<T>, closure: @escaping (T) -> Void) {
self.channel = channel
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.registerReceive(clause, index: index)
}
func execute() {
if let value = channel.getValueFromBuffer() {
closure(value)
}
}
}
final class ReceivingChannelReceiveCase<T> : SelectCase {
let channel: ReceivingChannel<T>
let closure: (T) -> Void
init(channel: ReceivingChannel<T>, closure: @escaping (T) -> Void) {
self.channel = channel
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.registerReceive(clause, index: index)
}
func execute() {
if let value = channel.getValueFromBuffer() {
closure(value)
}
}
}
final class FallibleChannelReceiveCase<T> : SelectCase {
let channel: FallibleChannel<T>
var closure: (ChannelResult<T>) -> Void
init(channel: FallibleChannel<T>, closure: @escaping (ChannelResult<T>) -> Void) {
self.channel = channel
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.registerReceive(clause, index: index)
}
func execute() {
if let result = channel.getResultFromBuffer() {
closure(result)
}
}
}
final class FallibleReceivingChannelReceiveCase<T> : SelectCase {
let channel: FallibleReceivingChannel<T>
var closure: (ChannelResult<T>) -> Void
init(channel: FallibleReceivingChannel<T>, closure: @escaping (ChannelResult<T>) -> Void) {
self.channel = channel
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.registerReceive(clause, index: index)
}
func execute() {
if let result = channel.getResultFromBuffer() {
closure(result)
}
}
}
final class ChannelSendCase<T> : SelectCase {
let channel: Channel<T>
var value: T
let closure: (Void) -> Void
init(channel: Channel<T>, value: T, closure: @escaping (Void) -> Void) {
self.channel = channel
self.value = value
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(value, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class SendingChannelSendCase<T> : SelectCase {
let channel: SendingChannel<T>
var value: T
let closure: (Void) -> Void
init(channel: SendingChannel<T>, value: T, closure: @escaping (Void) -> Void) {
self.channel = channel
self.value = value
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(value, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class FallibleChannelSendCase<T> : SelectCase {
let channel: FallibleChannel<T>
let value: T
let closure: (Void) -> Void
init(channel: FallibleChannel<T>, value: T, closure: @escaping (Void) -> Void) {
self.channel = channel
self.value = value
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(value, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class FallibleSendingChannelSendCase<T> : SelectCase {
let channel: FallibleSendingChannel<T>
let value: T
let closure: (Void) -> Void
init(channel: FallibleSendingChannel<T>, value: T, closure: @escaping (Void) -> Void) {
self.channel = channel
self.value = value
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(value, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class FallibleChannelSendErrorCase<T> : SelectCase {
let channel: FallibleChannel<T>
let error: Error
let closure: (Void) -> Void
init(channel: FallibleChannel<T>, error: Error, closure: @escaping (Void) -> Void) {
self.channel = channel
self.error = error
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(error, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class FallibleSendingChannelSendErrorCase<T> : SelectCase {
let channel: FallibleSendingChannel<T>
let error: Error
let closure: (Void) -> Void
init(channel: FallibleSendingChannel<T>, error: Error, closure: @escaping (Void) -> Void) {
self.channel = channel
self.error = error
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.send(error, clause: clause, index: index)
}
func execute() {
closure()
}
}
final class TimeoutCase<T> : SelectCase {
let channel: Channel<T>
let closure: (Void) -> Void
init(channel: Channel<T>, closure: @escaping (Void) -> Void) {
self.channel = channel
self.closure = closure
}
func register(_ clause: UnsafeMutableRawPointer, index: Int) {
channel.registerReceive(clause, index: index)
}
func execute() {
closure()
}
}
public class SelectCaseBuilder {
var cases: [SelectCase] = []
var otherwise: ((Void) -> Void)?
public func receive<T>(from channel: Channel<T>?, closure: @escaping (T) -> Void) {
if let channel = channel {
let selectCase = ChannelReceiveCase(channel: channel, closure: closure)
cases.append(selectCase)
}
}
public func receive<T>(from channel: ReceivingChannel<T>?, closure: @escaping (T) -> Void) {
if let channel = channel {
let selectCase = ReceivingChannelReceiveCase(channel: channel, closure: closure)
cases.append(selectCase)
}
}
public func receive<T>(from channel: FallibleChannel<T>?, closure: @escaping (ChannelResult<T>) -> Void) {
if let channel = channel {
let selectCase = FallibleChannelReceiveCase(channel: channel, closure: closure)
cases.append(selectCase)
}
}
public func receive<T>(from channel: FallibleReceivingChannel<T>?, closure: @escaping (ChannelResult<T>) -> Void) {
if let channel = channel {
let selectCase = FallibleReceivingChannelReceiveCase(channel: channel, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ value: T, to channel: Channel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = ChannelSendCase(channel: channel, value: value, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ value: T, to channel: SendingChannel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = SendingChannelSendCase(channel: channel, value: value, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ value: T, to channel: FallibleChannel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = FallibleChannelSendCase(channel: channel, value: value, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ value: T, to channel: FallibleSendingChannel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = FallibleSendingChannelSendCase(channel: channel, value: value, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ error: Error, to channel: FallibleChannel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = FallibleChannelSendErrorCase(channel: channel, error: error, closure: closure)
cases.append(selectCase)
}
}
public func send<T>(_ error: Error, to channel: FallibleSendingChannel<T>?, closure: @escaping (Void) -> Void) {
if let channel = channel, !channel.closed {
let selectCase = FallibleSendingChannelSendErrorCase(channel: channel, error: error, closure: closure)
cases.append(selectCase)
}
}
public func timeout(_ deadline: Double, closure: @escaping (Void) -> Void) {
let done = Channel<Bool>()
co {
wake(at: deadline)
done.send(true)
}
let selectCase = TimeoutCase<Bool>(channel: done, closure: closure)
cases.append(selectCase)
}
public func otherwise(_ closure: @escaping (Void) -> Void) {
self.otherwise = closure
}
}
private func select(_ builder: SelectCaseBuilder) {
mill_choose_init_("select")
var clauses: [UnsafeMutableRawPointer] = []
for (index, selectCase) in builder.cases.enumerated() {
let clause = malloc(mill_clauselen())!
clauses.append(clause)
selectCase.register(clause, index: index)
}
if builder.otherwise != nil {
mill_choose_otherwise_()
}
let index = mill_choose_wait_()
if index == -1 {
builder.otherwise?()
} else {
builder.cases[Int(index)].execute()
}
clauses.forEach(free)
}
public func select(_ build: (_ when: SelectCaseBuilder) -> Void) {
let builder = SelectCaseBuilder()
build(builder)
select(builder)
}
public func sel(_ build: (_ when: SelectCaseBuilder) -> Void) {
select(build)
}
public func forSelect(_ build: (_ when: SelectCaseBuilder, _ done: @escaping (Void) -> Void) -> Void) {
let builder = SelectCaseBuilder()
var keepRunning = true
func done() {
keepRunning = false
}
while keepRunning {
let builder = SelectCaseBuilder()
build(builder, done)
select(builder)
}
}
public func forSel(build: (_ when: SelectCaseBuilder, _ done: @escaping (Void) -> Void) -> Void) {
forSelect(build)
}
| mit | c17b84ae98dbf9b8c4b5ece8b94a5ea0 | 27.920765 | 119 | 0.621634 | 4.080571 | false | false | false | false |
Daltron/Spartan | Spartan/Classes/Spartan.swift | 1 | 52037 | /*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
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 Alamofire
public class Spartan: NSObject {
/* Token that is included with each request that requires OAuth authentication. If the request you
make requries OAuth and this is nil, the response status code will be a 401 Unauthorized
*/
public static var authorizationToken: String?
/* When enabled, will log each network request and its response in the console */
public static var loggingEnabled: Bool = true {
didSet {
SpartanRequestManager.default.loggingEnabled = loggingEnabled
}
}
/* API Documentation: https://developer.spotify.com/web-api/get-album */
@discardableResult
public class func getAlbum(id: String,
market: CountryCode? = nil,
success: @escaping ((Album) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
var parameters: [String: Any] = [:]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return Album.find(id: id, parameters: parameters, success: success, failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-several-albums */
@discardableResult
public class func getAlbums(ids: [String],
market: CountryCode? = nil,
success: @escaping (([Album]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
var parameters: [String: Any] = ["ids" : ids.joined(separator: ",")]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return Album.all(parameters: parameters, success: success, failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-albums-tracks */
@discardableResult
public class func getTracks(albumId:String,
limit:Int = 20,
offset:Int = 0,
market: CountryCode? = nil,
success: @escaping ((PagingObject<SimplifiedTrack>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(SimplifiedAlbum.pluralRoot)/\(albumId)/\(Track.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-artist */
@discardableResult
public class func getArtist(id: String,
success: @escaping ((Artist) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
return Artist.find(id: id,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-several-artists */
@discardableResult
public class func getArtists(ids: [String],
success: @escaping (([Artist]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let parameters = ["ids" : ids.joined(separator: ",")]
return Artist.all(parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-artists-albums */
@discardableResult
public class func getArtistAlbums(artistId: String,
limit:Int = 20,
offset:Int = 0,
albumTypes: [AlbumType] = [.album, .single, .appearsOn, .compilation],
market: CountryCode? = nil,
success: @escaping ((PagingObject<SimplifiedAlbum>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
var albumTypesString: [String] = []
for type in albumTypes {
albumTypesString.append(type.rawValue)
}
let url = SpartanURL(url: "\(Artist.pluralRoot)/\(artistId)/\(Album.pluralRoot)")
var parameters = ["limit" : limit, "offset" : offset, "album_type" : albumTypesString.joined(separator: ",")] as [String: Any]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-artists-top-tracks */
@discardableResult
public class func getArtistsTopTracks(artistId: String,
country: CountryCode,
success: @escaping (([Track]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(Artist.pluralRoot)/\(artistId)/top-tracks")
let parameters = ["country" : country.rawValue]
return SpartanRequestManager.default.mapObjects(.get,
url: url,
parameters: parameters,
keyPath: Track.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-related-artists */
@discardableResult
public class func getArtistsRelatedArtists(artistId: String,
success: @escaping (([Artist]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(Artist.pluralRoot)/\(artistId)/related-artists")
return SpartanRequestManager.default.mapObjects(.get,
url: url,
keyPath: Artist.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/search-item */
@discardableResult
public class func search<T: SpartanBaseObject>(query: String,
type: ItemSearchType,
market: CountryCode? = nil,
limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<T>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "search")
var parameters: [String: Any] = ["q" : query, "type" : type.rawValue, "limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
keyPath: ItemSearchType.pluralRoot(for: type),
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-track */
@discardableResult
public class func getTrack(id: String,
market: CountryCode? = nil,
success: @escaping ((Track) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
var parameters: [String: Any] = [:]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return Track.find(id: id,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-several-tracks */
@discardableResult
public class func getTracks(ids: [String],
market: CountryCode? = nil,
success: @escaping (([Track]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
var parameters: [String: Any] = ["ids": ids.joined(separator: ",")]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return Track.all(parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-users-profile */
@discardableResult
public class func getUser(id: String,
success: @escaping ((PublicUser) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
return PublicUser.find(id: id, success: success, failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-audio-analysis */
@discardableResult
public class func getAudioAnaylsis(trackId: String,
success: @escaping ((AudioAnalysis) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(AudioAnalysis.root)/\(trackId)")
return SpartanRequestManager.default.mapObject(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-audio-features */
@discardableResult
public class func getAudioFeatures(trackId: String,
success: @escaping ((AudioFeaturesObject) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(AudioFeaturesObject.pluralRoot)/\(trackId)")
return SpartanRequestManager.default.mapObject(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-several-audio-features */
@discardableResult
public class func getAudioFeatures(trackIds: [String],
success: @escaping (([AudioFeaturesObject]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(AudioFeaturesObject.pluralRoot)")
let parameters = ["ids" : trackIds.joined(separator: ",")]
return SpartanRequestManager.default.mapObjects(.get,
url: url,
parameters: parameters,
keyPath: "audio_features",
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-list-featured-playlists */
@discardableResult
public class func getFeaturedPlaylists(locale: String? = nil, country: CountryCode? = nil, timestamp: String? = nil, limit: Int = 20, offset: Int = 0, success: @escaping ((FeaturedPlaylistsObject) -> Void), failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "browse/featured-playlists")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "locale", param: locale, parameters: ¶meters)
checkOptionalParamAddition(paramName: "country", param: country, parameters: ¶meters)
checkOptionalParamAddition(paramName: "timestamp", param: timestamp, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-list-new-releases */
@discardableResult
public class func getNewReleases(country: CountryCode? = nil,
limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<SimplifiedAlbum>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "browse/new-releases")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "country", param: country, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
keyPath: Album.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-list-categories */
@discardableResult
public class func getCategories(locale: String? = nil,
country: CountryCode? = nil,
limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<CategoryObject>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "browse/\(CategoryObject.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "locale", param: locale, parameters: ¶meters)
checkOptionalParamAddition(paramName: "country", param: country, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
keyPath: CategoryObject.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-category */
@discardableResult
public class func getCategory(id: String,
locale: String? = nil,
country: CountryCode? = nil,
success: @escaping ((CategoryObject) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "browse/\(CategoryObject.pluralRoot)/\(id)")
var parameters: [String: Any] = [:]
checkOptionalParamAddition(paramName: "locale", param: locale, parameters: ¶meters)
checkOptionalParamAddition(paramName: "country", param: country, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-categorys-playlists */
@discardableResult
public class func getCategorysPlaylists(categoryId: String,
locale: String? = nil,
country: CountryCode? = nil,
limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<SimplifiedPlaylist>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "browse/\(CategoryObject.pluralRoot)/\(categoryId)/\(Playlist.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "locale", param: locale, parameters: ¶meters)
checkOptionalParamAddition(paramName: "country", param: country, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
keyPath: Playlist.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-current-users-profile */
@discardableResult
public class func getMe(success: @escaping ((PrivateUser) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me")
return SpartanRequestManager.default.mapObject(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-followed-artists */
@discardableResult
public class func getMyFollowedArtists(limit: Int = 20,
after: String? = nil,
success: @escaping ((PagingObject<Artist>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/following?type=artist")
var parameters: [String: Any] = ["limit" : limit]
checkOptionalParamAddition(paramName: "after", param: after, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
keyPath: Artist.pluralRoot,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/follow-artists-users */
@discardableResult
public class func follow(ids: [String],
type: FollowType,
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/following?type=\(type.rawValue)&ids=\(ids.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.put,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/follow-artists-users */
@discardableResult
public class func unfollow(ids: [String],
type: FollowType,
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/following?type=\(type.rawValue)&ids=\(ids.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.delete,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/check-current-user-follows */
@discardableResult
public class func getIsFollowing(ids: [String],
type: FollowType,
success: @escaping (([Bool]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/following/contains?type=\(type.rawValue)&ids=\(ids.joined(separator: ","))")
return SpartanRequestManager.default.mapBoolArray(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/follow-playlist */
@discardableResult
public class func followPlaylist(ownerId: String,
playlistId: String,
isPublic: Bool = true,
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "users/\(ownerId)/\(Playlist.pluralRoot)/\(playlistId)/followers")
let parameters: [String: Any] = ["public" : isPublic]
return SpartanRequestManager.default.makeRequest(.put,
url: url,
parameters: parameters,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/unfollow-playlist */
@discardableResult
public class func unfollowPlaylist(ownerId: String,
playlistId: String,
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "users/\(ownerId)/\(Playlist.pluralRoot)/\(playlistId)/followers")
return SpartanRequestManager.default.makeRequest(.delete,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/save-tracks-user */
@discardableResult
public class func saveTracks(trackIds: [String],
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Track.pluralRoot)?ids=\(trackIds.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.put,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-users-saved-tracks */
@discardableResult
public class func getSavedTracks(limit: Int = 20,
offset: Int = 0,
market: CountryCode? = nil,
success: @escaping ((PagingObject<SavedTrack>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Track.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/remove-tracks-user */
@discardableResult
public class func removeSavedTracks(trackIds: [String],
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Track.pluralRoot)?ids=\(trackIds.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.delete,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/check-users-saved-tracks */
@discardableResult
public class func tracksAreSaved(trackIds: [String],
success: @escaping (([Bool]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Track.pluralRoot)/contains?ids=\(trackIds.joined(separator: ","))")
return SpartanRequestManager.default.mapBoolArray(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/save-albums-user */
@discardableResult
public class func saveAlbums(albumIds: [String],
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Album.pluralRoot)?ids=\(albumIds.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.put,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-users-saved-albums */
@discardableResult
public class func getSavedAlbums(limit: Int = 20,
offset: Int = 0,
market: CountryCode? = nil,
success: @escaping ((PagingObject<SavedAlbum>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Album.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/remove-albums-user */
@discardableResult
public class func removeSavedAlbums(albumIds: [String],
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Album.pluralRoot)?ids=\(albumIds.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.delete,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/check-users-saved-albums */
@discardableResult
public class func albumsAreSaved(albumIds: [String],
success: @escaping (([Bool]) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Album.pluralRoot)/contains?ids=\(albumIds.joined(separator: ","))")
return SpartanRequestManager.default.mapBoolArray(.get,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */
@discardableResult
public class func getMyTopArtists(limit: Int = 20,
offset: Int = 0,
timeRange: TimeRange = .mediumTerm,
success: @escaping ((PagingObject<Artist>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/top/\(Artist.pluralRoot)")
let parameters: [String: Any] = ["limit" : limit, "offset" : offset, "time_range" : timeRange.rawValue]
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */
@discardableResult
public class func getMyTopTracks(limit: Int = 20,
offset: Int = 0,
timeRange: TimeRange = .mediumTerm,
success: @escaping ((PagingObject<Track>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/top/\(Track.pluralRoot)")
let parameters: [String: Any] = ["limit" : limit, "offset" : offset, "time_range" : timeRange.rawValue]
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-recommendations */
@discardableResult
public class func getRecommendations(limit: Int = 20,
market: CountryCode? = nil,
minAttributes: [(TuneableTrackAttribute, Float)]? = nil,
maxAttributes: [(TuneableTrackAttribute, Float)]? = nil,
targetAttributes: [(TuneableTrackAttribute, Float)]? = nil,
seedArtists: [String]? = nil, seedGenres: [String]? = nil,
seedTracks: [String]? = nil,
success: @escaping ((RecommendationsObject) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "recommendations")
var parameters: [String: Any] = ["limit" : limit]
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
checkOptionalTuneableTrackAttributeTupleParamAddition(prefix: "max", attributes: maxAttributes, parameters: ¶meters)
checkOptionalTuneableTrackAttributeTupleParamAddition(prefix: "min", attributes: minAttributes, parameters: ¶meters)
checkOptionalTuneableTrackAttributeTupleParamAddition(prefix: "target", attributes: targetAttributes, parameters: ¶meters)
checkOptionalArrayParamAddition(paramName: "seed_artists", param: seedArtists, parameters: ¶meters)
checkOptionalArrayParamAddition(paramName: "seed_genres", param: seedGenres, parameters: ¶meters)
checkOptionalArrayParamAddition(paramName: "seed_tracks", param: seedTracks, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-list-users-playlists */
@discardableResult
public class func getUsersPlaylists(userId: String,
limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<SimplifiedPlaylist>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)")
let parameters: [String: Any] = ["limit" : limit, "offset" : offset]
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-list-users-playlists */
@discardableResult
public class func getMyPlaylists(limit: Int = 20,
offset: Int = 0,
success: @escaping ((PagingObject<SimplifiedPlaylist>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "me/\(Playlist.pluralRoot)")
let parameters: [String: Any] = ["limit" : limit, "offset" : offset]
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-playlist */
@discardableResult
public class func getUsersPlaylist(userId: String,
playlistId: String,
fields: [String]? = nil,
market: CountryCode? = nil,
success: @escaping ((Playlist) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)")
var parameters: [String: Any] = [:]
checkOptionalParamAddition(paramName: "fields", param: fields?.joined(separator: ","), parameters: ¶meters)
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/get-playlists-tracks */
@discardableResult
public class func getPlaylistTracks(userId: String,
playlistId: String,
limit: Int = 20,
offset: Int = 0,
fields: [String]? = nil,
market: CountryCode? = nil,
success: @escaping ((PagingObject<PlaylistTrack>) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)/\(Track.pluralRoot)")
var parameters: [String: Any] = ["limit" : limit, "offset" : offset]
checkOptionalParamAddition(paramName: "fields", param: fields?.joined(separator: ","), parameters: ¶meters)
checkOptionalParamAddition(paramName: "market", param: market?.rawValue, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.get,
url: url,
parameters: parameters,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/create-playlist */
@discardableResult
public class func createPlaylist(userId: String,
name: String,
isPublic: Bool = true,
isCollaborative: Bool = false,
success: @escaping ((Playlist) -> Void),
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)")
let parameters: [String: Any] = ["name" : name, "public" : isPublic, "collaborative" : isCollaborative]
return SpartanRequestManager.default.mapObject(.post,
url: url,
parameters: parameters,
encoding: JSONEncoding.default,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/change-playlist-details */
@discardableResult
public class func changePlaylistDetails(userId: String,
playlistId: String,
name: String,
isPublic: Bool,
isCollaborative: Bool,
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)")
let parameters: [String: Any] = ["name" : name, "public" : isPublic, "collaborative" : isCollaborative]
return SpartanRequestManager.default.makeRequest(.put,
url: url,
parameters: parameters,
encoding: JSONEncoding.default,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/add-tracks-to-playlist */
@discardableResult
public class func addTracksToPlaylist(userId: String,
playlistId: String,
trackUris: [String],
position: Int? = nil,
success: ((SnapshotResponse) -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
var urlString = "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)/\(Track.pluralRoot)?uris=\(trackUris.joined(separator: ","))"
if let position = position {
urlString += "&position=\(position)"
}
let url = SpartanURL(url: urlString)
return SpartanRequestManager.default.mapObject(.post,
url: url,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/remove-tracks-playlist */
@discardableResult
public class func removeTracksFromPlaylist(userId: String,
playlistId: String,
trackUris: [String],
success: ((SnapshotResponse) -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)/\(Track.pluralRoot)")
var trackUrisArray: [[String: String]] = []
for trackUri in trackUris {
trackUrisArray.append(["uri" : trackUri])
}
let parameters: [String: Any] = ["tracks" : trackUrisArray]
return SpartanRequestManager.default.mapObject(.delete,
url: url,
parameters: parameters,
encoding: JSONEncoding.default,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/reorder-playlists-tracks */
@discardableResult
public class func reorderPlaylistsTracks(userId: String,
playlistId: String,
rangeStart: Int,
rangeLength: Int = 1,
insertBefore: Int,
snapshotId: String? = nil,
success: ((SnapshotResponse) -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)/\(Track.pluralRoot)")
var parameters: [String: Any] = ["range_start" : rangeStart, "range_length" : rangeLength, "insert_before" : insertBefore]
checkOptionalParamAddition(paramName: "snapshot_id", param: snapshotId, parameters: ¶meters)
return SpartanRequestManager.default.mapObject(.put,
url: url,
parameters: parameters,
encoding: JSONEncoding.default,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/replace-playlists-tracks */
@discardableResult
public class func replacePlaylistsTracks(userId: String,
playlistId: String,
trackUris: [String],
success: (() -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(userId)/\(Playlist.pluralRoot)/\(playlistId)/\(Track.pluralRoot)?uris=\(trackUris.joined(separator: ","))")
return SpartanRequestManager.default.makeRequest(.put,
url: url,
emptyBody: true,
success: success,
failure: failure)
}
/* API Documentation: https://developer.spotify.com/web-api/check-user-following-playlist */
@discardableResult
public class func getUsersAreFollowingPlaylists(ownerId: String,
playlistId: String,
userIds: [String],
success: (([Bool]) -> Void)?,
failure: ((SpartanError) -> Void)?) -> Request {
let url = SpartanURL(url: "\(PublicUser.pluralRoot)/\(ownerId)/\(Playlist.pluralRoot)/\(playlistId)/followers/contains?ids=\(userIds.joined(separator: ","))")
return SpartanRequestManager.default.mapBoolArray(.get,
url: url,
success: success,
failure: failure)
}
private class func checkOptionalParamAddition(paramName: String,
param: Any?, parameters: inout [String: Any]) {
if let param = param {
parameters[paramName] = param
}
}
private class func checkOptionalArrayParamAddition(paramName: String,
param: [String]?,
parameters: inout [String: Any]) {
if let param = param {
parameters[paramName] = param.joined(separator: ",")
}
}
private class func checkOptionalTuneableTrackAttributeTupleParamAddition(prefix: String,
attributes: [(TuneableTrackAttribute, Float)]?,
parameters: inout [String: Any]) {
guard let attributes = attributes else {
return
}
for (attribute, value) in attributes {
parameters["\(prefix)_\(attribute.rawValue)"] = value
}
}
}
| mit | 1196e9ecf94cf792bf680c1f20369fbd | 52.426078 | 259 | 0.454042 | 6.078379 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Library/SharedFunctions.swift | 1 | 1546 | import AppboyKit
import Library
import UIKit
// MARK: - Haptic feedback
func generateImpactFeedback(
feedbackGenerator: UIImpactFeedbackGeneratorType = UIImpactFeedbackGenerator(style: .light)
) {
feedbackGenerator.prepare()
feedbackGenerator.impactOccurred()
}
func generateNotificationSuccessFeedback(
feedbackGenerator: UINotificationFeedbackGeneratorType = UINotificationFeedbackGenerator()
) {
feedbackGenerator.prepare()
feedbackGenerator.notificationOccurred(.success)
}
func generateNotificationWarningFeedback(
feedbackGenerator: UINotificationFeedbackGeneratorType = UINotificationFeedbackGenerator()
) {
feedbackGenerator.prepare()
feedbackGenerator.notificationOccurred(.warning)
}
func generateSelectionFeedback(
feedbackGenerator: UISelectionFeedbackGeneratorType = UISelectionFeedbackGenerator()
) {
feedbackGenerator.prepare()
feedbackGenerator.selectionChanged()
}
// MARK: - Login workflow
public func logoutAndDismiss(
viewController: UIViewController,
appEnvironment: AppEnvironmentType.Type = AppEnvironment.self,
pushNotificationDialog: PushNotificationDialogType.Type =
PushNotificationDialog.self
) {
appEnvironment.logout()
pushNotificationDialog.resetAllContexts()
NotificationCenter.default.post(.init(name: .ksr_sessionEnded))
viewController.dismiss(animated: true, completion: nil)
}
// MARK: - Braze
public func userNotificationCenterDidReceiveResponse(
appBoy: AppboyType?,
isNotNil: () -> (),
isNil: () -> ()
) {
appBoy == nil ? isNil() : isNotNil()
}
| apache-2.0 | 2b5c4bfd16fb56659a5693313ffb45de | 24.766667 | 93 | 0.797542 | 5.136213 | false | false | false | false |
scottrhoyt/RxApollo | RxApollo/RxApollo.swift | 1 | 4894 | //
// RxApollo.swift
// RxApollo
//
// Created by Scott Hoyt on 5/9/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import Foundation
import RxSwift
import Apollo
/// An `Error` emitted by `ApolloReactiveExtensions`.
public enum RxApolloError: Error {
/// One or more `GraphQLError`s were encountered.
case graphQLErrors([GraphQLError])
}
/// Reactive extensions for `ApolloClient`.
public final class ApolloReactiveExtensions {
private let client: ApolloClient
fileprivate init(_ client: ApolloClient) {
self.client = client
}
/// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy.
///
/// - Parameters:
/// - query: The query to fetch.
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server and when data should be loaded from the local cache.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - Returns: A `Maybe` that emits the results of the query.
public func fetch<Query: GraphQLQuery>(
query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
queue: DispatchQueue = DispatchQueue.main) -> Maybe<Query.Data> {
return Maybe.create { maybe in
let cancellable = self.client.fetch(query: query, cachePolicy: cachePolicy, queue: queue) { result, error in
if let error = error {
maybe(.error(error))
} else if let errors = result?.errors {
maybe(.error(RxApolloError.graphQLErrors(errors)))
} else if let data = result?.data {
maybe(.success(data))
} else {
maybe(.completed)
}
}
return Disposables.create {
cancellable.cancel()
}
}
}
/// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned `Observable` will emit events whenever any of the data the query result depends on changes in the local cache.
///
/// - Parameters:
/// - query: The query to watch.
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server or from the local cache.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - Returns: An `Observable` that emits the results of watching the `query`.
public func watch<Query: GraphQLQuery>(
query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
queue: DispatchQueue = DispatchQueue.main) -> Observable<Query.Data> {
return Observable.create { observer in
let watcher = self.client.watch(query: query, cachePolicy: cachePolicy, queue: queue) { result, error in
if let error = error {
observer.onError(error)
} else if let errors = result?.errors {
observer.onError(RxApolloError.graphQLErrors(errors))
} else if let data = result?.data {
observer.onNext(data)
}
// Should we silently ignore the case where `result` and `error` are both nil, or should this be an error situation?
}
return Disposables.create {
watcher.cancel()
}
}
}
/// Performs a mutation by sending it to the server.
///
/// - Parameters:
/// - mutation: The mutation to perform.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - Returns: A `Maybe` that emits the results of the mutation.
public func perform<Mutation: GraphQLMutation>(mutation: Mutation, queue: DispatchQueue = DispatchQueue.main) -> Maybe<Mutation.Data> {
return Maybe.create { maybe in
let cancellable = self.client.perform(mutation: mutation, queue: queue) { result, error in
if let error = error {
maybe(.error(error))
} else if let errors = result?.errors {
maybe(.error(RxApolloError.graphQLErrors(errors)))
} else if let data = result?.data {
maybe(.success(data))
} else {
maybe(.completed)
}
}
return Disposables.create {
cancellable.cancel()
}
}
}
}
public extension ApolloClient {
/// Reactive extensions.
var rx: ApolloReactiveExtensions { return ApolloReactiveExtensions(self) }
}
| mit | 3ca958347e13fb0e87c9e1358282d8f7 | 40.820513 | 328 | 0.607603 | 4.825444 | false | false | false | false |
1000copy/fin | View/V2FPSLabel.swift | 1 | 1885 | //
// V2FPSLabel.swift
// V2ex-Swift
//
// Created by huangfeng on 1/15/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
//重写自 YYFPSLabel
//https://github.com/ibireme/YYText/blob/master/Demo/YYTextDemo/YYFPSLabel.m
class V2FPSLabel: UILabel {
fileprivate var _link :CADisplayLink?
fileprivate var _count:Int = 0
fileprivate var _lastTime:TimeInterval = 0
fileprivate let _defaultSize = CGSize(width: 55, height: 20);
override init(frame: CGRect) {
var targetFrame = frame
if frame.size.width == 0 && frame.size.height == 0{
targetFrame.size = _defaultSize
}
super.init(frame: targetFrame)
self.layer.cornerRadius = 5
self.clipsToBounds = true
self.textAlignment = .center
self.isUserInteractionEnabled = false
self.textColor = UIColor.white
self.backgroundColor = UIColor(white: 0, alpha: 0.7)
self.font = UIFont(name: "Menlo", size: 14)
weak var weakSelf = self
_link = CADisplayLink(target: weakSelf!, selector:#selector(V2FPSLabel.tick(_:)) );
_link!.add(to: RunLoop.main, forMode:RunLoopMode.commonModes)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func tick(_ link:CADisplayLink) {
if _lastTime == 0 {
_lastTime = link.timestamp
return
}
_count += 1
let delta = link.timestamp - _lastTime
if delta < 1 {
return
}
_lastTime = link.timestamp
let fps = Double(_count) / delta
_count = 0
let progress = fps / 60.0;
self.textColor = UIColor(hue: CGFloat(0.27 * ( progress - 0.2 )) , saturation: 1, brightness: 0.9, alpha: 1)
self.text = "\(Int(fps+0.5))FPS"
}
}
| mit | 74ab7e64f0072b4f560344291f383262 | 28.34375 | 116 | 0.583067 | 4.004264 | false | false | false | false |
Urinx/SublimeCode | Sublime/Sublime/Utils/Extension/UIApplication.swift | 1 | 804 | //
// UIApplication.swift
// Sublime
//
// Created by Eular on 4/20/16.
// Copyright © 2016 Eular. All rights reserved.
//
import Foundation
// MARK: - UIApplication
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
} | gpl-3.0 | 0cae96954edfe295b4859bcc36412869 | 28.777778 | 146 | 0.650062 | 5.353333 | false | false | false | false |
wang-chuanhui/CHSDK | Source/File/HandleFile.swift | 1 | 1241 | //
// FileExecute.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/18.
// Copyright © 2017年 王传辉. All rights reserved.
//
import UIKit
public protocol HandleFile {
}
extension File: HandleFile {
}
public extension HandleFile where Self: File {
}
public extension HandleFile where Self == File {
func create() -> Bool {
return FileManager.default.createFile(atPath: path, contents: nil, attributes: nil)
}
var size: UInt64 {
guard isExists else {
return 0
}
if isDirectory {
return Directory(path).size
}
return (attributes[FileAttributeKey.size] as? NSNumber)?.uint64Value ?? 0
}
}
public extension HandleFile where Self == Directory {
func create() throws {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
var size: UInt64 {
guard isExists else {
return 0
}
guard isDirectory else {
return File(path).size
}
var size = (attributes[FileAttributeKey.size] as? NSNumber)?.uint64Value ?? 0
size = children.reduce(size, {$0 + $1.size})
return size
}
}
| mit | 407f655071ab6940f90a5e2c5079a463 | 20.137931 | 113 | 0.606852 | 4.155932 | false | false | false | false |
LiuSky/XBPrint | XBPrint/ViewController.swift | 1 | 13045 | //
// ViewController.swift
// XBPrint
//
// Created by xiaobin liu on 16/3/24.
// Copyright © 2016年 Sky. All rights reserved.
//
import UIKit
import CoreBluetooth
class ViewController: UIViewController,XBPrintInstructionProtocol {
var bluetoothManager = BluetoothManager()
lazy var tableView: UITableView = {
let temporaryTableView = UITableView()
temporaryTableView.backgroundColor = UIColor.white
temporaryTableView.backgroundView = nil
temporaryTableView.dataSource = self
temporaryTableView.delegate = self
temporaryTableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
return temporaryTableView
}()
lazy var searchButton: UIButton = {
let temporaryButton = UIButton(type: .custom)
temporaryButton.bounds = CGRect(x: 0, y: 0, width: 80, height: 50)
temporaryButton.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)
temporaryButton.setTitle("搜索中", for: UIControlState())
temporaryButton.setTitle("停止搜索", for: .selected)
temporaryButton.setTitleColor(UIColor.red, for: UIControlState())
temporaryButton.setTitleColor(UIColor.red, for: .selected)
return temporaryButton
}()
lazy var printButton: UIButton = {
let temporaryButton = UIButton(type: .custom)
temporaryButton.bounds = CGRect(x: 0, y: 0, width: 80, height: 50)
temporaryButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30)
temporaryButton.setTitle("打印", for: UIControlState())
temporaryButton.setTitleColor(UIColor.red, for: UIControlState())
temporaryButton.setTitleColor(UIColor.red, for: .selected)
return temporaryButton
}()
//搜索到的打印机数组
var printerArrary: [CBPeripheral]?
//点击搜索按钮
@objc func chickButton(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
bluetoothManager.startScan()
} else {
sender.isSelected = true
bluetoothManager.stopScan()
}
}
//打印
@objc func print() {
let printTemplate = PrintTemplate(storeName: "米客互联(福建总部)", number: "A001", tableType: TableType.tableForTwo, waiting: "您前面还有:0桌在等候", time: "排队时间:03月26日10时10分", phone: "餐厅电话:13696888888", qrcode: "www.chidaoni.com")
for peripheral in printerArrary! {
if peripheral.state == .connected {
let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
//打印商家名称
var cmmStoreNameData = Data()
cmmStoreNameData.append(printerInitialize)
cmmStoreNameData.append(printer(model:0))
cmmStoreNameData.append(printer(characterSize: 1))
cmmStoreNameData.append(printer(alignment: 1))
let storeNameData = printTemplate.storeName.data(using: String.Encoding(rawValue: enc))
cmmStoreNameData.append(storeNameData!)
cmmStoreNameData.append(printer(paperFeed: 2))
bluetoothManager.writeValue(peripheral, data: cmmStoreNameData as Data)
//打印排队号码以及桌子类型
var cmmNumberData = Data()
cmmNumberData.append(printerInitialize)
cmmNumberData.append(printer(characterSize: 17))
let numberData = printTemplate.number.data(using: String.Encoding(rawValue: enc))
cmmNumberData.append(numberData!)
cmmNumberData.append(printer(model:0))
cmmNumberData.append(printer(characterSize: 0))
cmmNumberData.append(printer(alignment: 1))
let tableTypeData = printTemplate.tableType.tableName.data(using: String.Encoding(rawValue: enc))
cmmNumberData.append(tableTypeData!)
cmmNumberData.append(printer(paperFeed: 2))
bluetoothManager.writeValue(peripheral, data: cmmNumberData)
//打印等待人数
var cmmWaitingData = Data()
cmmWaitingData.append(printerInitialize as Data)
cmmWaitingData.append(printer(model: 0))
cmmWaitingData.append(printer(characterSize: 0))
cmmWaitingData.append(printerLeftSpacing(50, nH: 0))
let waitingData = printTemplate.waiting.data(using: String.Encoding(rawValue: enc))
cmmWaitingData.append(waitingData!)
cmmWaitingData.append(printer(paperFeed: 1))
bluetoothManager.writeValue(peripheral, data: cmmWaitingData)
//打印时间
var cmmTimeData = Data()
cmmTimeData.append(printerInitialize)
cmmTimeData.append(printer(model: 0))
cmmTimeData.append(printer(characterSize: 0))
cmmTimeData.append(printerLeftSpacing(50, nH: 0))
let timeData = printTemplate.time.data(using: String.Encoding(rawValue: enc))
cmmTimeData.append(timeData!)
cmmTimeData.append(printer(paperFeed: 1))
bluetoothManager.writeValue(peripheral, data: cmmTimeData)
//打印电话号码
var cmmPhoneData = Data()
cmmPhoneData.append(printerInitialize)
cmmPhoneData.append(printer(model: 0))
cmmPhoneData.append(printer(characterSize: 0))
cmmPhoneData.append(printerLeftSpacing(50, nH: 0))
let phoneData = printTemplate.phone.data(using: String.Encoding(rawValue: enc))
cmmPhoneData.append(phoneData!)
cmmPhoneData.append(printer(paperFeed: 2))
bluetoothManager.writeValue(peripheral, data: cmmPhoneData)
//打印二维码
var cmmQrCodeData = Data()
cmmQrCodeData.append(printerInitialize)
cmmQrCodeData.append(printerLeftSpacing(50, nH: 0))
if peripheral.name!.hasPrefix("D") {
cmmQrCodeData.append(printer(qrcode: printTemplate.qrcode))
} else if peripheral.name!.hasPrefix("G") {
cmmQrCodeData.append(printerQRCode(12, ecc: 48, qrcode: printTemplate.qrcode))
}
cmmQrCodeData.append(printer(paperFeed: 1))
bluetoothManager.writeValue(peripheral, data: cmmQrCodeData)
//广告语
var cmmAdvertisingData = Data()
cmmAdvertisingData.append(printerInitialize)
cmmAdvertisingData.append(printer(model: 0))
cmmAdvertisingData.append(printer(characterSize: 0))
cmmAdvertisingData.append(printerLeftSpacing(50, nH: 0))
let advertisingData = printTemplate.advertising.data(using: String.Encoding(rawValue: enc))
cmmAdvertisingData.append(advertisingData!)
cmmAdvertisingData.append(printer(paperFeed: 1))
bluetoothManager.writeValue(peripheral, data: cmmAdvertisingData)
//线
var cmmLineData = Data()
cmmLineData.append(printerInitialize)
cmmLineData.append(printer(model: 0))
cmmLineData.append(printer(characterSize: 0))
let lineData = "--------------------------------".data(using: String.Encoding(rawValue: enc))
cmmLineData.append(lineData!)
cmmLineData.append(printer(paperFeed: 1))
bluetoothManager.writeValue(peripheral, data: cmmLineData)
//技术支持
var cmmTechnicalSupportData = Data()
cmmTechnicalSupportData.append(printerInitialize)
cmmTechnicalSupportData.append(printer(model: 0))
cmmTechnicalSupportData.append(printer(characterSize: 0))
cmmTechnicalSupportData.append(printerLeftSpacing(50, nH: 0))
let technicalSupportData = printTemplate.technicalSupport.data(using: String.Encoding(rawValue: enc))
cmmTechnicalSupportData.append(technicalSupportData!)
cmmTechnicalSupportData.append(printer(paperFeed: 5))
bluetoothManager.writeValue(peripheral, data: cmmTechnicalSupportData)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "蓝牙打印机"
self.view.backgroundColor = UIColor.white
tableView.frame = view.frame
view.addSubview(tableView)
searchButton.addTarget(self, action: #selector(ViewController.chickButton(_:)), for: .touchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: searchButton)
navigationItem.leftBarButtonItem = leftBarButtonItem
printButton.addTarget(self, action: #selector(ViewController.print), for: .touchUpInside)
let rightBarButtonItem = UIBarButtonItem(customView: printButton)
navigationItem.rightBarButtonItem = rightBarButtonItem
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
bluetoothManager.delegate = self
bluetoothManager.startScan()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - <#UITableViewDataSource#>
extension ViewController: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return printerArrary?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "选择打印机"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self))!
let peripheral = printerArrary![(indexPath as NSIndexPath).row]
cell.textLabel?.text = peripheral.name
let rightLabel = UILabel(frame: CGRect(x: 0,y: 0,width: 70,height: 20))
rightLabel.textColor = UIColor.red
if peripheral.state == .connected {
rightLabel.text = "已连接"
} else if peripheral.state == .connecting {
rightLabel.text = "连接中"
} else {
rightLabel.text = "未连接"
}
cell.accessoryView = rightLabel
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let peripheral = printerArrary![(indexPath as NSIndexPath).row]
bluetoothManager.connectPeripheral(peripheral)
self.tableView.reloadData()
}
}
// MARK: - <#XBBluetoothCenterDelegate#>
extension ViewController: BluetoothCenterDelegate {
func bluetoothCenterOff() {
debugPrint("蓝牙关闭")
}
func bluetoothCenterOn() {
debugPrint("蓝牙开着")
}
func bluetoothCenter(_ central: CBCentralManager, didDiscoverPeripheral peripheralArray: [CBPeripheral]) {
self.printerArrary = peripheralArray
tableView.reloadData()
}
func bluetoothCenter(_ central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
debugPrint("连接设备成功")
self.tableView.reloadData()
}
func bluetoothCenter(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.tableView.reloadData()
debugPrint("断开外设方法")
}
func bluetoothCenter(_ central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
debugPrint("连接设备失败")
}
func bluetoothCenter(_ peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let error = error {
debugPrint("打印失败\(error)")
} else {
debugPrint("打印成功")
}
}
}
| mit | daa7198504fb05c8daf7aae5a7f5615c | 39.037736 | 222 | 0.610038 | 4.913933 | false | false | false | false |
freak4pc/netfox | netfox/Core/NFXRawBodyDetailsController.swift | 1 | 2341 | //
// NFXRawBodyDetailsController.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
#if os(iOS)
import Foundation
import UIKit
class NFXRawBodyDetailsController: NFXGenericBodyDetailsController
{
var bodyView: UITextView = UITextView()
private var copyAlert: UIAlertController?
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Body details"
self.bodyView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.bodyView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.bodyView.backgroundColor = UIColor.clear
self.bodyView.textColor = UIColor.NFXGray44Color()
self.bodyView.textAlignment = .left
self.bodyView.isEditable = false
self.bodyView.isSelectable = false
self.bodyView.font = UIFont.NFXFont(size: 13)
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(NFXRawBodyDetailsController.copyLabel))
self.bodyView.addGestureRecognizer(lpgr)
switch bodyType {
case .request:
self.bodyView.text = self.selectedModel.getRequestBody() as String
default:
self.bodyView.text = self.selectedModel.getResponseBody() as String
}
self.view.addSubview(self.bodyView)
}
@objc fileprivate func copyLabel(lpgr: UILongPressGestureRecognizer) {
guard let text = (lpgr.view as? UITextView)?.text,
copyAlert == nil else { return }
UIPasteboard.general.string = text
let alert = UIAlertController(title: "Text Copied!", message: nil, preferredStyle: .alert)
copyAlert = alert
self.present(alert, animated: true) { [weak self] in
guard let `self` = self else { return }
Timer.scheduledTimer(timeInterval: 0.45,
target: self,
selector: #selector(NFXRawBodyDetailsController.dismissCopyAlert),
userInfo: nil,
repeats: false)
}
}
@objc fileprivate func dismissCopyAlert() {
copyAlert?.dismiss(animated: true) { [weak self] in self?.copyAlert = nil }
}
}
#endif
| mit | 3415c86d01c3c5a7ead06521a87f4f33 | 31.5 | 119 | 0.617949 | 4.698795 | false | false | false | false |
andart/SodexoPass | SodexoPass/ViewController.swift | 1 | 4694 | //
// ViewController.swift
// SodexoPass
//
// Created by Andrey Artemenko on 13/04/2017.
// Copyright © 2017 Andrey Artemenko. All rights reserved.
//
import UIKit
import Eureka
import TesseractOCR
import BarcodeScanner
let cardStoreKey = "cardStoreKey"
class ViewController: FormViewController, G8TesseractDelegate, BarcodeScannerCodeDelegate, BarcodeScannerErrorDelegate, BarcodeScannerDismissalDelegate {
let store = UserDefaults.standard
weak var captchaImageView: UIImageView?
weak var captchaTextField: UITextField?
weak var cardNumberRow: IntRow?
override func viewDidLoad() {
super.viewDidLoad()
var cardNumber = store.object(forKey: cardStoreKey) as! Int?
form +++ Section("Проверка баланса карты")
<<< IntRow() {
$0.title = "Номер карты"
$0.placeholder = "Укажите номер"
$0.add(rule: RuleRequired())
self.cardNumberRow = $0
if cardNumber != nil {
$0.value = cardNumber
}
}.onCellHighlightChanged({ (cell, row) in
if !row.isHighlighted, row.value != nil {
cardNumber = row.value
self.store.set(cardNumber, forKey: cardStoreKey)
}
})
<<< ButtonRow() {
$0.title = "Сканировать"
}.onCellSelection({ (cell, row) in
let controller = BarcodeScannerController()
controller.codeDelegate = self
controller.errorDelegate = self
controller.dismissalDelegate = self
self.present(controller, animated: true, completion: nil)
})
<<< CaptchaRow() {
self.captchaImageView = $0.cell.captchaImageView
self.captchaTextField = $0.cell.textField
$0.cell.textField.placeholder = "Введите символы с картинки"
$0.cell.button.addTarget(self, action: #selector(ViewController.reloadCaptcha), for: .touchUpInside)
}
<<< ButtonRow() {
$0.title = "Проверить"
}.onCellSelection({ (cell, row) in
if cardNumber != nil, let captchaCode = self.captchaTextField?.text {
API.shared.checkBalance(cardNumber: "\(cardNumber!)", captchaCode: captchaCode) { summ in
let alert = UIAlertController(title: "Доступно", message: "\((summ as! Int) / 100)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
API.shared.getCookie() {
self.reloadCaptcha()
}
}
func reloadCaptcha() {
API.shared.getCaptcha() { (image) in
if image != nil {
self.captchaImageView?.image = image
self.recognizeImage(image!)
}
}
}
fileprivate func recognizeImage(_ image: UIImage) {
DispatchQueue.global(qos: .userInitiated).async {
let tesseract:G8Tesseract = G8Tesseract(language:"eng")
tesseract.delegate = self
tesseract.image = image.g8_grayScale()
tesseract.recognize()
DispatchQueue.main.async {
self.captchaTextField?.text = tesseract.recognizedText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
}
func shouldCancelImageRecognitionForTesseract(tesseract: G8Tesseract!) -> Bool {
return false; // return true if you need to interrupt tesseract before it finishes
}
func barcodeScanner(_ controller: BarcodeScannerController, didCaptureCode code: String, type: String) {
controller.dismiss(animated: true, completion: nil)
self.cardNumberRow?.value = Int(code)
self.cardNumberRow?.cell.textField.text = code
self.reloadCaptcha()
}
func barcodeScanner(_ controller: BarcodeScannerController, didReceiveError error: Error) {
print(error)
}
func barcodeScannerDidDismiss(_ controller: BarcodeScannerController) {
controller.dismiss(animated: true, completion: nil)
}
}
| mit | 642f7033a2f336a8a7fe0df7ffd06686 | 34.384615 | 153 | 0.560435 | 5.060506 | false | false | false | false |
mikaelm1/Teach-Me-Fast | Teach Me Fast/SignupVC.swift | 1 | 6731 | //
// SignupVC.swift
// Teach Me Fast
//
// Created by Mikael Mukhsikaroyan on 6/7/16.
// Copyright © 2016 MSquaredmm. All rights reserved.
//
import UIKit
import Firebase
enum ErrorCodes: Int {
//case noInternet = 100
case emailTaken = 17007
case weakPassword = 17026
case invalidEmail = 17999
case userNotFound = 17011
case wrongPassword = 17009
}
class SignupVC: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
title = "Create Account"
setupFields()
navigationController?.navigationBar.barTintColor = UIColor.rgb(0, green: 130, blue: 241, alpha: 1)
navigationController?.navigationBar.tintColor = UIColor.white()
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white()]
navigationController?.navigationBar.barStyle = .black
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
// MARK: Helper methods
func getEmail() -> String? {
if let email = emailTextField.text where email != "" {
return email
}
return nil
}
func getPassword() -> String? {
if let pwd = passwordTextField.text where pwd != "" {
return pwd
}
return nil
}
func getUsername() -> String? {
if let username = usernameTextField.text where username != "" {
return username
}
return nil
}
func goToPosts() {
let vc = storyboard?.instantiateViewController(withIdentifier: Constants.postsContainer) as! SWRevealViewController
present(vc, animated: true, completion: nil)
}
// MARK: Firebase methods
func isUsernameAvailable(_ username: String, completion: (available: Bool) -> Void ) {
print("Checking for username")
FirebaseClient.sharedInstance.refUsers.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
print("Snapshots: \(snapshots)")
for snap in snapshots {
//print("SNAP: \(snap)")
if let userDict = snap.value as? [String: AnyObject] {
//print("UserDict: \(userDict)")
if let usrname = userDict["username"] as? String {
print("Got the username: \(usrname)")
if usrname == username {
//print("The usernames are equal")
completion(available: false)
return
}
}
}
}
completion(available: true)
}
})
completion(available: true)
}
func createAccount(_ email: String, password pwd: String, username: String) {
FIRAuth.auth()?.createUser(withEmail: email, password: pwd, completion: { (user, error) in
if let error = error {
print("Error creating user: \(error.debugDescription)")
switch error.code {
case ErrorCodes.emailTaken.rawValue:
self.showAlert("An account for that email already exists.", success: false)
case ErrorCodes.weakPassword.rawValue:
self.showAlert("The password must be at least six characters long.", success: false)
case ErrorCodes.invalidEmail.rawValue:
self.showAlert("Invalid email given. Please enter a valid email.", success: false)
default:
self.showAlert("There was an error creating your account. Please try again.", success: false)
}
} else {
print("Created account")
user!.sendEmailVerification(completion: { (error) in
if error != nil {
print("Error sending email: \(error)")
//self.sendEmailVerification(user!)
} else {
print("Sent email verification")
self.showAlert("A verification email has been sent to the email address you provided. Please verify before logging in.", success: true)
self.performSegue(withIdentifier: Constants.segueToSignin, sender: nil)
}
})
let userInfo = ["provider": "email", "username": username]
FirebaseClient.sharedInstance.createFirebaseUser(user!.uid, userInfo: userInfo)
}
})
}
func showAlert(_ message: String, success: Bool) {
if success {
_ = SweetAlert().showAlert("Welcome!", subTitle: message, style: AlertStyle.success)
} else {
_ = SweetAlert().showAlert("Error.", subTitle: message, style: AlertStyle.error)
}
}
// MARK: Actions
@IBAction func joinButtonPressed(_ sender: UIButton) {
view.endEditing(true)
if let username = getUsername(), let email = getEmail(), let pwd = getPassword() {
isUsernameAvailable(username, completion: { (available) in
if available {
self.createAccount(email, password: pwd, username: username)
} else {
print("Username not available")
self.showAlert("That username is already taken. Please choose another.", success: false)
}
})
} else {
print("Didn't get text from usernameField")
showAlert("Please enter all of the fields.", success: false)
}
}
@IBAction func signinButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: Constants.segueToSignin, sender: nil)
}
@IBAction func skipLoginPressed(_ sender: UIButton) {
goToPosts()
}
}
extension SignupVC: UITextFieldDelegate {
func setupFields() {
emailTextField.delegate = self
passwordTextField.delegate = self
usernameTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | dd1964bb255edc37034933ef4056f248 | 35.182796 | 159 | 0.561516 | 5.409968 | false | false | false | false |
StevenUpForever/FBSimulatorControl | fbsimctl/FBSimulatorControlKit/Sources/HttpRelay.swift | 2 | 15916 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
enum QueryError : Error, CustomStringConvertible {
case TooManyMatches([FBiOSTarget], Int)
case NoMatches
case WrongTarget(String, String)
case NoneProvided
var description: String { get {
switch self {
case .TooManyMatches(let matches, let expected):
return "Matched too many Targets. \(expected) targets matched but had \(matches.count)"
case .NoMatches:
return "No Matching Targets"
case .WrongTarget(let expected, let actual):
return "Wrong Target. Expected \(expected) but got \(actual)"
case .NoneProvided:
return "No Query Provided"
}
}}
}
extension HttpRequest {
func jsonBody() throws -> JSON {
return try JSON.fromData(self.body)
}
}
enum ResponseKeys : String {
case Success = "success"
case Failure = "failure"
case Status = "status"
case Message = "message"
case Events = "events"
case Subject = "subject"
}
private class HttpEventReporter : EventReporter {
var events: [EventReporterSubject] = []
let interpreter: EventInterpreter = JSONEventInterpreter(pretty: false)
fileprivate func report(_ subject: EventReporterSubject) {
self.events.append(subject)
}
var jsonDescription: JSON { get {
return JSON.array(self.events.map { $0.jsonDescription })
}}
static func errorResponse(_ errorMessage: String?) -> HttpResponse {
let json = JSON.dictionary([
ResponseKeys.Status.rawValue : JSON.string(ResponseKeys.Failure.rawValue),
ResponseKeys.Message.rawValue : JSON.string(errorMessage ?? "Unknown Error")
])
return HttpResponse.internalServerError(json.data)
}
func interactionResultResponse(_ result: CommandResult) -> HttpResponse {
switch result.outcome {
case .failure(let string):
let json = JSON.dictionary([
ResponseKeys.Status.rawValue : JSON.string(ResponseKeys.Failure.rawValue),
ResponseKeys.Message.rawValue : JSON.string(string),
ResponseKeys.Events.rawValue : self.jsonDescription
])
return HttpResponse.internalServerError(json.data)
case .success(let subject):
var dictionary = [
ResponseKeys.Status.rawValue : JSON.string(ResponseKeys.Success.rawValue),
ResponseKeys.Events.rawValue : self.jsonDescription
]
if let subject = subject {
dictionary[ResponseKeys.Subject.rawValue] = subject.jsonDescription
}
let json = JSON.dictionary(dictionary)
return HttpResponse.ok(json.data)
}
}
}
extension ActionPerformer {
func dispatchAction(_ action: Action, queryOverride: FBiOSTargetQuery?) -> HttpResponse {
let reporter = HttpEventReporter()
var result: CommandResult? = nil
DispatchQueue.main.sync {
result = self.perform(reporter: reporter, action: action, queryOverride: queryOverride)
}
return reporter.interactionResultResponse(result!)
}
func runWithSingleSimulator<A>(_ query: FBiOSTargetQuery, action: (FBSimulator) throws -> A) throws -> A {
let simulator = try self.runnerContext(HttpEventReporter()).querySingleSimulator(query)
var result: A? = nil
var error: Error? = nil
DispatchQueue.main.sync {
do {
result = try action(simulator)
} catch let caughtError {
error = caughtError
}
}
if let error = error {
throw error
}
return result!
}
}
enum HttpMethod : String {
case GET = "GET"
case POST = "POST"
}
enum ActionHandler {
case constant(Action)
case path(([String]) throws -> Action)
case parser((JSON) throws -> Action)
case binary((Data) throws -> Action)
case file(String, (HttpRequest, URL) throws -> Action)
func produceAction(_ request: HttpRequest) throws -> (Action, FBiOSTargetQuery?) {
switch self {
case .constant(let action):
return (action, nil)
case .path(let pathHandler):
let components = Array(request.pathComponents.dropFirst())
let action = try pathHandler(components)
return (action, nil)
case .parser(let actionParser):
let json = try request.jsonBody()
let action = try actionParser(json)
let query = try? FBiOSTargetQuery.inflate(fromJSON: json.getValue("simulators").decode())
return (action, query)
case .binary(let binaryHandler):
let action = try binaryHandler(request.body)
return (action, nil)
case .file(let pathExtension, let handler):
let guid = UUID().uuidString
let destination = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("fbsimctl-\(guid)")
.appendingPathExtension(pathExtension)
if (FileManager.default.fileExists(atPath: destination.path)) {
throw ParseError.custom("Could not generate temporary filename, \(destination.path) already exists.")
}
try request.body.write(to: destination)
let action = try handler(request, destination)
return (action, nil)
}
}
}
class ActionHttpResponseHandler : NSObject, HttpResponseHandler {
let performer: ActionPerformer
let handler: ActionHandler
init(performer: ActionPerformer, handler: ActionHandler) {
self.performer = performer
self.handler = handler
super.init()
}
func handle(_ request: HttpRequest) -> HttpResponse {
return SimpleResponseHandler.perform(request: request) { request in
let pathQuery = try SimpleResponseHandler.extractQueryFromPath(request)
let (action, actionQuery) = try self.handler.produceAction(request)
let response = performer.dispatchAction(action, queryOverride: pathQuery ?? actionQuery)
return response
}
}
}
class SimpleResponseHandler : NSObject, HttpResponseHandler {
let handler:(HttpRequest)throws -> HttpResponse
init(handler: @escaping (HttpRequest) throws -> HttpResponse) {
self.handler = handler
super.init()
}
func handle(_ request: HttpRequest) -> HttpResponse {
return SimpleResponseHandler.perform(request: request, self.handler)
}
static func perform(request: HttpRequest, _ handler:(HttpRequest)throws -> HttpResponse) -> HttpResponse {
do {
return try handler(request)
} catch let error as CustomStringConvertible {
return HttpEventReporter.errorResponse(error.description)
} catch let error as NSError {
return HttpEventReporter.errorResponse(error.localizedDescription)
} catch {
return HttpEventReporter.errorResponse(nil)
}
}
static func extractQueryFromPath(_ request: HttpRequest) throws -> FBiOSTargetQuery? {
guard let queryPath = request.pathComponents.dropFirst().first, request.pathComponents.count >= 3 else {
return nil
}
return FBiOSTargetQuery.udids([
try FBiOSTargetQuery.parseUDIDToken(queryPath)
])
}
}
protocol Route {
var method: HttpMethod { get }
var endpoint: String { get }
func responseHandler(performer: ActionPerformer) -> HttpResponseHandler
}
extension Route {
func httpRoutes(_ performer: ActionPerformer) -> [HttpRoute] {
let handler = responseHandler(performer: performer)
return [
HttpRoute(method: self.method.rawValue, path: "/.*/" + self.endpoint, handler: handler),
HttpRoute(method: self.method.rawValue, path: "/" + self.endpoint, handler: handler),
]
}
}
struct ActionRoute : Route {
let method: HttpMethod
let eventName: EventName
let handler: ActionHandler
static func post(_ eventName: EventName, handler: @escaping (JSON) throws -> Action) -> Route {
return ActionRoute(method: HttpMethod.POST, eventName: eventName, handler: ActionHandler.parser(handler))
}
static func postFile(_ eventName: EventName, _ pathExtension: String, handler: @escaping (HttpRequest, URL) throws -> Action) -> Route {
return ActionRoute(method: HttpMethod.POST, eventName: eventName, handler: ActionHandler.file(pathExtension, handler))
}
static func getConstant(_ eventName: EventName, action: Action) -> Route {
return ActionRoute(method: HttpMethod.GET, eventName: eventName, handler: ActionHandler.constant(action))
}
static func get(_ eventName: EventName, handler: @escaping ([String]) throws -> Action) -> Route {
return ActionRoute(method: HttpMethod.GET, eventName: eventName, handler: ActionHandler.path(handler))
}
var endpoint: String { get {
return self.eventName.rawValue
}}
func responseHandler(performer: ActionPerformer) -> HttpResponseHandler {
return ActionHttpResponseHandler(performer: performer, handler: self.handler)
}
}
struct ScreenshotRoute : Route {
enum Format : String {
case jpeg = "jpeg"
case png = "png"
}
let format: ScreenshotRoute.Format
var method: HttpMethod { get {
return HttpMethod.GET
}}
var endpoint: String { get {
return "screenshot.\(self.format.rawValue)"
}}
func responseHandler(performer: ActionPerformer) -> HttpResponseHandler {
let format = self.format
return SimpleResponseHandler { request in
guard let query = try SimpleResponseHandler.extractQueryFromPath(request) else {
throw QueryError.NoneProvided
}
let imageData: Data = try performer.runWithSingleSimulator(query) { simulator in
let image = try simulator.connect().connectToFramebuffer().image
switch (format) {
case .jpeg: return try image.jpegImageData()
case .png: return try image.pngImageData()
}
}
return HttpResponse(statusCode: 200, body: imageData, contentType: "image/" + self.format.rawValue)
}
}
}
class HttpRelay : Relay {
struct HttpError : Error, CustomStringConvertible {
let message: String
var description: String { get {
return message
}}
}
let portNumber: in_port_t
let httpServer: HttpServer
let performer: ActionPerformer
init(portNumber: in_port_t, performer: ActionPerformer) {
self.portNumber = portNumber
self.performer = performer
self.httpServer = HttpServer(
port: portNumber,
routes: HttpRelay.actionRoutes.flatMap { $0.httpRoutes(performer) },
logger: FBControlCoreGlobalConfiguration.defaultLogger
)
}
func start() throws {
do {
try self.httpServer.start()
} catch let error as NSError {
throw HttpRelay.HttpError(message: "An Error occurred starting the HTTP Server on Port \(self.portNumber): \(error.description)")
}
}
func stop() {
self.httpServer.stop()
}
fileprivate static var clearKeychainRoute: Route { get {
return ActionRoute.post(.clearKeychain) { json in
let bundleID = try json.getValue("bundle_id").getString()
return Action.clearKeychain(bundleID)
}
}}
fileprivate static var configRoute: Route { get {
return ActionRoute.getConstant(.config, action: Action.config)
}}
fileprivate static var diagnosticQueryRoute: Route { get {
return ActionRoute.post(.diagnose) { json in
let query = try FBDiagnosticQuery.inflate(fromJSON: json.decode())
return Action.diagnose(query, DiagnosticFormat.Content)
}
}}
fileprivate static var diagnosticRoute: Route { get {
return ActionRoute.get(.diagnose) { components in
guard let name = components.last else {
throw ParseError.custom("No diagnostic name provided")
}
let query = FBDiagnosticQuery.named([name])
return Action.diagnose(query, DiagnosticFormat.Content)
}
}}
fileprivate static var hidRoute: Route { get {
return ActionRoute.post(.HID) { json in
let event = try FBSimulatorHIDEvent.inflate(fromJSON: json.decode())
return Action.hid(event)
}
}}
fileprivate static var installRoute: Route { get {
return ActionRoute.postFile(.install, "ipa") { request, file in
let shouldCodeSign = request.getBoolQueryParam("codesign", false)
return Action.install(file.path, shouldCodeSign)
}
}}
fileprivate static var launchRoute: Route { get {
return ActionRoute.post(.launch) { json in
if let agentLaunch = try? FBAgentLaunchConfiguration.inflate(fromJSON: json.decode()) {
return Action.launchAgent(agentLaunch)
}
if let appLaunch = try? FBApplicationLaunchConfiguration.inflate(fromJSON: json.decode()) {
return Action.launchApp(appLaunch)
}
throw JSONError.parse("Could not parse \(json) either an Agent or App Launch")
}
}}
fileprivate static var listRoute: Route { get {
return ActionRoute.getConstant(.list, action: Action.list)
}}
fileprivate static var openRoute: Route { get {
return ActionRoute.post(.open) { json in
let urlString = try json.getValue("url").getString()
guard let url = URL(string: urlString) else {
throw JSONError.parse("\(urlString) is not a valid URL")
}
return Action.open(url)
}
}}
fileprivate static var recordRoute: Route { get {
return ActionRoute.post(.record) { json in
if try json.getValue("start").getBool() {
return Action.record(Record.start(nil))
}
return Action.record(Record.stop)
}
}}
fileprivate static var relaunchRoute: Route { get {
return ActionRoute.post(.relaunch) { json in
let launchConfiguration = try FBApplicationLaunchConfiguration.inflate(fromJSON: json.decode())
return Action.relaunch(launchConfiguration)
}
}}
fileprivate static var searchRoute: Route { get {
return ActionRoute.post(.search) { json in
let search = try FBBatchLogSearch.inflate(fromJSON: json.decode())
return Action.search(search)
}
}}
fileprivate static var setLocationRoute: Route { get {
return ActionRoute.post(.setLocation) { json in
let latitude = try json.getValue("latitude").getNumber().doubleValue
let longitude = try json.getValue("longitude").getNumber().doubleValue
return Action.setLocation(latitude, longitude)
}
}}
fileprivate static var tapRoute: Route { get {
return ActionRoute.post(.tap) { json in
let x = try json.getValue("x").getNumber().doubleValue
let y = try json.getValue("y").getNumber().doubleValue
return Action.tap(x, y)
}
}}
fileprivate static var terminateRoute: Route { get {
return ActionRoute.post(.terminate) { json in
let bundleID = try json.getValue("bundle_id").getString()
return Action.terminate(bundleID)
}
}}
fileprivate static var uploadRoute: Route { get {
let jsonToDiagnostics:(JSON)throws -> [FBDiagnostic] = { json in
switch json {
case .array(let array):
let diagnostics = try array.map { jsonDiagnostic in
return try FBDiagnostic.inflate(fromJSON: jsonDiagnostic.decode())
}
return diagnostics
case .dictionary:
let diagnostic = try FBDiagnostic.inflate(fromJSON: json.decode())
return [diagnostic]
default:
throw JSONError.parse("Unparsable Diagnostic")
}
}
return ActionRoute.post(.upload) { json in
return Action.upload(try jsonToDiagnostics(json))
}
}}
fileprivate static var actionRoutes: [Route] { get {
return [
self.clearKeychainRoute,
self.configRoute,
self.diagnosticQueryRoute,
self.diagnosticRoute,
self.hidRoute,
self.installRoute,
self.launchRoute,
self.listRoute,
self.openRoute,
self.recordRoute,
self.relaunchRoute,
self.searchRoute,
self.setLocationRoute,
self.tapRoute,
self.terminateRoute,
self.uploadRoute,
ScreenshotRoute(format: ScreenshotRoute.Format.png),
ScreenshotRoute(format: ScreenshotRoute.Format.jpeg),
]
}}
}
| bsd-3-clause | 0c2c6bb1636607e0bb5b7aff76d3d224 | 31.481633 | 138 | 0.692762 | 4.403985 | false | false | false | false |
dasdom/GlobalADN | GlobalADN/TimeLine/TimeLineViewController.swift | 1 | 1259 | //
// TimeLineViewController.swift
// GlobalADN
//
// Created by dasdom on 17.06.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import UIKit
class TimeLineViewController: UITableViewController {
var dataSource: TableViewProtocol
init(tableViewDataSource aDataSource: TableViewProtocol) {
dataSource = aDataSource
super.init(nibName: nil, bundle: nil)
let theRefreshControl = UIRefreshControl()
theRefreshControl.addTarget(dataSource, action: "fetchData:", forControlEvents: .ValueChanged)
refreshControl = theRefreshControl
self.title = "Global"
}
convenience required init(coder aDecoder: NSCoder!) {
self.init(tableViewDataSource: TimeLineDataSource())
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = dataSource as UITableViewDelegate
tableView.dataSource = dataSource as UITableViewDataSource
dataSource.registerCellsAndSetTableView(tableView)
dataSource.fetchData(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 1e3a9ebf4540a3d194c6e6f79db9edae | 26.977778 | 102 | 0.675933 | 5.380342 | false | false | false | false |
mohamede1945/quran-ios | Quran/EditController.swift | 2 | 3094 | //
// EditController.swift
// Quran
//
// Created by Mohamed Afifi on 5/7/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
public protocol EditControllerDelegate: class {
func hasItemsToEdit() -> Bool
}
open class EditController {
open var tableView: UITableView?
open weak var delegate: EditControllerDelegate?
open weak var navigationItem: UINavigationItem?
open var isEnabled: Bool = true
open let usesRightBarButton: Bool
public init(usesRightBarButton: Bool) {
self.usesRightBarButton = usesRightBarButton
}
open func configure(tableView: UITableView?, delegate: EditControllerDelegate?, navigationItem: UINavigationItem?) {
self.tableView = tableView
self.delegate = delegate
self.navigationItem = navigationItem
}
open func endEditing(_ animated: Bool) {
guard isEnabled else {
return
}
tableView?.setEditing(false, animated: animated)
updateEditBarItem(animated: animated)
}
open func onStartSwipingToEdit() {
guard isEnabled else {
return
}
updateEditBarItem(animated: true)
}
@objc
open func onEditBarButtonTapped() {
guard isEnabled else {
return
}
tableView?.setEditing(true, animated: true)
updateEditBarItem(animated: true)
}
@objc
open func onDoneBarButtonTapped() {
guard isEnabled else {
return
}
tableView?.setEditing(false, animated: true)
updateEditBarItem(animated: true)
}
open func onEditableItemsUpdated() {
guard isEnabled else {
return
}
if !(delegate?.hasItemsToEdit() ?? false) {
tableView?.setEditing(false, animated: true)
}
updateEditBarItem(animated: true)
}
private func updateEditBarItem(animated: Bool) {
let button: UIBarButtonItem?
if !(delegate?.hasItemsToEdit() ?? false) {
button = nil
} else if tableView?.isEditing ?? false {
button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDoneBarButtonTapped))
} else {
button = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(onEditBarButtonTapped))
}
if navigationItem?.rightBarButtonItem?.action != button?.action {
navigationItem?.setRightBarButton(button, animated: animated)
}
}
}
| gpl-3.0 | e5015912298afec3064efc342ac7458b | 27.915888 | 120 | 0.65223 | 4.804348 | false | false | false | false |
jjatie/Charts | Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift | 1 | 2441 | //
// TriangleShapeRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
open class TriangleShapeRenderer: ShapeRenderer {
open func renderShape(
context: CGContext,
dataSet: ScatterChartDataSet,
viewPortHandler _: ViewPortHandler,
point: CGPoint,
color: NSUIColor
) {
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius
let shapeHoleSize = shapeHoleSizeHalf * 2.0
let shapeHoleColor = dataSet.scatterShapeHoleColor
let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0
context.setFillColor(color.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf))
context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf))
if shapeHoleSize > 0.0 {
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
}
context.closePath()
context.fillPath()
if shapeHoleSize > 0.0, shapeHoleColor != nil {
context.setFillColor(shapeHoleColor!.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.closePath()
context.fillPath()
}
}
}
| apache-2.0 | 016356f618908ff5d55241500ef1dedd | 37.746032 | 124 | 0.646047 | 4.478899 | false | false | false | false |
lukesutton/yopuy | Sources/Service.swift | 1 | 5013 | import Foundation
/**
A struct which wraps interaction with a remote API. It delegates all the HTTP
requests to the underlying adapter.
*/
public struct Service<Adapter: HTTPAdapter> {
private let adapter: Adapter
/**
The root URL for the remote API. All requests will be made relative to this.
*/
public let host: URL
/**
The default configuration that will be applied to every request.
*/
public let options: Options
/**
Create a new instance of a service using an adapter and a root URL.
*/
public init(adapter: Adapter, host: URL, options: Options = Options()) {
self.adapter = adapter
self.host = host
self.options = options
}
/**
The handler function for service calls which return single resources.
*/
public typealias SingularHandler<R: Resource, M> = (Response<R, SingularPath, M, R.Singular>) -> Void
/**
The handler function for service calls which return a collection of
resources.
*/
public typealias CollectionHandler<R: IdentifiableResource, M> = (Response<R, CollectionPath, M, R.Collection>) -> Void
/**
Makes a `GET` request to an endpoint which returns a collection.
*/
public func call<R: IdentifiableResource>(_ path: Path<R, CollectionPath, GET>, options: Options = Options(), handler: @escaping CollectionHandler<R, GET>) {
perform(.GET, path, options: options, handler: handler, parser: R.parse(collection:))
}
/**
Makes a `POST` request to an endpoint which returns a resource.
*/
public func call<R: Resource>(_ path: Path<R, SingularPath, POST>, options: Options = Options(), handler: @escaping SingularHandler<R, POST>) {
perform(.POST, path, options: options, handler: handler, parser: R.parse(singular:))
}
/**
Makes a `GET` request to an endpoint which returns a resource.
*/
public func call<R: Resource>(_ path: Path<R, SingularPath, GET>, options: Options = Options(), handler: @escaping SingularHandler<R, GET>) {
perform(.GET, path, options: options, handler: handler, parser: R.parse(singular:))
}
/**
Makes a `PUT` request to an endpoint which returns a resource.
*/
public func call<R: Resource>(_ path: Path<R, SingularPath, PUT>, options: Options = Options(), handler: @escaping SingularHandler<R, PUT>) {
perform(.PUT, path, options: options, handler: handler, parser: R.parse(singular:))
}
/**
Makes a `PATCH` request to an endpoint which returns a resource.
*/
public func call<R: Resource>(_ path: Path<R, SingularPath, PATCH>, options: Options = Options(), handler: @escaping SingularHandler<R, PATCH>) {
perform(.PATCH, path, options: options, handler: handler, parser: R.parse(singular:))
}
/**
Makes a `DELETE` request to an endpoint which returns a resource.
*/
public func call<R: Resource>(_ path: Path<R, SingularPath, DELETE>, options: Options = Options(), handler: @escaping SingularHandler<R, DELETE>) {
perform(.DELETE, path, options: options, handler: handler, parser: R.parse(singular:))
}
/**
Performs the actual request. Generates a `Request` object and handles the
response from the underlying adapter, mapping it to the `Response` which is
sent to the handler.
*/
private func perform<R: Resource, P, M, Result>(
_ method: HTTPMethod,
_ path: Path<R, P, M>,
options: Options,
handler: @escaping (Response<R, P, M, Result>) -> Void,
parser: @escaping (Data) throws -> Result) {
// TODO: Catch errors with the URL generation
let request = Request<R, P, M>(
path: path,
URL: URL(string: path.path, relativeTo: host)!,
headers: merge(self.options.headers, options.headers, with: mergeHeaders),
query: merge(self.options.query, options.query, with: mergeQueries),
body: options.body
)
adapter.perform(method, request: request) { raw in
switch raw {
case let .error(error, _):
handler(Response<R, P, M, Result>.error(path: path, result: error, headers: []))
case .empty:
handler(Response<R, P, M, Result>.empty(path: path, headers: []))
case let .success(result, _):
do {
let result = try parser(result)
handler(Response<R, P, M, Result>.success(path: path, result: result, headers: []))
}
catch let error {
handler(Response<R, P, M, Result>.error(path: path, result: error, headers: []))
}
}
}
}
private func merge<A>(_ a: A?, _ b: A?, with op: (A, A) -> A) -> A? {
guard let a = a else { return b }
guard let b = b else { return a }
return op(a, b)
}
private func mergeHeaders(_ a: [Header], _ b: [Header]) -> [Header] {
let keys = b.map { $0.pair.0 }
let filtered = a.filter { !keys.contains($0.pair.0) }
return filtered + b
}
private func mergeQueries(_ a: [String: String], _ b: [String: String]) -> [String: String] {
var result = a
for (k, v) in b {
result.updateValue(v, forKey: k)
}
return result
}
}
| mit | 1077f005b77671aa28db674b0d967034 | 35.064748 | 159 | 0.648514 | 3.844325 | false | false | false | false |
a736220388/FinestFood | FinestFood/FinestFood/classes/FoodSubject/homePage/views/FoodDetailCell.swift | 1 | 1765 | //
// FoodDetailCell.swift
// FinestFood
//
// Created by qianfeng on 16/8/24.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class FoodDetailCell: UITableViewCell {
@IBOutlet weak var superView: UIView!
@IBOutlet weak var webView: UIWebView!
@IBAction func likeBtn(sender: UIButton) {
}
@IBAction func shareBtn(sender: UIButton) {
}
@IBAction func commentBtn(sender: UIButton) {
}
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var shareLabel: UILabel!
var lastContentOffsetY:CGFloat? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configModel(model:FoodDetailModel){
let webUrl = NSURL(string: model.url!)
let request = NSURLRequest(URL: webUrl!)
webView.loadRequest(request)
webView.scrollView.delegate = self
likeLabel.text = "\(model.likes_count!)人喜欢"
commentLabel.text = "\(model.comments_count!)次分享"
shareLabel.text = "\(model.shares_count!)条评论"
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension FoodDetailCell:UIScrollViewDelegate{
// func scrollViewDidScroll(scrollView: UIScrollView) {
// if lastContentOffsetY != nil{
// if lastContentOffsetY < webView.scrollView.contentOffset.y{
// superView.hidden = true
// }else{
// superView.hidden = false
// }
// }
// lastContentOffsetY = webView.scrollView.contentOffset.y
// }
}
| mit | e632edd25f8d417e00e658b00caeacd1 | 27.129032 | 73 | 0.638188 | 4.392947 | false | false | false | false |
AlesTsurko/DNMKit | DNMModel/PitchDyadSpeller.swift | 1 | 29511 | //
// PitchDyadSpeller.swift
// denm_pitch
//
// Created by James Bean on 8/12/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import Foundation
/**
Spells PitchDyads
*/
public class PitchDyadSpeller {
// MARK: String Representation
/// Printed description of PitchSpellerDyad
public var description: String = "PitchSpellerDyad"
// MARK: Attributes
/// PitchDyad spelled by PitchSpellerDyad
public var dyad: PitchDyad
public var bothPitchesHaveBeenSpelled: Bool {
return getBothPitchesHaveBeenSpelled() }
public var onePitchHasBeenSpelled: Bool {
return getOnePitchHasBeenSpelled()
}
public var neitherPitchHasBeenSpelled: Bool {
return getNeitherPitchHasBeenSpelled()
}
public var canBeSpelledObjectively: Bool {
return getCanBeSpelledObjectively()
}
/// All possible PitchSpelling combinations for PitchDyad
public var allPSDyads: [PitchSpellingDyad] { return getAllPSDyads() }
/// All PitchSpellingDyads that preserve interval quality properly
public var stepPreserving: [PitchSpellingDyad] { return getStepPreserving() }
/// All PitchSpellingDyads that preserve fine direction (1/8th-tone arrow direction)
public var fineMatching: [PitchSpellingDyad] { return getFineMatching() }
/// All PitchSpellingDyads that preserve coarse (flat == flat, quarterFlat != flat)
public var coarseMatching: [PitchSpellingDyad] { return getCoarseMatching() }
/// All PitchSpellingDyads that preserve coarse direction (sharp == quarterSharp)
public var coarseDirectionMatching: [PitchSpellingDyad] {
return getCoarseDirectionMatching()
}
/// All PitchSpellingDyads that preserve coarse resolution (sharp == flat, sharp != qsharp)
public var coarseResolutionMatching: [PitchSpellingDyad] {
return getCoarseResolutionMatching()
}
/**
In the case of pitches with an 1/8th-tone resolution (0.25), prevailingFine is used to
ensure same fine direction for both pitches in dyad (if necessary)
*/
public var prevailingFine: Float?
// MARK: Spelling with desired properties
/**
Fine value desired (in the context of a PitchVerticality, if other pitches require a
specific fine value)
*/
public var desiredFine: Float?
/**
Coarse direction value desired (in the context of a PitchVerticality, if other pitches
require a specific coarse direction)
*/
public var desiredCoarseDirection: Float?
/**
Coarse resolution value desired (in the context of a PitchVerticality, if other pitches
require a specific coarse coarse resolution)
*/
public var desiredCoarseResolution: Float?
/**
Create a PitchDyadSpeller with a PitchDyad (pair of Pitches)
- parameter dyad: Pair of Pitches
- returns: PitchDyadSpeller
*/
public init(dyad: PitchDyad) {
self.dyad = dyad
}
/**
Spell with a desired fine value
- parameter fine: Fine value (1/8th-tone direction (0, 0.25, -0.25))
*/
public func spellWithDesiredFine(fine: Float) {
self.desiredFine = fine
spell()
}
/**
Spell with a desired coarse direction value
- parameter coarseDirection: Coarse direction value (0, 1, -1)
*/
public func spellWithDesiredCoarseDirection(coarseDirection: Float) {
self.desiredCoarseDirection = coarseDirection
spell()
}
/**
Spell with a desired coarse resolution value
- parameter coarseResolution: Coarse resolution value (0.5, 1)
*/
public func spellWithDesiredCoarseResolution(coarseResolution: Float) {
self.desiredCoarseResolution = coarseResolution
spell()
}
/**
Spell the pitches of the Dyad. If this PitchDyadSpeller is NOT being used within a
PitchVerticalitySpeller (which, probably shouldn't happen -- but for testing purposes,
this is left as a possibility), set shouldSpellPitchesObjectively to true. This will
automatically set the PitchSpelling for Pitches that have a single possible PitchSpelling.
Same thing with mustSpellBothPitches, this will be cleaned up higher in the chain when
using a PitchVerticalitySpeller, but use it for testing
- parameter mustSpellBothPitches: Must spell both Pitches in Dyad
- parameter shouldSpellPitchesObjectively: Spell pitches with only one pitch spelling
*/
public func spell(
enforceBothPitchesSpelled mustSpellBothPitches: Bool = false,
spellPitchesObjectively shouldSpellPitchesObjectively: Bool = false
)
{
if shouldSpellPitchesObjectively { spellPitchesObjectivelyIfPossible() }
if bothPitchesHaveBeenSpelled {
//print("both have been spelled")
/* pass */
}
else if neitherPitchHasBeenSpelled {
neitherSpelled()
}
else if onePitchHasBeenSpelled {
oneSpelled()
}
// set default values to pitches if there's just no other solution
if mustSpellBothPitches {
for pitch in [dyad.pitch0, dyad.pitch1] {
if !pitch.hasBeenSpelled {
pitch.setPitchSpelling(pitch.possibleSpellings.first!)
}
}
}
}
// make private?
public func oneSpelled() {
guard onePitchHasBeenSpelled else { return }
// get spelled pitch
let unspelled: Pitch = dyad.pitch0.hasBeenSpelled ? dyad.pitch1 : dyad.pitch0
// get unspelled pitch
let spelled: Pitch = dyad.pitch0.hasBeenSpelled ? dyad.pitch0 : dyad.pitch1
// orient self around resolution of spelled pitch
switch spelled.resolution {
case 0.50: oneSpelledQuarterTone(spelled: spelled, unspelled: unspelled)
case 0.25: oneSpelledEighthTone(spelled: spelled, unspelled: unspelled)
default: oneSpelledHalfTone(spelled: spelled, unspelled: unspelled)
}
}
// make private
public func oneSpelledHalfTone(spelled spelled: Pitch, unspelled: Pitch) {
// filter step preserving to include more-global fine-match: encapsulate
if desiredFine != nil && unspelled.resolution == 0.25 {
//sp = filterPSDyadsToIncludeDesiredFineMatching(sp)
let all = filterPSDyadsToIncludeCurrentlySpelled(allPSDyads)
let dfm = filterPSDyadsToIncludeDesiredFineMatching(all)
switch dfm.count {
case 0:
break
case 1:
let spelling = getSpellingForUnspelledFromPSDyad(dfm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
let sp = intersection(dfm, array1: stepPreserving)
switch sp.count {
case 0:
break
case 1:
let spelling = getSpellingForUnspelledFromPSDyad(sp.first!)
spellPitch(unspelled, withSpelling: spelling)
break
default:
break
}
}
}
else {
let sp = filterPSDyadsToIncludeCurrentlySpelled(stepPreserving)
switch sp.count {
case 0:
//print("none sp: big trouble")
let crm = filterPSDyadsToIncludeCurrentlySpelled(coarseResolutionMatching)
switch crm.count {
case 0:
//print("none crm: really big trouble")
break
case 1:
//print("one crm")
let spelling = getSpellingForUnspelledFromPSDyad(crm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one crm")
let leastMeanSharp = getLeastMeanSharp(crm)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
}
case 1:
//print("one sp: spell")
let spelling = getSpellingForUnspelledFromPSDyad(sp.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp")
let sp_crm = intersection(sp, array1: coarseResolutionMatching)
switch sp_crm.count {
case 1:
//print("one sp_crm")
let spelling = getSpellingForUnspelledFromPSDyad(sp_crm.first!)
spellPitch(unspelled, withSpelling: spelling)
break
default:
//print("more than one sp_crm")
let leastMeanSharp = getLeastMeanSharp(sp)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
}
}
}
}
// make private
public func oneSpelledQuarterTone(spelled spelled: Pitch, unspelled: Pitch) {
// filter step preserving to include more-global fine-match: encapsulate
if desiredFine != nil && unspelled.resolution == 0.25 {
//sp = filterPSDyadsToIncludeDesiredFineMatching(sp)
let all = filterPSDyadsToIncludeCurrentlySpelled(allPSDyads)
let dfm = filterPSDyadsToIncludeDesiredFineMatching(all)
switch dfm.count {
case 0:
break
case 1:
let spelling = getSpellingForUnspelledFromPSDyad(dfm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
let sp = intersection(dfm, array1: stepPreserving)
switch sp.count {
case 0:
break
case 1:
let spelling = getSpellingForUnspelledFromPSDyad(sp.first!)
spellPitch(unspelled, withSpelling: spelling)
break
default:
break
}
}
}
// IF NO MORE-GLOBAL FINE MATCH REQUIRED
else {
let sp = filterPSDyadsToIncludeCurrentlySpelled(stepPreserving)
switch sp.count {
case 0:
//print("none step preserving: big trouble")
//let spelling = getLeastSharp(GetPitchSpellings.forPitch(unspelled))
let spelling = getLeastSharp(PitchSpelling.pitchSpellingsForPitch(pitch: unspelled))
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one step preserving: spell")
let spelling = getSpellingForUnspelledFromPSDyad(sp.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one step preserving")
let sp_cdm = intersection(sp, array1: coarseDirectionMatching)
switch sp_cdm.count {
case 0:
//print("none sp_cdm")
let leastMeanSharp = getLeastMeanSharp(sp)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one sp_cdm: spell")
let spelling = getSpellingForUnspelledFromPSDyad(sp_cdm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp_cdm")
let sp_cdm_crm = intersection(sp_cdm, array1: coarseResolutionMatching)
switch sp_cdm_crm.count {
case 0:
//print("none sp_cdm_crm")
break
case 1:
//print("one sp_cdm_crm")
let spelling = getSpellingForUnspelledFromPSDyad(sp_cdm_crm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp_cdm_crm")
break
}
}
}
}
}
// make private
public func oneSpelledEighthTone(spelled spelled: Pitch, unspelled: Pitch) {
prevailingFine = spelled.spelling!.fine
switch unspelled.resolution {
// UNSPELLED HAS 1/8th-tone RESOLUTION
case 0.25:
let fm = filterPSDyadsToIncludeCurrentlySpelled(fineMatching)
switch fm.count {
case 0:
//print("none fine matching: big trouble)")
break
case 1:
//print("one fine matching: spell")
let spelling = getSpellingForUnspelledFromPSDyad(fm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one fine matching")
let fm_sp = intersection(fm, array1: stepPreserving)
switch fm_sp.count {
case 0:
//print("none fm_sp: get least mean sharp of fm")
let leastMeanSharp = getLeastMeanSharp(fm)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one fm_sp: spell")
let spelling = getSpellingForUnspelledFromPSDyad(fm_sp.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one fm_sp")
let fm_sp_cdm = intersection(fm_sp, array1: coarseDirectionMatching)
switch fm_sp_cdm.count {
case 0:
//print("none fm_sp_cdm")
let leastMeanSharp = getLeastMeanSharp(fm_sp)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one fm_sp_cdm: spell")
let spelling = getSpellingForUnspelledFromPSDyad(fm_sp_cdm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one fm_sp_cdm")
let leastMeanSharp = getLeastMeanSharp(fm_sp_cdm)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
}
}
}
// UNSPELLED HAS A 1/4 or 1/2-tone RESOLUTION
default:
//print("unspelled does not have 1/8th-tone resolution")
let sp = filterPSDyadsToIncludeCurrentlySpelled(stepPreserving)
switch sp.count {
case 0:
//print("none sp")
let cdm = filterPSDyadsToIncludeCurrentlySpelled(coarseDirectionMatching)
let spelling = getSpellingForUnspelledFromPSDyad(cdm.first!)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one sp")
let spelling = getSpellingForUnspelledFromPSDyad(sp.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp")
let sp_cdm = intersection(sp, array1: coarseDirectionMatching)
switch sp_cdm.count {
case 0:
//print("none sp_cdm")
let leastMeanSharp = getLeastMeanSharp(sp)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one sp_cdm")
let spelling = getSpellingForUnspelledFromPSDyad(sp_cdm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp_cdm")
let sp_cdm_crm = intersection(sp_cdm, array1: coarseResolutionMatching)
switch sp_cdm_crm.count {
case 0:
//print("none sp_cdm_crm")
let leastMeanSharp = getLeastMeanSharp(sp_cdm)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
case 1:
//print("one sp_cdm_crm: spell")
let spelling = getSpellingForUnspelledFromPSDyad(sp_cdm_crm.first!)
spellPitch(unspelled, withSpelling: spelling)
default:
//print("more than one sp_cdm_crm")
let leastMeanSharp = getLeastMeanSharp(sp_cdm_crm)
let spelling = getSpellingForUnspelledFromPSDyad(leastMeanSharp)
spellPitch(unspelled, withSpelling: spelling)
}
}
}
}
}
// make private
public func neitherSpelled() {
// ENCAPSULATE
if dyad.pitch0.resolution == 1 && dyad.pitch1.resolution == 1 {
var spellings: [PitchSpelling] = []
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
spellings.append(spelling)
}
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
spellings.append(spelling)
}
let leastSharp = getLeastSharp(spellings)
spellPitch(leastSharp.pitch, withSpelling: leastSharp)
oneSpelled()
}
// ENCAPSULATE
else if desiredFine != nil {
for pitch in [dyad.pitch0, dyad.pitch1] {
//print(pitch)
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: pitch) {
if spelling.fine == desiredFine! {
//print("FINE MATCH")
spellPitch(pitch, withSpelling: spelling)
if onePitchHasBeenSpelled { oneSpelled() }
break
}
}
// DEPRECATED
/*
for spelling in GetPitchSpellings.forPitch(pitch) {
print(spelling)
if spelling.fine == desiredFine! {
//print("FINE MATCH")
spellPitch(pitch, withSpelling: spelling)
if onePitchHasBeenSpelled { oneSpelled() }
break
}
}
*/
}
}
// ENCAPSULATE
else {
var containsNaturalSpelling: Bool = false
for pitch in [dyad.pitch0, dyad.pitch1] {
//for spelling in GetPitchSpellings.forPitch(pitch) {
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: pitch) {
if spelling.coarse == 0.0 {
spellPitch(pitch, withSpelling: spelling)
containsNaturalSpelling = true
break
}
}
break
}
// ENCAPSULATE
if containsNaturalSpelling { if onePitchHasBeenSpelled { oneSpelled() } }
else {
var containsFlatOrSharpSpelling: Bool = false
for pitch in [dyad.pitch0, dyad.pitch1] {
//for spelling in GetPitchSpellings.forPitch(pitch) {
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: pitch) {
if spelling.coarseResolution == 1.0 {
spellPitch(pitch, withSpelling: spelling)
containsFlatOrSharpSpelling = true
break
}
}
break
}
// ENCAPSULATE
if containsFlatOrSharpSpelling {
//print("contains flat or sharp spelling")
if onePitchHasBeenSpelled { oneSpelled() }
else {
//print("still no pitches spelled")
// get spelling with least sharp
var dyads: [PitchSpellingDyad] = []
//for ps0 in GetPitchSpellings.forPitch(dyad.pitch0) {
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
//for ps1 in GetPitchSpellings.forPitch(dyad.pitch1) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let dyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
dyads.append(dyad)
}
}
let leastMeanSharp = getLeastMeanSharp(dyads)
spellPitch(dyad.pitch0, withSpelling: leastMeanSharp.pitchSpelling0)
spellPitch(dyad.pitch1, withSpelling: leastMeanSharp.pitchSpelling1)
}
}
else {
// this only happens if both pitches are 1/4 tone pitches: 4.5 / 11.5
//for spelling in GetPitchSpellings.forPitch(dyad.pitch0) {
for spelling in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
if spelling.coarse == 0.5 {
spellPitch(dyad.pitch0, withSpelling: spelling)
break
}
}
if onePitchHasBeenSpelled { oneSpelled() }
}
}
}
}
private func filterPSDyadsToIncludeCurrentlySpelled(psDyads: [PitchSpellingDyad])
-> [PitchSpellingDyad]
{
assert(onePitchHasBeenSpelled, "one pitch must be spelled")
if dyad.pitch0.hasBeenSpelled {
return psDyads.filter { $0.pitchSpelling0 == self.dyad.pitch0.spelling! }
}
else {
return psDyads.filter { $0.pitchSpelling1 == self.dyad.pitch1.spelling! }
}
}
private func filterPSDyadsToIncludeDesiredFineMatching(psDyads: [PitchSpellingDyad])
-> [PitchSpellingDyad]
{
assert(desiredFine != nil, "desiredFine must be set for this to work")
var psDyads = psDyads
if dyad.pitch0.resolution == 0.25 {
psDyads = psDyads.filter { $0.pitchSpelling0.fine == self.desiredFine! }
}
else { psDyads = psDyads.filter { $0.pitchSpelling1.fine == self.desiredFine! } }
return psDyads
}
public func spellPitchesObjectivelyIfPossible() {
for pitch in [dyad.pitch0, dyad.pitch1] {
if PitchSpelling.pitchSpellingsForPitch(pitch: pitch).count == 1 {
let spelling = PitchSpelling.pitchSpellingsForPitch(pitch: pitch).first!
pitch.setPitchSpelling(spelling)
}
}
}
private func getCanBeSpelledObjectively() -> Bool {
let pitch0_count = PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0).count
let pitch1_count = PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1).count
return pitch0_count == 1 && pitch1_count == 1
}
private func getBothPitchesHaveBeenSpelled() -> Bool {
return dyad.pitch0.hasBeenSpelled && dyad.pitch1.hasBeenSpelled
}
private func getOnePitchHasBeenSpelled() -> Bool {
return (
dyad.pitch0.hasBeenSpelled && !dyad.pitch1.hasBeenSpelled ||
dyad.pitch1.hasBeenSpelled && !dyad.pitch0.hasBeenSpelled
)
}
private func getNeitherPitchHasBeenSpelled() -> Bool {
return !dyad.pitch0.hasBeenSpelled && !dyad.pitch1.hasBeenSpelled
}
public func getCoarseMatching() -> [PitchSpellingDyad] {
var coarseMatching: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
if psDyad.isCoarseMatching { coarseMatching.append(psDyad) }
}
}
return coarseMatching
}
public func getCoarseResolutionMatching() -> [PitchSpellingDyad] {
var coarseResolutionMatching: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
if psDyad.isCoarseResolutionMatching { coarseResolutionMatching.append(psDyad) }
}
}
return coarseResolutionMatching
}
public func getCoarseDirectionMatching() -> [PitchSpellingDyad] {
var coarseDirectionMatching: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
if psDyad.isCoarseDirectionMatching { coarseDirectionMatching.append(psDyad) }
}
}
return coarseDirectionMatching
}
public func getFineMatching() -> [PitchSpellingDyad] {
var fineMatching: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
if psDyad.isFineMatching { fineMatching.append(psDyad) }
}
}
return fineMatching
}
public func getStepPreserving() -> [PitchSpellingDyad] {
var stepPreserving: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
if psDyad.isStepPreserving { stepPreserving.append(psDyad) }
}
}
return stepPreserving
}
private func getAllPSDyads() -> [PitchSpellingDyad] {
var allPSDyads: [PitchSpellingDyad] = []
for ps0 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch0) {
for ps1 in PitchSpelling.pitchSpellingsForPitch(pitch: dyad.pitch1) {
let psDyad = PitchSpellingDyad(ps0: ps0, ps1: ps1)
allPSDyads.append(psDyad)
}
}
return allPSDyads
}
private func getSpellingForUnspelledFromPSDyad(psDyad: PitchSpellingDyad)
-> PitchSpelling
{
// manage this better
assert(onePitchHasBeenSpelled, "one pitch must be spelled")
return dyad.pitch0.hasBeenSpelled ? psDyad.pitchSpelling1 : psDyad.pitchSpelling0
}
private func getLeastMeanSharp(psDyads: [PitchSpellingDyad]) -> PitchSpellingDyad {
var leastMeanSharp: PitchSpellingDyad?
for psDyad in psDyads {
if leastMeanSharp == nil { leastMeanSharp = psDyad }
else if abs(psDyad.meanSharpness) < abs(leastMeanSharp!.meanSharpness) {
leastMeanSharp = psDyad
}
}
return leastMeanSharp!
}
private func getLeastSharp(pitchSpellings: [PitchSpelling]) -> PitchSpelling {
var leastSharp: PitchSpelling?
for pitchSpelling in pitchSpellings {
if leastSharp == nil { leastSharp = pitchSpelling }
else if abs(pitchSpelling.sharpness) < abs(leastSharp!.sharpness) {
leastSharp = pitchSpelling
}
}
return leastSharp!
}
private func spellPitch(unspelled: Pitch, withSpelling spelling: PitchSpelling) {
unspelled.setPitchSpelling(spelling)
if spelling.fine != 0 { prevailingFine = spelling.fine }
}
}
| gpl-2.0 | 8b4dc345ef2ea2a64ba37072717dfde9 | 39.424658 | 100 | 0.557099 | 4.652373 | false | false | false | false |
groue/RxGRDB | Tests/RxGRDBTests/ValueObservationTests.swift | 1 | 12998 | import XCTest
import GRDB
import RxSwift
import RxGRDB
private struct Player: Codable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
var score: Int?
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer)
}
}
}
class ValueObservationTests : XCTestCase {
// MARK: - Default Scheduler
func testDefaultSchedulerChangesNotifications() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
try withExtendedLifetime(disposeBag) {
let testSubject = ReplaySubject<Int>.createUnbounded()
ValueObservation
.tracking(Player.fetchCount)
.rx.observe(in: writer)
.subscribe(testSubject)
.disposed(by: disposeBag)
try writer.writeWithoutTransaction { db in
try Player(id: 1, name: "Arthur", score: 1000).insert(db)
try db.inTransaction {
try Player(id: 2, name: "Barbara", score: 750).insert(db)
try Player(id: 3, name: "Craig", score: 500).insert(db)
return .commit
}
}
let expectedElements = [0, 1, 3]
if writer is DatabaseQueue {
let elements = try testSubject
.take(expectedElements.count)
.toBlocking(timeout: 1).toArray()
XCTAssertEqual(elements, expectedElements)
} else {
let elements = try testSubject
.take(until: { $0 == expectedElements.last }, behavior: .inclusive)
.toBlocking(timeout: 1).toArray()
assertValueObservationRecordingMatch(recorded: elements, expected: expectedElements)
}
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
func testDefaultSchedulerFirstValueIsEmittedAsynchronously() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
withExtendedLifetime(disposeBag) {
let expectation = self.expectation(description: "")
let semaphore = DispatchSemaphore(value: 0)
ValueObservation
.tracking(Player.fetchCount)
.rx.observe(in: writer)
.subscribe(onNext: { _ in
semaphore.wait()
expectation.fulfill()
})
.disposed(by: disposeBag)
semaphore.signal()
waitForExpectations(timeout: 1, handler: nil)
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
func testDefaultSchedulerError() throws {
func test(writer: DatabaseWriter) throws {
let observable = ValueObservation
.tracking { try $0.execute(sql: "THIS IS NOT SQL") }
.rx.observe(in: writer)
let result = observable.toBlocking().materialize()
switch result {
case .completed:
XCTFail("Expected error")
case let .failed(elements: _, error: error):
XCTAssertNotNil(error as? DatabaseError)
}
}
try Test(test)
.run { DatabaseQueue() }
.runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
}
// MARK: - Immediate Scheduler
func testImmediateSchedulerChangesNotifications() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
try withExtendedLifetime(disposeBag) {
let testSubject = ReplaySubject<Int>.createUnbounded()
ValueObservation
.tracking(Player.fetchCount)
.rx.observe(in: writer, scheduling: .immediate)
.subscribe(testSubject)
.disposed(by: disposeBag)
try writer.writeWithoutTransaction { db in
try Player(id: 1, name: "Arthur", score: 1000).insert(db)
try db.inTransaction {
try Player(id: 2, name: "Barbara", score: 750).insert(db)
try Player(id: 3, name: "Craig", score: 500).insert(db)
return .commit
}
}
let expectedElements = [0, 1, 3]
if writer is DatabaseQueue {
let elements = try testSubject
.take(expectedElements.count)
.toBlocking(timeout: 1).toArray()
XCTAssertEqual(elements, expectedElements)
} else {
let elements = try testSubject
.take(until: { $0 == expectedElements.last }, behavior: .inclusive)
.toBlocking(timeout: 1).toArray()
assertValueObservationRecordingMatch(recorded: elements, expected: expectedElements)
}
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
func testImmediateSchedulerEmitsFirstValueSynchronously() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
withExtendedLifetime(disposeBag) {
let semaphore = DispatchSemaphore(value: 0)
ValueObservation
.tracking(Player.fetchCount)
.rx.observe(in: writer, scheduling: .immediate)
.subscribe(onNext: { _ in
semaphore.signal()
})
.disposed(by: disposeBag)
semaphore.wait()
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
func testImmediateSchedulerError() throws {
func test(writer: DatabaseWriter) throws {
let observable = ValueObservation
.tracking { try $0.execute(sql: "THIS IS NOT SQL") }
.rx.observe(in: writer, scheduling: .immediate)
let result = observable.toBlocking().materialize()
switch result {
case .completed:
XCTFail("Expected error")
case let .failed(elements: _, error: error):
XCTAssertNotNil(error as? DatabaseError)
}
}
try Test(test)
.run { DatabaseQueue() }
.runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
}
func testIssue780() throws {
func test(dbPool: DatabasePool) throws {
struct Entity: Codable, FetchableRecord, PersistableRecord, Equatable {
var id: Int64
var name: String
}
try dbPool.write { db in
try db.create(table: "entity") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
}
let observation = ValueObservation.tracking(Entity.fetchAll)
let entities = try dbPool.rx
.write { db in try Entity(id: 1, name: "foo").insert(db) }
.asCompletable()
.andThen(observation.rx.observe(in: dbPool, scheduling: .immediate))
.take(1)
.toBlocking(timeout: 1)
.single()
XCTAssertEqual(entities, [Entity(id: 1, name: "foo")])
}
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
}
// MARK: - Utils
/// This test checks the fundamental promise of ValueObservation by
/// comparing recorded values with expected values.
///
/// Recorded values match the expected values if and only if:
///
/// - The last recorded value is the last expected value
/// - Recorded values are in the same order as expected values
///
/// However, both missing and repeated values are allowed - with the only
/// exception of the last expected value which can not be missed.
///
/// For example, if the expected values are [0, 1], then the following
/// recorded values match:
///
/// - `[0, 1]` (identical values)
/// - `[1]` (missing value but the last one)
/// - `[0, 0, 1, 1]` (repeated value)
///
/// However the following recorded values don't match, and fail the test:
///
/// - `[1, 0]` (wrong order)
/// - `[0]` (missing last value)
/// - `[]` (missing last value)
/// - `[0, 1, 2]` (unexpected value)
/// - `[1, 0, 1]` (unexpected value)
func assertValueObservationRecordingMatch<Value>(
recorded recordedValues: [Value],
expected expectedValues: [Value],
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line)
where Value: Equatable
{
_assertValueObservationRecordingMatch(
recorded: recordedValues,
expected: expectedValues,
// Last value can't be missed
allowMissingLastValue: false,
message(), file: file, line: line)
}
private func _assertValueObservationRecordingMatch<R, E>(
recorded recordedValues: R,
expected expectedValues: E,
allowMissingLastValue: Bool,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line)
where
R: BidirectionalCollection,
E: BidirectionalCollection,
R.Element == E.Element,
R.Element: Equatable
{
guard let value = expectedValues.last else {
if !recordedValues.isEmpty {
XCTFail("unexpected recorded prefix \(Array(recordedValues)) - \(message())", file: file, line: line)
}
return
}
let recordedSuffix = recordedValues.reversed().prefix(while: { $0 == value })
let expectedSuffix = expectedValues.reversed().prefix(while: { $0 == value })
if !allowMissingLastValue {
// Both missing and repeated values are allowed in the recorded values.
// This is because of asynchronous DatabasePool observations.
if recordedSuffix.isEmpty {
XCTFail("missing expected value \(value) - \(message())", file: file, line: line)
}
}
let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count)
let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count)
_assertValueObservationRecordingMatch(
recorded: remainingRecordedValues,
expected: remainingExpectedValues,
// Other values can be missed
allowMissingLastValue: true,
message(), file: file, line: line)
}
}
| mit | acd6af8aa279202abaaffcfdec93a8e9 | 38.871166 | 117 | 0.538852 | 5.353377 | false | true | false | false |
PekanMmd/Pokemon-XD-Code | Objects/managers/XGSettings.swift | 1 | 2672 | //
// XGSettings.swift
// GoD Tool
//
// Created by Stars Momodu on 09/09/2019.
//
import Foundation
private let settingsFile = XGFiles.nameAndFolder("Settings.json", XGFolders.Documents)
class XGSettings {
static var current = XGSettings.load()
var verbose = false
var increaseFileSizes = true
var enableExperimentalFeatures = false
var inputDuration = 0.18 // How long a button press lasts by default when input into Dolphin
var inputPollDuration: UInt32 = 500 // How often to poll for new inputs (ms)
private struct Settings: Codable {
var verbose: Bool?
var increaseFileSizes: Bool?
var enableExperimentalFeatures: Bool?
var inputDuration: Double?
var inputPollDuration: UInt32?
var username: String?
enum CodingKeys: String, CodingKey {
case verbose = "Verbose Logs"
case increaseFileSizes = "Increase File Sizes"
case enableExperimentalFeatures = "Enable Experimental Features"
case inputDuration = "The default duration (seconds) for button inputs when running Dolphin"
case inputPollDuration = "The length of time (milliseconds) after which to poll for new inputs when running Dolphin"
}
}
private init() {}
private init(settings: Settings) {
if let verbose = settings.verbose {
self.verbose = verbose
}
if let increaseFileSizes = settings.increaseFileSizes {
self.increaseFileSizes = increaseFileSizes
}
if let experimental = settings.enableExperimentalFeatures {
self.enableExperimentalFeatures = experimental
}
if let duration = settings.inputDuration {
self.inputDuration = duration
}
if let duration = settings.inputPollDuration {
self.inputPollDuration = duration
}
}
func save() {
guard XGISO.inputISOFile != nil else { return }
let settingsData = Settings(verbose: verbose,
increaseFileSizes: increaseFileSizes,
enableExperimentalFeatures: enableExperimentalFeatures,
inputDuration: inputDuration,
inputPollDuration: inputPollDuration
)
settingsData.writeJSON(to: settingsFile)
}
static func reload() {
XGSettings.current = load()
}
fileprivate static func load() -> XGSettings {
if XGISO.inputISOFile != nil, settingsFile.exists {
do {
let loadedSettings = try Settings.fromJSON(file: settingsFile)
let settings = XGSettings(settings: loadedSettings)
settings.save()
return settings
} catch {
printg("Error loading settings file: \(settingsFile.path)")
printg("Overwriting settings with new file. Corrupt file will be renamed.")
settingsFile.rename("Settings Corrupt.json")
}
}
let settings = XGSettings()
settings.save()
return settings
}
}
| gpl-2.0 | 5cd67a1a3053be23a28249fe5afb650b | 27.126316 | 119 | 0.727171 | 3.8557 | false | false | false | false |
radicalbear/radbear-ios | radbear-ios/Classes/FontAwesome.swift | 1 | 1835 | //
// FontAwesome.swift
//
// Created by Ryan Murphy on 10/16/17.
// Copyright © 2017 Radical Bear, LLC. All rights reserved.
//
import FontAwesomeKit
public class FontAwesome{
public class func getFontAwesomeIcon(icon: FAKFontAwesome, darkTheme: Bool, dim: Bool) -> UIImage{
let darkColor = dim ? UIColor.darkGray : UIColor.black
let lightColor = dim ? UIColor.lightGray : UIColor.white
let theme = darkTheme ? lightColor : darkColor
return getFontAwesomeIcon(icon: icon, color: theme)
}
public class func getFontAwesomeIcon(icon: FAKFontAwesome) -> UIImage{
return getFontAwesomeIcon(icon: icon, color: nil)
}
public class func getFontAwesomeIcon(icon: FAKFontAwesome, color: UIColor?) -> UIImage{
let resizedIcon = FAKFontAwesome.init(code: icon.characterCode(), size: icon.iconFontSize - 5)
if(color != nil){
resizedIcon!.addAttribute(NSForegroundColorAttributeName, value:color)
}
return resizedIcon!.image(with: CGSize(width: resizedIcon!.iconFontSize, height: resizedIcon!.iconFontSize))
}
public class func getFontAwesomeIcon(iconName: String, color: UIColor, size: Float) -> UIImage?{
do{
let icon = try FAKFontAwesome.init(identifier: iconName, size: CGFloat(size))
icon.addAttribute(NSForegroundColorAttributeName, value:color)
return icon.image(with: CGSize(width: icon.iconFontSize, height: icon.iconFontSize))
} catch {
NSLog("Could not find icon: %@", iconName);
return nil
}
}
public class func defaultPlaceholder() -> UIImage?{
let DEFAULT_ICON_SIZE: Float = 28
return FontAwesome.getFontAwesomeIcon(iconName: "fa-picture-o", color: UIColor.gray, size: DEFAULT_ICON_SIZE)
}
}
| mit | 06178bcb5628726b6ce76791d7c8ca18 | 39.755556 | 116 | 0.672301 | 4.335697 | false | false | false | false |
LinShiwei/HealthyDay | HealthyDay/MainInformationView.swift | 1 | 8604 | //
// MainInformationView.swift
// HealthyDay
//
// Created by Linsw on 16/10/2.
// Copyright © 2016年 Linsw. All rights reserved.
//
import UIKit
internal protocol MainInfoViewTapGestureDelegate {
func didTap(inLabel label:UILabel)
}
internal class MainInformationView: UIView{
//MARK: Property
private var stepCountLabel : StepCountLabel!
private var distanceWalkingRunningLabel : DistanceWalkingRunningLabel!
private let containerView = UIView()
private let dot = UIView()
private let labelMaskView = UIView()
private let decorativeView = UIView()
private let gradientLayer = CAGradientLayer()
private var bottomDecorativeCurveView : BottomDecorativeCurve?
private let bottomDecorativeCurveRotateDegree : CGFloat = CGFloat.pi/180*2
internal var stepCount = 0{
didSet{
stepCountLabel.stepCount = stepCount
}
}
internal var distance = 0{
didSet{
distanceWalkingRunningLabel.text = String(format:"%.2f",Double(distance)/1000)
}
}
internal var delegate : MainInfoViewTapGestureDelegate?
//MARK: View
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
initGradientLayer()
initContainerView(rotateRadius: frame.height)
initDotView()
initBottomDecorativeView()
addGestureToSelf()
}
//MARK: Custom View
private func initGradientLayer(){
guard gradientLayer.superlayer == nil else {return}
gradientLayer.frame = bounds
gradientLayer.colors = [theme.lightThemeColor.cgColor,theme.darkThemeColor.cgColor]
layer.addSublayer(gradientLayer)
}
private func initContainerView(rotateRadius radius:CGFloat){
guard containerView.superview == nil else{return}
containerView.center = CGPoint(x: frame.width/2, y: frame.height/2+radius)
distanceWalkingRunningLabel = DistanceWalkingRunningLabel(frame:CGRect(x: -containerView.center.x, y: -containerView.center.y+frame.height*0.17, width: frame.width, height: frame.height*0.6))
stepCountLabel = StepCountLabel(size: CGSize(width:frame.width,height:frame.height*0.47), center: CGPoint(x: radius*sin(CGFloat.pi/3), y: -radius*sin(CGFloat.pi/6)))
containerView.addSubview(stepCountLabel)
containerView.addSubview(distanceWalkingRunningLabel)
addSubview(containerView)
}
private func initDotView(){
guard dot.superview == nil else{return}
dot.frame.size = CGSize(width: 10, height: 10)
dot.center = CGPoint(x: frame.width*2/5, y: 66)
dot.layer.cornerRadius = dot.frame.width
dot.layer.backgroundColor = UIColor.white.cgColor
addSubview(dot)
}
private func initBottomDecorativeView(){
guard decorativeView.superview == nil else{return}
let height = frame.height*0.24
let width = frame.width
decorativeView.frame = CGRect(x: 0, y: frame.height-height, width: width, height: height)
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: height))
path.addCurve(to: CGPoint(x: width, y:height), controlPoint1: CGPoint(x:width/3,y:height/2), controlPoint2: CGPoint(x:width/3*2,y:height/2))
path.addLine(to: CGPoint(x: 0, y: height))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.lineWidth = 1
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
decorativeView.layer.addSublayer(shapeLayer)
if bottomDecorativeCurveView == nil {
bottomDecorativeCurveView = BottomDecorativeCurve(withMainInfoViewFrame: frame, andBottomDecorativeViewSize: CGSize(width: width, height: height))
decorativeView.addSubview(bottomDecorativeCurveView!)
}
addSubview(decorativeView)
}
//MARK: Gesture Helper
private func addGestureToSelf(){
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MainInformationView.didTap(_:)))
addGestureRecognizer(tapGesture)
}
internal func didTap(_ sender: UITapGestureRecognizer){
if pointIsInLabelText(point:sender.location(in: stepCountLabel), label:stepCountLabel){
delegate?.didTap(inLabel: stepCountLabel)
}
if pointIsInLabelText(point: sender.location(in: distanceWalkingRunningLabel), label: distanceWalkingRunningLabel){
delegate?.didTap(inLabel: distanceWalkingRunningLabel)
}
}
private func pointIsInLabelText(point:CGPoint, label:UILabel)->Bool{
if (abs(point.x-label.bounds.width/2) < label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 0).width/2)&&(abs(point.y-label.bounds.height/2) < label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 0).height/2){
return true
}else{
return false
}
}
//MARK: Animation helper
private func hideDistanceWalkingRunningSublabel(alpha:CGFloat){
guard distanceWalkingRunningLabel.subviewsAlpha != alpha else {return}
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {[unowned self] in
self.distanceWalkingRunningLabel.subviewsAlpha = alpha
}, completion: nil)
}
private func hideStepCountSublabel(alpha:CGFloat){
guard stepCountLabel.subviewsAlpha != alpha else {return}
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {[unowned self] in
self.stepCountLabel.subviewsAlpha = alpha
}, completion: nil)
}
private func swipeClockwise(){
containerView.transform = .identity
dot.center.x = frame.width*2/5
bottomDecorativeCurveView?.transform = .identity
}
private func swipeCounterclockwise(){
containerView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/3)
dot.center.x = frame.width*3/5
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree)
}
internal func panAnimation(progress: CGFloat, currentState: MainVCState){
assert(progress >= -1 && progress <= 1)
switch progress {
case 1:
swipeClockwise()
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 1)
case -1:
swipeCounterclockwise()
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 1)
default:
switch currentState{
case .running:
hideDistanceWalkingRunningSublabel(alpha: 0)
hideStepCountSublabel(alpha: 1)
if progress > 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*progress/2)
dot.center.x = frame.width*2/5 //可以去掉吗
bottomDecorativeCurveView?.transform = .identity
}
if progress < 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*progress)
dot.center.x = frame.width*2/5-frame.width/5*progress
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: bottomDecorativeCurveRotateDegree*progress)
}
case .step:
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 0)
if progress > 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*(progress-1))
dot.center.x = frame.width*3/5-frame.width/5*progress
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree*(1-progress))
}
if progress < 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*(progress/2-1))
dot.center.x = frame.width*3/5
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree)
}
}
}
}
internal func refreshAnimations(){
bottomDecorativeCurveView?.refreshAnimation()
}
}
| mit | e689c33018fe8ec7f35ed499f35fe5c1 | 39.909524 | 240 | 0.655453 | 4.599036 | false | false | false | false |
ricardorauber/iOS-Swift | iOS-Swift.playground/Pages/Constants and Variables.xcplaygroundpage/Contents.swift | 1 | 1830 | //: ## Constants and Variables
//: ----
//: [Previous](@previous)
import Foundation
//: Constants
let constant = "My first constant!"
//: Variables
var variable = "My first variable!"
var r = 250.0, g = 100.0, b = 210.0
//: Type Annotations
var hello: String
hello = "Hello!"
//: Emoji Names
//: - Emoji shortcut: control + command + space
let 😎 = ":)"
//: Printing
print(😎)
print("Using a string with a constant or variable: \(hello) \(😎)")
//: Comments
// One line comment
/*
Multiple
Lines
Comment
*/
//: Integer
let intConstant1 = 10
let intConstant2: Int = 10
let uIntConstant: UInt = 20
let uInt8Constant: UInt8 = 8
let uInt16Constant: UInt16 = 16
let uInt32Constant: UInt32 = 32
let uInt64Constant: UInt64 = 21
//: Float
let floatConstant: Float = 10.5
//: Double
let doubleConstant1 = 30.7
let doubleConstant2: Double = 30.7
//: Boolean
let trueConstant = true
let falseConstant: Bool = false
let anotherOne = !trueConstant
//: String
let stringConstant1 = "You already know that, right?"
let stringConstant2: String = "Yes, you know!"
//: Tuples
let tupleWith2Values = (100, "A message")
let tupleWith2NamedValues = (number: 200, text: "Another Message")
let (intValue, stringValue) = tupleWith2Values
let (onlyTheIntValue, _) = tupleWith2NamedValues
let (_, onlyTheStringValue) = tupleWith2NamedValues
let standardConstantFromTuple = tupleWith2Values.0
let standardConstantFromNamedTuple = tupleWith2NamedValues.text
print(
intValue,
stringValue,
onlyTheIntValue,
onlyTheStringValue,
standardConstantFromTuple,
standardConstantFromNamedTuple
)
//: Type aliases
typealias MyInt = Int8
var customAlias1 = MyInt.min
var customAlias2 = MyInt.max
//: Converting types
let doubleToIntConstant = Int(45.32)
let intToDoubleConstant = Double(50)
//: [Next](@next)
| mit | 3976e04bae7e5ac197098997e8dd872b | 17.029703 | 66 | 0.716639 | 3.475191 | false | false | false | false |
someoneAnyone/Nightscouter | Common/Models/ServerConfiguration.swift | 1 | 14820 | //
// ServerConfiguration.swift
// Nightscouter
//
// Created by Peter Ina on 1/11/16.
// Copyright © 2016 Nothingonline. All rights reserved.
//
import Foundation
public struct ServerConfiguration: Codable, CustomStringConvertible {
public let status: String
public let version: String
public var name: String
public let serverTime: String
public let apiEnabled: Bool
public let careportalEnabled: Bool
public let boluscalcEnabled: Bool
public var settings: Settings?
public var description: String {
var dict = [String: Any]()
dict["status"] = status
dict["apiEnabled"] = apiEnabled
dict["serverTime"] = serverTime
dict["careportalEnabled"] = careportalEnabled
dict["boluscalcEnabled"] = boluscalcEnabled
dict["settings"] = settings
dict["version"] = version
dict["name"] = name
return dict.description
}
public init() {
self.status = "okToTest"
self.version = "0.0.0test"
self.name = "NightscoutTest"
self.serverTime = "2016-01-13T15:04:59.059Z"
self.apiEnabled = true
self.careportalEnabled = false
self.boluscalcEnabled = false
let placeholderAlarm1: [Double] = [15, 30, 45, 60]
let placeholderAlarm2: [Double] = [30, 60, 90, 120]
let alrm = Alarm(urgentHigh: true, urgentHighMins: placeholderAlarm2, high: true, highMins: placeholderAlarm2, low: true, lowMins: placeholderAlarm1, urgentLow: true, urgentLowMins: placeholderAlarm1, warnMins: placeholderAlarm2)
let timeAgo = TimeAgoAlert(warn: true, warnMins: 60.0 * 10, urgent: true, urgentMins: 60.0 * 15)
let plugins: [Plugin] = [Plugin.delta, Plugin.rawbg]
let thre = Thresholds(bgHigh: 300, bgLow: 70, bgTargetBottom: 60, bgTargetTop: 250)
let s = Settings(units: .mgdl, showRawbg: .never, customTitle: "NightscoutDefault", alarmUrgentHigh: true, alarmUrgentHighMins: alrm.urgentLowMins, alarmHigh: alrm.urgentHigh, alarmHighMins: alrm.warnMins, alarmLow: alrm.low, alarmLowMins: alrm.lowMins, alarmUrgentLow: alrm.urgentLow, alarmUrgentLowMins: alrm.urgentLowMins, alarmWarnMins: alrm.warnMins, alarmTimeagoWarn: timeAgo.warn, alarmTimeagoWarnMins: timeAgo.urgentMins, alarmTimeagoUrgent: timeAgo.urgent, alarmTimeagoUrgentMins: timeAgo.urgentMins, thresholds: thre, enable: plugins)
self.settings = s
}
public init(status: String, version: String, name: String, serverTime: String, api: Bool, carePortal: Bool, boluscalc: Bool, settings: Settings?, head: String) {
self.status = status
self.version = version
self.name = name
self.serverTime = serverTime
self.apiEnabled = api
self.careportalEnabled = carePortal
self.boluscalcEnabled = boluscalc
self.settings = settings
}
}
extension ServerConfiguration {
public init(name: String) {
var c = ServerConfiguration()
c.settings?.customTitle = name
self = c
}
}
extension ServerConfiguration: Equatable { }
public func ==(lhs: ServerConfiguration, rhs: ServerConfiguration) -> Bool {
return lhs.status == rhs.status &&
lhs.version == rhs.version &&
lhs.name == rhs.name &&
lhs.serverTime == rhs.serverTime &&
lhs.apiEnabled == rhs.apiEnabled &&
lhs.careportalEnabled == rhs.careportalEnabled &&
lhs.boluscalcEnabled == rhs.boluscalcEnabled &&
lhs.settings == rhs.settings
}
extension ServerConfiguration {
public var displayName: String {
if let settings = settings {
return settings.customTitle
} else {
return name
}
}
public var displayRawData: Bool {
if let settings = settings {
let rawEnabled = settings.enable.contains(Plugin.rawbg)
if rawEnabled {
switch settings.showRawbg {
case .noise:
return true
case .always:
return true
case .never:
return false
}
}
}
return false
}
public var displayUnits: GlucoseUnit {
if let settings = settings {
return settings.units
}
return .mgdl
}
}
public struct Settings: Codable {
public let units: GlucoseUnit
public let showRawbg: RawBGMode
public var customTitle: String
public var alarms: Alarm {
return Alarm(urgentHigh: alarmUrgentHigh, urgentHighMins: alarmUrgentHighMins, high: alarmHigh, highMins: alarmHighMins, low: alarmLow, lowMins: alarmLowMins, urgentLow: alarmUrgentLow, urgentLowMins: alarmUrgentLowMins, warnMins: alarmWarnMins)
}
public let alarmUrgentHigh: Bool
public let alarmUrgentHighMins: [Double]
public let alarmHigh: Bool
public let alarmHighMins: [Double]
public let alarmLow: Bool
public let alarmLowMins: [Double]
public let alarmUrgentLow: Bool
public let alarmUrgentLowMins: [Double]
public let alarmWarnMins: [Double]
public let alarmTimeagoWarn: Bool
public var alarmTimeagoWarnMins: Double = 15
public let alarmTimeagoUrgent: Bool
public var alarmTimeagoUrgentMins: Double = 30
public var timeAgo: TimeAgoAlert {
return TimeAgoAlert(warn: alarmTimeagoWarn, warnMins: TimeInterval(alarmTimeagoWarnMins * 10), urgent: alarmTimeagoUrgent, urgentMins: TimeInterval(alarmTimeagoUrgentMins * 10))
}
public let thresholds: Thresholds
public let enable: [Plugin]
}
extension Settings {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
units = try values.decode(GlucoseUnit.self, forKey: .units)
showRawbg = try values.decode(RawBGMode.self, forKey: .showRawbg)
customTitle = try values.decode(String.self, forKey: .customTitle)
alarmUrgentHigh = try values.decode(Bool.self, forKey: .alarmUrgentHigh)
alarmUrgentHighMins = try values.decode([Double].self, forKey: .alarmUrgentHighMins)
alarmHigh = try values.decode(Bool.self, forKey: .alarmHigh)
alarmHighMins = try values.decode([Double].self, forKey: .alarmHighMins)
alarmLow = try values.decode(Bool.self, forKey: .alarmLow)
alarmLowMins = try values.decode([Double].self, forKey: .alarmLowMins)
alarmUrgentLow = try values.decode(Bool.self, forKey: .alarmUrgentLow)
alarmUrgentLowMins = try values.decode([Double].self, forKey: .alarmUrgentLowMins)
alarmWarnMins = try values.decode([Double].self, forKey: .alarmWarnMins)
alarmTimeagoWarn = try values.decode(Bool.self, forKey: .alarmTimeagoWarn)
alarmTimeagoUrgent = try values.decode(Bool.self, forKey: .alarmTimeagoUrgent)
do {
alarmTimeagoWarnMins = try values.decode(Double.self, forKey: .alarmTimeagoWarnMins) * 10
} catch {
alarmTimeagoWarnMins = 15
}
do {
alarmTimeagoUrgentMins = try values.decode(Double.self, forKey: .alarmTimeagoUrgentMins) * 10
} catch {
alarmTimeagoUrgentMins = 30
}
thresholds = try values.decode(Thresholds.self, forKey: .thresholds)
enable = try values.decode([Plugin].self, forKey: .enable)
}
}
extension Settings: Equatable {}
public func ==(lhs: Settings, rhs: Settings) -> Bool {
return lhs.units == rhs.units &&
lhs.customTitle == rhs.customTitle &&
lhs.alarms == rhs.alarms &&
lhs.timeAgo == rhs.timeAgo &&
lhs.enable == rhs.enable &&
lhs.thresholds == rhs.thresholds
}
public enum Plugin: String, Codable, CustomStringConvertible, RawRepresentable {
case careportal
case rawbg
case iob
case ar2
case treatmentnotify
case delta
case direction
case upbat
case errorcodes
case simplealarms
case pushover
case maker
case cob
case bwp
case cage
case basal
case profile
case timeago
case alexa
case bridge, bgnow, devicestatus, boluscalc, food, sage, iage, mmconnect, pump, openaps, loop, cors, bwpcage, bgi, unknown
public var description: String {
return self.rawValue
}
}
extension Plugin {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let type = try container.decode(String.self)
self = Plugin(rawValue: type) ?? .unknown
}
}
public enum GlucoseUnit: String, Codable, RawRepresentable, CustomStringConvertible {
case mgdl = "mg/dL"
case mmol = "mmol"
public init() {
self = .mgdl
}
public init(rawValue: String) {
switch rawValue {
case GlucoseUnit.mmol.rawValue, "mmol/L":
self = .mmol
default:
self = .mgdl
}
}
public var description: String {
switch self {
case .mgdl:
return "mg/dL"
case .mmol:
return "mmol/L"
}
}
public var descriptionShort: String {
switch self {
case .mgdl:
return "mg"
case .mmol:
return "mmol"
}
}
}
// Need to re-evaluate how we treat Glucose units and conversion within the app.
@available(iOS 10.0, *)
extension GlucoseUnit {
@available(watchOSApplicationExtension 3.0, *)
public var unit: UnitConcentrationMass {
switch self {
case .mgdl:
return .milligramsPerDeciliter
case .mmol:
return .millimolesPerLiter(withGramsPerMole: 0.01)
}
}
}
public enum RawBGMode: String, Codable, RawRepresentable, CustomStringConvertible {
case never = "never"
case always = "always"
case noise = "noise"
public init() {
self = .never
}
public init(rawValue: String) {
switch rawValue {
case RawBGMode.always.rawValue:
self = .always
case RawBGMode.noise.rawValue:
self = .noise
default:
self = .never
}
}
public var description: String {
return self.rawValue
}
}
public struct Thresholds: Codable, CustomStringConvertible {
public let bgHigh: Double
public let bgLow: Double
public let bgTargetBottom :Double
public let bgTargetTop :Double
public var description: String {
let dict = ["bgHigh": bgHigh, "bgLow": bgLow, "bgTargetBottom": bgTargetBottom, "bgTargetTop": bgTargetTop]
return dict.description
}
public init() {
self.bgHigh = 300
self.bgLow = 60
self.bgTargetBottom = 70
self.bgTargetTop = 250
}
public init(bgHigh: Double? = 300, bgLow: Double? = 60, bgTargetBottom: Double? = 70, bgTargetTop: Double? = 250) {
guard let bgHigh = bgHigh, let bgLow = bgLow, let bgTargetTop = bgTargetTop, let bgTargetBottom = bgTargetBottom else {
self = Thresholds()
return
}
self.bgHigh = bgHigh
self.bgLow = bgLow
self.bgTargetBottom = bgTargetBottom
self.bgTargetTop = bgTargetTop
}
}
extension Thresholds: ColorBoundable {
public var bottom: Double { return self.bgLow }
public var targetBottom: Double { return self.bgTargetBottom }
public var targetTop: Double { return self.bgTargetTop }
public var top: Double { return self.bgHigh }
}
extension Thresholds: Equatable {}
public func ==(lhs: Thresholds, rhs: Thresholds) -> Bool {
return lhs.bottom == rhs.bottom &&
lhs.targetBottom == rhs.targetBottom &&
lhs.targetTop == rhs.targetTop &&
lhs.top == rhs.top
}
public struct Alarm: Codable, CustomStringConvertible {
public let urgentHigh: Bool
public let urgentHighMins: [Double]
public let high: Bool
public let highMins: [Double]
public let low: Bool
public let lowMins: [Double]
public let urgentLow: Bool
public let urgentLowMins: [Double]
public let warnMins: [Double]
public var description: String {
let dict = ["urgentHigh": urgentHigh, "urgentHighMins": urgentHighMins, "high": high, "highMins": highMins, "low": low, "lowMins": lowMins, "urgentLow": urgentLow, "urgentLowMins": urgentLowMins, "warnMins": warnMins] as [String : Any]
return dict.description
}
}
extension Alarm : Equatable {}
public func ==(lhs: Alarm, rhs: Alarm) -> Bool {
return lhs.urgentHigh == rhs.urgentHigh &&
lhs.urgentHighMins == rhs.urgentHighMins &&
lhs.high == rhs.high &&
lhs.highMins == rhs.highMins &&
lhs.low == rhs.low &&
lhs.lowMins == rhs.lowMins &&
lhs.urgentLow == rhs.urgentLow &&
lhs.urgentLowMins == rhs.urgentLowMins &&
lhs.warnMins == rhs.warnMins
}
public enum AlarmType: String, Codable, CustomStringConvertible {
case predict
case simple
init() {
self = .predict
}
public var description: String {
return self.rawValue
}
}
public struct TimeAgoAlert: Codable, CustomStringConvertible {
public let warn: Bool
public let warnMins: TimeInterval
public let urgent: Bool
public let urgentMins: TimeInterval
public var description: String {
let dict = ["warn": warn, "warnMins": warnMins, "urgent": urgent, "urgentMins": urgentMins] as [String : Any]
return dict.description
}
}
public extension TimeAgoAlert {
func isDataStaleWith(interval sinceNow: TimeInterval) -> (warn: Bool, urgent: Bool) {
return isDataStaleWith(interval: sinceNow, warn: self.warnMins, urgent: self.urgentMins)
}
private func isDataStaleWith(interval sinceNow: TimeInterval, warn: TimeInterval, urgent: TimeInterval, fallback: TimeInterval = TimeInterval(600)) -> (warn: Bool, urgent: Bool) {
let warnValue: TimeInterval = -max(fallback, warn)
let urgentValue: TimeInterval = -max(fallback, urgent)
let returnValue = (sinceNow < warnValue, sinceNow < urgentValue)
#if DEBUG
// print("\(__FUNCTION__): {sinceNow: \(sinceNow), warneValue: \(warnValue), urgentValue: \(urgentValue), fallback:\(-fallback), returning: \(returnValue)}")
#endif
return returnValue
}
}
extension TimeAgoAlert: Equatable {}
public func ==(lhs: TimeAgoAlert, rhs: TimeAgoAlert) -> Bool {
return lhs.warn == rhs.warn &&
lhs.warnMins == rhs.warnMins &&
lhs.urgent == rhs.urgent &&
lhs.urgentMins == rhs.urgentMins
}
| mit | 9692faa913034f48869e6067d33173fd | 31.931111 | 552 | 0.637965 | 4.118677 | false | false | false | false |
LearningSwift2/LearningApps | CounterApp/Counter-completed/Swift-Counter/ViewController.swift | 2 | 4461 | //
// ViewController.swift
// Swift-Counter
//
// Created by Ben Gohlke on 8/17/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
// The following variables and constants are called properties; they hold values that can be accessed from any method in this class
// This allows the app to set its current count when the app first loads.
// The line below simply generates a random number and then makes sure it falls within the bounds 1-100.
var currentCount: Int = Int(arc4random() % 100)
// These are called IBOutlets and are a kind of property; they connect elements in the storyboard with the code so you can update the UI elements from code.
@IBOutlet weak var countTextField: UITextField!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var stepper: UIStepper!
override func viewDidLoad()
{
super.viewDidLoad()
//
// 1. Once the currentCount variable is set, each of the UI elements on the screen need to be updated to match the currentCount.
// There is a method below that performs these steps. All you need to do perform a method call in the line below.
//
updateViewsWithCurrentCount()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateViewsWithCurrentCount()
{
// Here we are updating the different subviews in our main view with the current count.
//
// 2. The textfield needs to always show the current count. Fill in the blank below to set the text value of the textfield.
//
countTextField.text = "\(currentCount)"
//
// 3. Here we are setting the value property of the UISlider in the view. This causes the slider to set its handle to the
// appropriate position. Fill in the blank below.
//
slider.value = Float(currentCount)
//
// 4. We also need to update the value of the UIStepper. The user will not see any change to the stepper, but it needs to have a
// current value nonetheless, so when + or - is tapped, it will know what value to increment. Fill in the blanks below.
//
stepper.value = Double(currentCount)
}
// MARK: - Gesture recognizers
@IBAction func viewTapped(sender: UITapGestureRecognizer)
{
// This method is run whenever the user taps on the blank, white view (meaning they haven't tapped any of the controls on the
// view). It hides the keyboard if the user has edited the count textfield, and also updates the currentCount variable.
if countTextField.isFirstResponder()
{
countTextField.resignFirstResponder()
currentCount = Int(countTextField.text!)!
//
// 8. Hopefully you're seeing a pattern here. After we update the currentCount variable, what do we need to do next? Fill in
// the blank below.
//
updateViewsWithCurrentCount()
}
}
// MARK: - Action handlers
@IBAction func sliderValueChanged(sender: UISlider)
{
//
// 5. This method will run whenever the value of the slider is changed by the user. The "sender" object passed in as an argument
// to this method represents the slider from the view. We need to take the value of the slider and use it to update the
// value of our "currentCount" instance variable. Fill in the blank below.
//
currentCount = Int(sender.value)
//
// 6. Once we update the value of currentCount, we need to make sure all the UI elements on the screen are updated to keep
// everything in sync. We have previously done this (look in viewDidLoad). Fill in the blank below.
//
updateViewsWithCurrentCount()
}
@IBAction func stepperValueChanged(sender: UIStepper)
{
//
// 7. This method is run when the value of the stepper is changed by the user. If you've done steps 5 and 6 already, these steps
// should look pretty familiar, hint, hint. ;) Fill in the blanks below.
//
currentCount = Int(sender.value)
updateViewsWithCurrentCount()
}
} | apache-2.0 | e184f293b84bcd13e769c46b54cc2384 | 39.93578 | 160 | 0.644923 | 4.951165 | false | false | false | false |
Vostro162/VaporTelegram | Sources/App/ReplyKeyboardMarkup+Extensions.swift | 1 | 1693 | //
// ReplyKeyboardMarkup+Extensions.swift
// VaporTelegram
//
// Created by Marius Hartig on 11.05.17.
//
//
import Foundation
import Vapor
// MARK: - JSON
extension ReplyKeyboardMarkup: JSONInitializable {
public init(json: JSON) throws {
guard
let keyboardButtonJSON = json["keyboard"],
let keyboardButtons = try? KeyboardButton.create(arrayOfArrayJSON: keyboardButtonJSON)
else { throw VaporTelegramError.parsing }
self.keyboardButtons = keyboardButtons
/*
*
* Optionals
*
*/
if let resizeKeyboard = json["resize_keyboard"]?.bool {
self.resizeKeyboard = resizeKeyboard
} else {
self.resizeKeyboard = false
}
if let oneTimeKeyboard = json["one_time_keyboard"]?.bool {
self.oneTimeKeyboard = oneTimeKeyboard
} else {
self.oneTimeKeyboard = false
}
if let selective = json["selective"]?.bool {
self.selective = selective
} else {
self.selective = false
}
}
}
// MARK: - Node
extension ReplyKeyboardMarkup: NodeRepresentable {
public func makeNode(context: Context) throws -> Node {
let keyboardButtonsNodes = Array.elementsToNode(from: keyboardButtons)
let keyboardButtonsNode = try Node(node: keyboardButtonsNodes)
return try Node(node: [
"keyboard": keyboardButtonsNode,
"resize_keyboard": resizeKeyboard,
"one_timeKeyboard": oneTimeKeyboard,
"selective": selective
])
}
}
| mit | 2b0fd0358d60ed6e515178f1e74250e0 | 24.651515 | 98 | 0.578263 | 4.851003 | false | false | false | false |
apple/swift-nio-extras | Sources/NIOExtras/RequestResponseHandler.swift | 1 | 4884 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// ``RequestResponseHandler`` receives a `Request` alongside an `EventLoopPromise<Response>` from the `Channel`'s
/// outbound side. It will fulfill the promise with the `Response` once it's received from the `Channel`'s inbound
/// side.
///
/// ``RequestResponseHandler`` does support pipelining `Request`s and it will send them pipelined further down the
/// `Channel`. Should ``RequestResponseHandler`` receive an error from the `Channel`, it will fail all promises meant for
/// the outstanding `Reponse`s and close the `Channel`. All requests enqueued after an error occured will be immediately
/// failed with the first error the channel received.
///
/// ``RequestResponseHandler`` requires that the `Response`s arrive on `Channel` in the same order as the `Request`s
/// were submitted.
public final class RequestResponseHandler<Request, Response>: ChannelDuplexHandler {
/// `Response` is the type this class expects to receive inbound.
public typealias InboundIn = Response
/// Don't expect to pass anything on in-bound.
public typealias InboundOut = Never
/// Type this class expect to receive in an outbound direction.
public typealias OutboundIn = (Request, EventLoopPromise<Response>)
/// Type this class passes out.
public typealias OutboundOut = Request
private enum State {
case operational
case error(Error)
var isOperational: Bool {
switch self {
case .operational:
return true
case .error:
return false
}
}
}
private var state: State = .operational
private var promiseBuffer: CircularBuffer<EventLoopPromise<Response>>
/// Create a new ``RequestResponseHandler``.
///
/// - parameters:
/// - initialBufferCapacity: ``RequestResponseHandler`` saves the promises for all outstanding responses in a
/// buffer. `initialBufferCapacity` is the initial capacity for this buffer. You usually do not need to set
/// this parameter unless you intend to pipeline very deeply and don't want the buffer to resize.
public init(initialBufferCapacity: Int = 4) {
self.promiseBuffer = CircularBuffer(initialCapacity: initialBufferCapacity)
}
public func channelInactive(context: ChannelHandlerContext) {
switch self.state {
case .error:
// We failed any outstanding promises when we entered the error state and will fail any
// new promises in write.
assert(self.promiseBuffer.count == 0)
case .operational:
let promiseBuffer = self.promiseBuffer
self.promiseBuffer.removeAll()
promiseBuffer.forEach { promise in
promise.fail(NIOExtrasErrors.ClosedBeforeReceivingResponse())
}
}
context.fireChannelInactive()
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
guard self.state.isOperational else {
// we're in an error state, ignore further responses
assert(self.promiseBuffer.count == 0)
return
}
let response = self.unwrapInboundIn(data)
let promise = self.promiseBuffer.removeFirst()
promise.succeed(response)
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
guard self.state.isOperational else {
assert(self.promiseBuffer.count == 0)
return
}
self.state = .error(error)
let promiseBuffer = self.promiseBuffer
self.promiseBuffer.removeAll()
context.close(promise: nil)
promiseBuffer.forEach {
$0.fail(error)
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let (request, responsePromise) = self.unwrapOutboundIn(data)
switch self.state {
case .error(let error):
assert(self.promiseBuffer.count == 0)
responsePromise.fail(error)
promise?.fail(error)
case .operational:
self.promiseBuffer.append(responsePromise)
context.write(self.wrapOutboundOut(request), promise: promise)
}
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension RequestResponseHandler: Sendable {}
#endif
| apache-2.0 | 89d1a309b94819eb71d773a82b371fac | 37.761905 | 121 | 0.64312 | 4.978593 | false | false | false | false |
ECP-CANDLE/Supervisor | workflows/cp-leaveout/swift/junk.swift | 1 | 307 | app (void v) dummy(string parent, int stage, int id, void block)
{
"echo" ("parent='%3s'"%parent) ("stage="+stage) ("id="+id) ;
}
(void v) db_setup()
{
python_persist(----
import db_cplo_init
global db_file
db_file = 'cplo.db'
db_cplo_init.main(db_file)
----,
----
'OK'
----) =>
v = propagate();
}
| mit | 43a908100a04cefb3e27d4e692d9de82 | 16.055556 | 64 | 0.57329 | 2.456 | false | false | false | false |
gaoleegin/SwiftLanguage | GuidedTour-2.playground/Pages/Generics.xcplaygroundpage/Contents.swift | 1 | 1705 | //: ## Generics
//:
//: Write a name inside angle brackets to make a generic function or type.
//:
func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
repeatItem("knock", numberOfTimes:4)
///范型
func repateItem1<Item>(item:Item,numbersOfItems:Int) ->[Item] {
var result = [Item]()
for _ in 0..<numbersOfItems{
result.append(item)
}
return result
}
//: You can make generic forms of functions and methods, as well as classes, enumerations, and structures.
//:
// Reimplement the Swift standard library's optional type
enum OptionalValue<Wrapped> {
case None
case Some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
//: Use `where` after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.
//:
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
//: > **Experiment**:
//: > Modify the `anyCommonElements(_:_:)` function to make a function that returns an array of the elements that any two sequences have in common.
//:
//: Writing `<T: Equatable>` is the same as writing `<T where T: Equatable>`.
//:
//: [Previous](@previous)
| apache-2.0 | 475507bcdd6e3c50068842a28a2e9974 | 29.890909 | 219 | 0.658034 | 3.896789 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome | Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Merge.swift | 2 | 8963 | //
// Merge.swift
// Rx
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// sequential
class Merge_Iter<O: ObserverType> : ObserverType {
typealias Element = O.Element
typealias DisposeKey = Bag<Disposable>.KeyType
let parent: Merge_<O>
let disposeKey: DisposeKey
init(parent: Merge_<O>, disposeKey: DisposeKey) {
self.parent = parent
self.disposeKey = disposeKey
}
func on(event: Event<Element>) {
switch event {
case .Next:
parent.lock.performLocked {
trySend(parent.observer, event)
}
case .Error:
parent.lock.performLocked {
trySend(parent.observer, event)
self.parent.dispose()
}
case .Completed:
let group = parent.mergeState.group
group.removeDisposable(disposeKey)
self.parent.lock.performLocked {
let state = parent.mergeState
if state.stopped && state.group.count == 1 {
trySendCompleted(parent.observer)
self.parent.dispose()
}
}
}
}
}
class Merge_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = Observable<O.Element>
typealias Parent = Merge<O.Element>
typealias MergeState = (
stopped: Bool,
group: CompositeDisposable,
sourceSubscription: SingleAssignmentDisposable
)
let parent: Parent
var lock = NSRecursiveLock()
var mergeState: MergeState = (
stopped: false,
group: CompositeDisposable(),
sourceSubscription: SingleAssignmentDisposable()
)
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
let state = self.mergeState
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let state = self.mergeState
state.group.addDisposable(state.sourceSubscription)
let disposable = self.parent.sources.subscribe(self)
state.sourceSubscription.setDisposable(disposable)
return state.group
}
func on(event: Event<Element>) {
switch event {
case .Next(let boxedValue):
let value = boxedValue.value
let innerSubscription = SingleAssignmentDisposable()
let maybeKey = mergeState.group.addDisposable(innerSubscription)
if let key = maybeKey {
let observer = Merge_Iter(parent: self, disposeKey: key)
let disposable = value.subscribe(observer)
innerSubscription.setDisposable(disposable)
}
case .Error(let error):
lock.performLocked {
trySendError(observer, error)
self.dispose()
}
case .Completed:
lock.performLocked {
let mergeState = self.mergeState
let group = mergeState.group
self.mergeState.stopped = true
if group.count == 1 {
trySendCompleted(observer)
self.dispose()
}
else {
mergeState.sourceSubscription.dispose()
}
}
}
}
}
// concurrent
class Merge_ConcurrentIter<O: ObserverType> : ObserverType {
typealias Element = O.Element
typealias DisposeKey = Bag<Disposable>.KeyType
typealias Parent = Merge_Concurrent<O>
let parent: Parent
let disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
self.parent = parent
self.disposeKey = disposeKey
}
func on(event: Event<Element>) {
switch event {
case .Next:
parent.lock.performLocked {
trySend(parent.observer, event)
}
case .Error:
parent.lock.performLocked {
trySend(parent.observer, event)
self.parent.dispose()
}
case .Completed:
let mergeState = parent.mergeState
mergeState.group.removeDisposable(disposeKey)
parent.lock.performLocked {
if mergeState.queue.value.count > 0 {
let s = mergeState.queue.value.dequeue()
self.parent.subscribe(s, group: mergeState.group)
}
else {
parent.mergeState.activeCount = mergeState.activeCount - 1
if mergeState.stopped && mergeState.activeCount == 0 {
trySendCompleted(parent.observer)
self.parent.dispose()
}
}
}
}
}
}
class Merge_Concurrent<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = Observable<O.Element>
typealias Parent = Merge<O.Element>
typealias QueueType = Queue<Observable<O.Element>>
typealias MergeState = (
stopped: Bool,
queue: RxMutableBox<QueueType>,
sourceSubscription: SingleAssignmentDisposable,
group: CompositeDisposable,
activeCount: Int
)
let parent: Parent
var lock = NSRecursiveLock()
var mergeState: MergeState = (
stopped: false,
queue: RxMutableBox(Queue(capacity: 2)),
sourceSubscription: SingleAssignmentDisposable(),
group: CompositeDisposable(),
activeCount: 0
)
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
let state = self.mergeState
_ = state.group.addDisposable(state.sourceSubscription)
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let state = self.mergeState
state.group.addDisposable(state.sourceSubscription)
let disposable = self.parent.sources.subscribe(self)
state.sourceSubscription.setDisposable(disposable)
return state.group
}
func subscribe(innerSource: Element, group: CompositeDisposable) {
let subscription = SingleAssignmentDisposable()
let key = group.addDisposable(subscription)
if let key = key {
let observer = Merge_ConcurrentIter(parent: self, disposeKey: key)
let disposable = innerSource.subscribe(observer)
subscription.setDisposable(disposable)
}
}
func on(event: Event<Element>) {
switch event {
case .Next(let boxedValue):
let value = boxedValue.value
let subscribe = lock.calculateLocked { () -> Bool in
let mergeState = self.mergeState
if mergeState.activeCount < self.parent.maxConcurrent {
self.mergeState.activeCount += 1
return true
}
else {
mergeState.queue.value.enqueue(value)
return false
}
}
if subscribe {
self.subscribe(value, group: mergeState.group)
}
case .Error(let error):
lock.performLocked {
trySendError(observer, error)
self.dispose()
}
case .Completed:
lock.performLocked {
let mergeState = self.mergeState
let group = mergeState.group
if mergeState.activeCount == 0 {
trySendCompleted(observer)
self.dispose()
}
else {
mergeState.sourceSubscription.dispose()
}
self.mergeState.stopped = true
}
}
}
}
class Merge<Element> : Producer<Element> {
let sources: Observable<Observable<Element>>
let maxConcurrent: Int
init(sources: Observable<Observable<Element>>, maxConcurrent: Int) {
self.sources = sources
self.maxConcurrent = maxConcurrent
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
if maxConcurrent > 0 {
let sink = Merge_Concurrent(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
else {
let sink = Merge_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
}
} | mit | 5488dc8192231589a3e4e441de1f52c5 | 29.181818 | 145 | 0.542229 | 5.399398 | false | false | false | false |
Eonil/SQLite3 | Sources/Common.swift | 2 | 1283 | //
// Common.swift
// EonilSQLite3
//
// Created by Hoon H. on 10/31/14.
//
//
import Foundation
func combine <K,V> (keys:[K], values:[V]) -> [K:V] {
precondition(keys.count == values.count)
var d = [:] as [K:V]
for i in 0..<keys.count {
d[keys[i]] = values[i]
}
return d
}
func collect <T:GeneratorType> (g:T) -> [T.Element] {
var c = [] as [T.Element]
var g2 = g
while let m = g2.next() {
c.append(m)
}
return c
}
//func collect <T:SequenceType> (c:T) -> [T.Generator.Element] {
// return collect(c.generate())
//}
func linkWeakly <T where T: AnyObject> (target:T) -> ()->T? {
weak var value = target as T?
return {
return value
}
}
/// MARK:
/// MARK: Operators
infix operator >>>> {
}
//infix operator >>>>? {
//
//}
//infix operator >>>>! {
//
//}
internal func >>>> <T,U> (value:T, function:T->U) -> U {
return function(value)
}
//func >>>>? <T,U> (value:T?, function:T->U) -> U? {
// return value == nil ? nil : function(value!)
//}
//func >>>>! <T,U> (value:T!, function:T->U) -> U {
// precondition(value != nil, "Supplied value `T` shouldn't be `nil`.")
// return function(value!)
//}
infix operator ||| {
}
internal func ||| <T> (value:T?, substitude:T) -> T {
return value == nil ? substitude : value!
}
| mit | 939759f99b88fe5cc0cde7784de1de2f | 11.83 | 71 | 0.55417 | 2.500975 | false | false | false | false |
tkester/swift-algorithm-club | Huffman Coding/Huffman.playground/Contents.swift | 1 | 752 | //: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import Foundation
let s1 = "so much words wow many compression"
if let originalData = s1.data(using: .utf8) {
print(originalData.count)
let huffman1 = Huffman()
let compressedData = huffman1.compressData(data: originalData as NSData)
print(compressedData.length)
let frequencyTable = huffman1.frequencyTable()
//print(frequencyTable)
let huffman2 = Huffman()
let decompressedData = huffman2.decompressData(data: compressedData, frequencyTable: frequencyTable)
print(decompressedData.length)
let s2 = String(data: decompressedData as Data, encoding: .utf8)!
print(s2)
assert(s1 == s2)
}
| mit | 2d5bf39dc4061ad3acf82981dfe8dbc7 | 25.857143 | 102 | 0.739362 | 3.54717 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Importers/OpenTracingShim/SpanContextShimTable.swift | 1 | 1792 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryApi
public class SpanContextShimTable {
private let lock = ReadWriteLock()
private var shimsMap = [SpanContext: SpanContextShim]()
public func setBaggageItem(spanShim: SpanShim, key: String, value: String) {
lock.withWriterLockVoid {
var contextShim = shimsMap[spanShim.span.context]
if contextShim == nil {
contextShim = SpanContextShim(spanShim: spanShim)
}
contextShim = contextShim?.newWith(key: key, value: value)
shimsMap[spanShim.span.context] = contextShim
}
}
public func getBaggageItem(spanShim: SpanShim, key: String) -> String? {
lock.withReaderLock {
let contextShim = shimsMap[spanShim.span.context]
return contextShim?.getBaggageItem(key: key)
}
}
public func get(spanShim: SpanShim) -> SpanContextShim? {
lock.withReaderLock {
shimsMap[spanShim.span.context]
}
}
public func create(spanShim: SpanShim) -> SpanContextShim {
return create(spanShim: spanShim, distContext: spanShim.telemetryInfo.emptyBaggage)
}
@discardableResult public func create(spanShim: SpanShim, distContext: Baggage?) -> SpanContextShim {
lock.withWriterLock {
var contextShim = shimsMap[spanShim.span.context]
if contextShim != nil {
return contextShim!
}
contextShim = SpanContextShim(telemetryInfo: spanShim.telemetryInfo, context: spanShim.span.context, baggage: distContext)
shimsMap[spanShim.span.context] = contextShim
return contextShim!
}
}
}
| apache-2.0 | ca71c4371267e6cbf59d4f411bbe079b | 32.185185 | 134 | 0.645647 | 4.246445 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/ChatLeftShareFeed/LeftShareFeedCell.swift | 1 | 5583 | //
// LeftShareFeedCell.swift
// Yep
//
// Created by ChaiYixiao on 4/21/16.
// Copyright © 2016 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class LeftShareFeedCell: ChatBaseCell {
var mediaView:FeedMediaView?
lazy var feedKindImageView: UIImageView = {
let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 42, height: 42))
return imageView
}()
var topLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
label.text = NSLocalizedString("给你分享一个话题:", comment: "")
return label
}()
var accessoryView: UIImageView = {
let image = UIImage.yep_iconAccessoryMini
let imageView = UIImageView(image: image)
return imageView
}()
var detailLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
label.numberOfLines = 1
return label
}()
var conversation: Conversation!
override func prepareForReuse() {
mediaView?.clearImages()
feedKindImageView.image = nil
topLabel.text = ""
detailLabel.text = ""
}
let cellBackgroundImageView: UIImageView = {
let imageView = UIImageView(image: UIImage.yep_shareFeedBubbleLeft)
imageView.userInteractionEnabled = true
return imageView
}()
lazy var loadingProgressView: MessageLoadingProgressView = {
let view = MessageLoadingProgressView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
view.hidden = true
view.backgroundColor = UIColor.clearColor()
return view
}()
typealias MediaTapAction = () -> Void
var mediaTapAction: MediaTapAction?
func makeUI() {
if let feedKindImage = makeFeedKindImage() {
feedKindImageView.image = feedKindImage
contentView.addSubview(feedKindImageView)
}
let avatarRadius = YepConfig.chatCellAvatarSize() / 2
let topOffset: CGFloat = 0
avatarImageView.center = CGPoint(x: YepConfig.chatCellGapBetweenWallAndAvatar() + avatarRadius, y: avatarRadius + topOffset)
}
private func makeFeedKindImage() -> UIImage? {
if let feed = conversation.withGroup?.withFeed, let feedKind = FeedKind(rawValue:feed.kind) {
switch feedKind {
case .DribbbleShot:
return UIImage.yep_iconDribbble
case .GithubRepo:
return UIImage.yep_iconGithub
case .Image:
var discoveredAttachments = [DiscoveredAttachment]()
feed.attachments.forEach({ (attachment) in
let discoveredAttachment = DiscoveredAttachment(metadata: attachment.metadata, URLString: attachment.URLString, image: nil)
discoveredAttachments.append(discoveredAttachment)
})
mediaView?.setImagesWithAttachments(discoveredAttachments)
if let mediaView = self.mediaView {
mediaView.subviews.forEach { (view) in
view.userInteractionEnabled = true
}
mediaView.frame = CGRect(x: 10, y: 10, width: 42, height: 42)
contentView.addSubview(mediaView)
}
break
case .Location:
return UIImage.yep_iconPinShadow
default :
return UIImage.yep_iconTopicText
}
}
return nil
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(cellBackgroundImageView)
contentView.addSubview(loadingProgressView)
let tap = UITapGestureRecognizer(target: self, action: #selector(ChatLeftImageCell.tapMediaView))
cellBackgroundImageView.addGestureRecognizer(tap)
UIView.performWithoutAnimation { [weak self] in
self?.makeUI()
}
prepareForMenuAction = { otherGesturesEnabled in
tap.enabled = otherGesturesEnabled
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tapMediaView() {
mediaTapAction?()
}
var loadingProgress: Double = 0 {
willSet {
if newValue == 1.0 {
loadingProgressView.hidden = true
} else {
loadingProgressView.progress = newValue
loadingProgressView.hidden = false
}
}
}
func loadingWithProgress(progress: Double, mediaView: FeedMediaView?) {
}
func configureWithMessage(message: Message, collectionView: UICollectionView, indexPath: NSIndexPath, mediaTapAction: MediaTapAction?) {
self.user = message.fromFriend
self.mediaTapAction = mediaTapAction
//var topOffset: CGFloat = 0
UIView.performWithoutAnimation { [weak self] in
self?.makeUI()
}
if let sender = message.fromFriend {
let userAvatar = UserAvatar(userID: sender.userID, avatarURLString: sender.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
}
loadingProgress = 0
}
}
| mit | 8e5cd06a55a43d319009dbc46bc59673 | 30.794286 | 143 | 0.592559 | 5.283951 | false | false | false | false |
emilstahl/swift | test/Constraints/members.swift | 10 | 14370 | // RUN: %target-parse-verify-swift
import Swift
////
// Members of structs
////
struct X {
func f0(i: Int) -> X { }
func f1(i: Int) { }
mutating func f1(f: Float) { }
func f2<T>(x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
x.f0(i)
x.f0(i).f1(i)
g0(X.f1)
x.f0(x.f2(1))
x.f0(1).f2(i)
yf.f0(1)
yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(x: Int)(y: Int) -> Int { return x + y } // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}}
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(y: 1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
var format : String
format._splitFirstIf({ $0.isASCII() })
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(x: Int) {}
func curried(x: Int)(y: Int) {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(y: 1)
// Member of enum Type
func enumMetatypeMember(opt: Int?) {
opt.None // expected-error{{static member 'None' cannot be used on instance of type 'Int?'}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In { // expected-error{{nested in generic type}}
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Members of archetypes
////
func id<T>(t: T) -> T { return t }
func doGetLogicValue<T : BooleanType>(t: T) {
t.boolValue
}
protocol P {
init()
func bar(x: Int)
mutating func mut(x: Int)
static func tum()
}
extension P {
func returnSelfInstance() -> Self {
return self
}
func returnSelfOptionalInstance(b: Bool) -> Self? {
return b ? self : nil
}
func returnSelfIUOInstance(b: Bool) -> Self! {
return b ? self : nil
}
static func returnSelfStatic() -> Self {
return Self()
}
static func returnSelfOptionalStatic(b: Bool) -> Self? {
return b ? Self() : nil
}
static func returnSelfIUOStatic(b: Bool) -> Self! {
return b ? Self() : nil
}
}
protocol ClassP : class {
func bas(x: Int)
}
func generic<T: P>(t: T) {
var t = t
// Instance member of archetype
let _: Int -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: T -> Int -> () = id(T.bar)
let _: Int -> () = id(T.bar(t))
_ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
// Instance member of extension returning Self)
let _: T -> () -> T = id(T.returnSelfInstance)
let _: () -> T = id(T.returnSelfInstance(t))
let _: T = id(T.returnSelfInstance(t)())
let _: () -> T = id(t.returnSelfInstance)
let _: T = id(t.returnSelfInstance())
let _: T -> Bool -> T? = id(T.returnSelfOptionalInstance)
let _: Bool -> T? = id(T.returnSelfOptionalInstance(t))
let _: T? = id(T.returnSelfOptionalInstance(t)(false))
let _: Bool -> T? = id(t.returnSelfOptionalInstance)
let _: T? = id(t.returnSelfOptionalInstance(true))
let _: T -> Bool -> T! = id(T.returnSelfIUOInstance)
let _: Bool -> T! = id(T.returnSelfIUOInstance(t))
let _: T! = id(T.returnSelfIUOInstance(t)(true))
let _: Bool -> T! = id(t.returnSelfIUOInstance)
let _: T! = id(t.returnSelfIUOInstance(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: Bool -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: Bool -> T! = id(T.returnSelfIUOStatic)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func genericClassP<T: ClassP>(t: T) {
// Instance member of archetype)
let _: Int -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: T -> Int -> () = id(T.bas)
let _: Int -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
////
// Members of existentials
////
func existential(p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}}
// Instance member of existential)
let _: Int -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(p.dynamicType.tum)
// Instance member of extension returning Self
let _: () -> P = id(p.returnSelfInstance)
let _: P = id(p.returnSelfInstance())
let _: P? = id(p.returnSelfOptionalInstance(true))
let _: P! = id(p.returnSelfIUOInstance(true))
}
func staticExistential(p: P.Type, pp: P.Protocol) {
let ppp: P = p.init()
_ = pp.init() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: P -> Int -> () = P.bar
let _: Int -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: P -> Int -> () = pp.bar
let _: Int -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
// Static member of extension returning Self)
let _: () -> P = id(p.returnSelfStatic)
let _: P = id(p.returnSelfStatic())
let _: Bool -> P? = id(p.returnSelfOptionalStatic)
let _: P? = id(p.returnSelfOptionalStatic(false))
let _: Bool -> P! = id(p.returnSelfIUOStatic)
let _: P! = id(p.returnSelfIUOStatic(true))
}
func existentialClassP(p: ClassP) {
// Instance member of existential)
let _: Int -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: ClassP -> Int -> () = id(ClassP.bas)
let _: Int -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(c: Scalar) -> Self
}
protocol Functional {
func apply(v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(f: Functional)(v1: Vector, v2: Vector) -> Scalar // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}}
}
// Make sure existential is closed early when we partially apply
func wrap<T>(t: T) -> T {
return t
}
func exercise(c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: Scalar -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(c: Copyable) -> Copyable {
return c.copy().copy()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines a Generator type alias
struct S22490787 {
typealias Generator = AnyGenerator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'SequenceType'}}
}
}
| apache-2.0 | 6e370d368f8d0c7dc12dbd60e917cc4f | 25.710037 | 169 | 0.65588 | 3.565757 | false | false | false | false |
material-components/material-components-ios | components/Dialogs/examples/DialogsAccessoryExampleViewController.swift | 2 | 13113 | // Copyright 2019-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialCollections
import MaterialComponents.MaterialDialogs
import MaterialComponents.MaterialDialogs_Theming
import MaterialComponents.MaterialTextControls_FilledTextFields
import MaterialComponents.MaterialTextControls_FilledTextFieldsTheming
import MaterialComponents.MaterialContainerScheme
import MaterialComponents.MaterialTypographyScheme
class DialogsAccessoryExampleViewController: MDCCollectionViewController {
@objc lazy var containerScheme: MDCContainerScheming = {
let scheme = MDCContainerScheme()
scheme.colorScheme = MDCSemanticColorScheme(defaults: .material201907)
scheme.typographyScheme = MDCTypographyScheme(defaults: .material201902)
return scheme
}()
let kReusableIdentifierItem = "customCell"
var menu: [String] = []
var handler: MDCActionHandler = { action in
print(action.title ?? "Some Action")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = containerScheme.colorScheme.backgroundColor
loadCollectionView(menu: [
"Material Filled Text Field",
"UI Text Field",
"Confirmation Dialog",
"Autolayout in Custom View",
])
}
func loadCollectionView(menu: [String]) {
self.collectionView?.register(
MDCCollectionViewTextCell.self, forCellWithReuseIdentifier: kReusableIdentifierItem)
self.menu = menu
}
override func collectionView(
_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath
) {
guard let alert = performActionFor(row: indexPath.row) else { return }
self.present(alert, animated: true, completion: nil)
}
private func performActionFor(row: Int) -> MDCAlertController? {
switch row {
case 0:
return performMDCTextField()
case 1:
return performUITextField()
case 2:
return performConfirmationDialog()
case 3:
return performCustomLabelWithButton()
default:
print("No row is selected")
return nil
}
}
// Demonstrate a custom view with MDCFilledTextField being assigned to the accessoryView API.
// This example also demonstrates the use of autolayout in custom views.
func performMDCTextField() -> MDCAlertController {
let alert = MDCAlertController(title: "Rename File", message: nil)
alert.addAction(MDCAlertAction(title: "Rename", emphasis: .medium, handler: handler))
alert.addAction(MDCAlertAction(title: "Cancel", emphasis: .low, handler: handler))
if let alertView = alert.view as? MDCAlertControllerView {
alertView.contentInsets.bottom = 16.0
}
let view = UIView(frame: CGRect.zero)
let label = newLabel(text: "OLD_FILE.PNG will be renamed:")
let namefield = MDCFilledTextField()
namefield.label.text = "New File Name"
namefield.placeholder = "Enter a new file name"
namefield.labelBehavior = MDCTextControlLabelBehavior.floats
namefield.clearButtonMode = UITextField.ViewMode.whileEditing
namefield.leadingAssistiveLabel.text = "An optional assistive message"
namefield.applyTheme(withScheme: containerScheme)
// Enable dynamic type.
namefield.adjustsFontForContentSizeCategory = true
namefield.font = UIFont.preferredFont(
forTextStyle: .body, compatibleWith: namefield.traitCollection)
namefield.leadingAssistiveLabel.font = UIFont.preferredFont(
forTextStyle: .caption2, compatibleWith: namefield.traitCollection)
label.translatesAutoresizingMaskIntoConstraints = false
namefield.translatesAutoresizingMaskIntoConstraints = false
view.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(label)
view.addSubview(namefield)
label.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: namefield.topAnchor, constant: -10).isActive = true
namefield.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
namefield.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
namefield.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
alert.accessoryView = view
alert.adjustsFontForContentSizeCategory = true // Enable dynamic type.
alert.applyTheme(withScheme: self.containerScheme)
return alert
}
func performUITextField() -> MDCAlertController {
let alert = MDCAlertController(title: "This is a title", message: "This is a message")
let textField = UITextField()
textField.placeholder = "This is a text field"
alert.accessoryView = textField
alert.addAction(MDCAlertAction(title: "Dismiss", emphasis: .medium, handler: handler))
alert.adjustsFontForContentSizeCategory = true // Enable dynamic type.
alert.applyTheme(withScheme: self.containerScheme)
return alert
}
// Demonstrate a confirmation dialog with a custom table view.
func performConfirmationDialog() -> MDCAlertController {
let alert = MDCAlertController(title: "Phone ringtone", message: "Please select a ringtone:")
alert.addAction(MDCAlertAction(title: "OK", handler: handler))
alert.addAction(MDCAlertAction(title: "Cancel", handler: handler))
alert.accessoryView = ExampleTableSeparatorView()
if let alertView = alert.view as? MDCAlertControllerView {
// Zero bottom-inset ensuring the bottom separator appears immediately above the actions.
alertView.contentInsets.bottom = 0
// Decreasing vertical margin between the accessory view and the message
alertView.accessoryViewVerticalInset = 8
// Aligning the accessory view with the dialog's edge by removing all horizontal insets.
alertView.accessoryViewHorizontalInset = -alertView.contentInsets.left
}
alert.adjustsFontForContentSizeCategory = true // Enable dynamic type.
alert.applyTheme(withScheme: self.containerScheme)
return alert
}
// Demonstrate a custom accessory view with auto layout, presenting a label and a button.
func performCustomLabelWithButton() -> MDCAlertController {
let alert = MDCAlertController(title: "Title", message: nil)
alert.addAction(MDCAlertAction(title: "Dismiss", emphasis: .medium, handler: handler))
let view = UIView(frame: CGRect.zero)
let label = newLabel(text: "Your storage is full. Your storage is full.")
let button = MDCButton()
button.setTitle("Learn More", for: UIControl.State.normal)
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 8)
button.applyTextTheme(withScheme: containerScheme)
label.translatesAutoresizingMaskIntoConstraints = false
button.translatesAutoresizingMaskIntoConstraints = false
view.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(label)
view.addSubview(button)
label.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: button.topAnchor).isActive = true
button.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
button.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
alert.accessoryView = view
alert.adjustsFontForContentSizeCategory = true // Enable dynamic type.
alert.applyTheme(withScheme: self.containerScheme)
return alert
}
func newLabel(text: String) -> UILabel {
let label = UILabel()
label.textColor = containerScheme.colorScheme.onSurfaceColor
label.font = containerScheme.typographyScheme.subtitle2
label.text = text
label.numberOfLines = 0
return label
}
}
// MDCCollectionViewController Data Source
extension DialogsAccessoryExampleViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(
_ collectionView: UICollectionView, numberOfItemsInSection section: Int
) -> Int {
return menu.count
}
override func collectionView(
_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: kReusableIdentifierItem,
for: indexPath)
guard let customCell = cell as? MDCCollectionViewTextCell else { return cell }
customCell.isAccessibilityElement = true
customCell.accessibilityTraits = .button
let cellTitle = menu[indexPath.row]
customCell.accessibilityLabel = cellTitle
customCell.textLabel?.text = cellTitle
return customCell
}
}
// MARK: Catalog by convention
extension DialogsAccessoryExampleViewController {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Dialogs", "Dialog With Accessory View"],
"primaryDemo": false,
"presentable": true,
]
}
}
// MARK: Snapshot Testing by Convention
extension DialogsAccessoryExampleViewController {
func resetTests() {
if presentedViewController != nil {
dismiss(animated: false)
}
}
@objc func testTextField() {
resetTests()
self.present(performUITextField(), animated: false, completion: nil)
}
@objc func testMDCTextField() {
resetTests()
self.present(performMDCTextField(), animated: false, completion: nil)
}
@objc func testCustomLabelWithButton() {
resetTests()
self.present(performCustomLabelWithButton(), animated: false, completion: nil)
}
@objc func testConfirmationDialog() {
resetTests()
self.present(performConfirmationDialog(), animated: false, completion: nil)
}
}
// An example view with a tableview and a bottom separator.
class ExampleTableSeparatorView: UIView, UITableViewDataSource {
let ringtones = ["Callisto", "Luna", "Phobos", "Dione"]
let tableView: UITableView = {
let tv = AutoSizedTableView()
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tv.separatorStyle = .none
tv.rowHeight = 40
return tv
}()
init() {
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
tableView.dataSource = self
tableView.alwaysBounceVertical = false
addSubview(tableView)
let separator = UIView(frame: .zero)
separator.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
addSubview(separator)
tableView.translatesAutoresizingMaskIntoConstraints = false
separator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(lessThanOrEqualTo: self.topAnchor),
tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
separator.topAnchor.constraint(equalTo: tableView.bottomAnchor),
separator.leadingAnchor.constraint(equalTo: self.leadingAnchor),
separator.trailingAnchor.constraint(equalTo: self.trailingAnchor),
separator.bottomAnchor.constraint(equalTo: self.bottomAnchor),
separator.heightAnchor.constraint(equalToConstant: 2),
])
tableView.reloadData()
let currentRingtone = IndexPath(row: 1, section: 0)
tableView.selectRow(at: currentRingtone, animated: false, scrollPosition: .top)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ringtones.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = ringtones[indexPath.row]
cell.indentationLevel = 1
return cell
}
}
// A tableview with intrinsic size that matches its content size.
final class AutoSizedTableView: UITableView {
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
| apache-2.0 | 2ce782bcd41cc9ee51e4b23e0a504a62 | 35.024725 | 98 | 0.747274 | 4.90756 | false | false | false | false |
pyconjp/pyconjp-ios | PyConJP/ViewController/Base/ZoomableImageViewController.swift | 1 | 2949 | //
// ZoomableImageViewController.swift
// PyConJP
//
// Created by Yutaro Muta on 9/12/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
class ZoomableImageViewController: UIViewController, UIScrollViewDelegate, StoryboardIdentifiable {
@IBOutlet weak var baseScrollView: UIScrollView?
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var closeButton: UIButton!
private var isCompletedLayoutSubviews = false
static func build() -> ZoomableImageViewController {
let zoomableImageViewController: ZoomableImageViewController = UIStoryboard(storyboard: .main).instantiateViewController()
return zoomableImageViewController
}
override var prefersStatusBarHidden: Bool {
return isCompletedLayoutSubviews
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
override func viewDidLoad() {
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ZoomableImageViewController.doubleTap(_:)))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ZoomableImageViewController.singleTap(_:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.require(toFail: doubleTapGesture)
view.addGestureRecognizer(singleTapGesture)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
isCompletedLayoutSubviews = true
self.setNeedsStatusBarAppearanceUpdate()
toggleToolBarHiddenWithAnimation(false)
}
private func toggleToolBarHiddenWithAnimation(_ toHidden: Bool) {
if toHidden {
UIView.animate(withDuration: 0.2, animations: {
self.closeButton.alpha = 0
}, completion: { _ in
self.closeButton.isHidden = true
})
} else {
closeButton.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.closeButton.alpha = 1
})
}
}
// MARK: - Scroll View Delegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
closeButton.isHidden = true
}
@objc func singleTap(_ gesture: UITapGestureRecognizer) {
toggleToolBarHiddenWithAnimation(!closeButton.isHidden)
}
@objc func doubleTap(_ gesture: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.2, animations: {
self.baseScrollView?.zoomScale = 1
})
}
@IBAction func onClose(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| mit | 0961d9b688513e4daa9dd0d96fb3c52a | 32.123596 | 130 | 0.665875 | 5.724272 | false | false | false | false |
zskyfly/twitter | twitter/TweetDetailViewController.swift | 1 | 2490 | //
// TweetDetailViewController.swift
// twitter
//
// Created by Zachary Matthews on 2/23/16.
// Copyright © 2016 zskyfly productions. All rights reserved.
//
import UIKit
class TweetDetailViewController: UIViewController {
@IBOutlet weak var likeCountLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var createdAtLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var userHandleLabel: UILabel!
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var replyButton: UIButton!
var tweet: Tweet!
var likeInFlight: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
ImageHelper.stylizeUserImageView(self.userImageView)
if let user = self.tweet.user {
ImageHelper.setImageForView(user.profileUrl, placeholder: ImageHelper.defaultBackgroundImage, imageView: self.userImageView, success: nil, failure: nil)
userNameLabel.text = user.name as? String
userHandleLabel.text = "@\(user.screenName!)"
}
if let text = self.tweet.text {
tweetTextLabel.text = text
}
createdAtLabel.text = tweet.getCreatedAtForDetail()
retweetCountLabel.text = "\(self.tweet.retweetCount)"
likeCountLabel.text = "\(self.tweet.favoriteCount)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let identifier = segue.identifier!
switch identifier {
case "ReplySegue":
let vc = segue.destinationViewController as! NewTweetViewController
vc.user = User._currentUser
vc.replyTweet = tweet
default:
return
}
}
@IBAction func onTapLike(sender: AnyObject) {
let statusId = self.tweet.idStr!
if !self.likeInFlight {
// self.toggleLikeButton()
TwitterClient.sharedInstance.favoriteCreate(statusId, success: { (tweet: Tweet) -> () in
print("favorite success")
}) { (error: NSError) -> () in
print("\(error.localizedDescription)")
}
}
}
}
| apache-2.0 | a54d5a8ac46ca4c04a173728a16c1c44 | 32.635135 | 164 | 0.647248 | 4.928713 | false | false | false | false |
ben-ng/swift | test/Parse/comment_operator.swift | 2 | 1859 | // RUN: %target-swift-frontend -typecheck -verify -module-name main %s
// Tests for interaction between comments & operators from SE-0037
// which defined comments to be whitespace for operator arity rules.
let foo: Bool! = true
// Used to be errors, should now work
let a = /* */!foo
_ = 1/**/+ 2
_ = 1 /**/+ 2
_ = 1 +/*hi*/2
// Used to work, should now be errors
// The actual error produced is probably not important.
// These are wrapped in functions to allow the parser to recover before the next test case.
func test1() { _ = foo/* */?.description } // expected-error {{expected ':' after '? ...' in ternary expression}}
func test2() { _ = foo/* */! } // expected-error {{expected expression after operator}}
func test3() { _ = 1/**/+2 } // expected-error {{consecutive statements on a line must be separated by ';'}} expected-error {{ambiguous use of operator '+'}}
func test4() { _ = 1+/**/2 } // expected-error {{'+' is not a postfix unary operator}} expected-error {{consecutive statements on a line must be separated by ';'}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
// Continue to be errors
func test5() { _ = !/* */foo } // expected-error {{unary operator cannot be separated from its operand}}
func test6() { _ = 1+/* */2 } // expected-error {{'+' is not a postfix unary operator}} expected-error {{consecutive statements on a line must be separated by ';'}} expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
// Continue to work
_ = foo!// this is dangerous
_ = 1 +/**/ 2
_ = 1 +/* hi */2
// Ensure built-in operators are properly tokenized.
_ =/**/2
_/**/= 2
typealias A = () ->/* */()
func test7(x: Int) { _ = x./* desc */ } // expected-error {{expected member name following '.'}}
| apache-2.0 | f265af15738cf471929e06c0c9573ff7 | 52.114286 | 261 | 0.626143 | 3.946921 | false | true | false | false |
hashemi/slox | slox/Class.swift | 1 | 2160 | //
// Class.swift
// slox
//
// Created by Ahmad Alhashemi on 2017-12-24.
// Copyright © 2017 Ahmad Alhashemi. All rights reserved.
//
struct Class {
class Superclass {
let superclass: Class?
init(_ superclass: Class?) {
self.superclass = superclass
}
}
let name: String
let superclass: Superclass
let methods: [String: UserFunction]
init(name: String, superclass: Class?, methods: [String: UserFunction]) {
self.name = name
self.superclass = Superclass(superclass)
self.methods = methods
}
func find(instance: Instance, method: String) -> UserFunction? {
if let boundMethod = methods[method]?.bind(instance) {
return boundMethod
}
if let superclass = superclass.superclass {
return superclass.find(instance: instance, method: method)
}
return nil
}
}
extension Class: CustomStringConvertible {
var description: String {
return name
}
}
extension Class: Callable {
var arity: Int { return methods["init"]?.arity ?? 0 }
func call(_ args: [LiteralValue]) throws -> LiteralValue {
let instance = Instance(class: self)
if let initializer = methods["init"] {
_ = try initializer.bind(instance).call(args)
}
return .instance(instance)
}
}
class Instance {
let klass: Class
var fields: [String: LiteralValue] = [:]
init(class klass: Class) {
self.klass = klass
}
func get(_ name: Token) throws -> LiteralValue {
if let value = fields[name.lexeme] {
return value
}
if let method = klass.find(instance: self, method: name.lexeme) {
return .function(method)
}
throw RuntimeError(name, "Undefined property '\(name.lexeme)'.")
}
func set(_ name: Token, _ value: LiteralValue) {
fields[name.lexeme] = value
}
}
extension Instance: CustomStringConvertible {
var description: String {
return "\(klass.name) instance"
}
}
| mit | f409f20c398055e3a844125e33067fad | 23.534091 | 77 | 0.576193 | 4.415133 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/Views/KeyboardImageButton.swift | 1 | 1746 | //
// KeyboardImageButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-03-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This button shows an image with a tap and long press action.
*/
public struct KeyboardImageButton: View {
/**
Create a keyboard image button that uses the `image` of
the provided `KeyboardAction`, if it has one.
*/
public init(
action: KeyboardAction,
tapAction: @escaping () -> Void = {},
longPressAction: @escaping () -> Void = {}) {
self.image = Image(uiImage: action.image)
self.tapAction = tapAction
self.longPressAction = longPressAction
}
/**
Create a keyboard image button with a custom `Image`.
*/
public init(
image: Image,
tapAction: @escaping () -> Void = {},
longPressAction: @escaping () -> Void = {}) {
self.image = image
self.tapAction = tapAction
self.longPressAction = longPressAction
}
private let image: Image
private let tapAction: () -> Void
private let longPressAction: () -> Void
public var body: some View {
image
.resizable()
.scaledToFit()
.onTapGesture(perform: tapAction)
.onLongPressGesture(perform: longPressAction)
.accessibility(addTraits: .isButton)
}
}
private extension KeyboardAction {
var image: UIImage {
switch self {
case .image(_, let imageName, _): return UIImage(named: imageName) ?? UIImage()
case .systemImage(_, let imageName, _): return UIImage(systemName: imageName) ?? UIImage()
default: return UIImage()
}
}
}
| mit | 49fba8b4ef06e0d56c3688725dac47b4 | 26.265625 | 98 | 0.595415 | 4.728997 | false | false | false | false |
auth0/Lock.swift | Lock/InfoBarView.swift | 1 | 3977 | // InfoBarView.swift
//
// Copyright (c) 2016 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
class InfoBarView: UIView {
weak var container: UIView?
weak var iconView: UIImageView?
weak var titleView: UILabel?
var title: String? {
get {
return self.titleView?.text
}
set {
self.titleView?.text = newValue
self.setNeedsUpdateConstraints()
}
}
var icon: UIImage? {
get {
return self.iconView?.image
}
set {
self.iconView?.image = newValue
}
}
convenience init() {
self.init(frame: CGRect.zero)
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.layoutHeader()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layoutHeader()
}
private func layoutHeader() {
let container = UIView()
let titleView = UILabel()
let iconView = UIImageView()
self.addSubview(container)
container.addSubview(titleView)
container.addSubview(iconView)
constraintEqual(anchor: container.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: container.bottomAnchor, toAnchor: self.bottomAnchor)
constraintEqual(anchor: container.topAnchor, toAnchor: self.topAnchor)
constraintEqual(anchor: container.rightAnchor, toAnchor: self.rightAnchor)
container.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: titleView.centerXAnchor, toAnchor: container.centerXAnchor)
constraintEqual(anchor: titleView.centerYAnchor, toAnchor: container.centerYAnchor)
titleView.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: iconView.rightAnchor, toAnchor: titleView.leftAnchor, constant: -7)
constraintEqual(anchor: iconView.centerYAnchor, toAnchor: titleView.centerYAnchor)
iconView.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
titleView.font = UIFont.systemFont(ofSize: 12.5)
titleView.textColor = UIColor.black.withAlphaComponent(0.56)
iconView.tintColor = UIColor( red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0 )
self.titleView = titleView
self.iconView = iconView
self.clipsToBounds = true
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.viewNoIntrinsicMetric, height: 35)
}
static var ssoInfoBar: InfoBarView {
let ssoBar = InfoBarView()
ssoBar.title = "SINGLE SIGN-ON ENABLED".i18n(key: "com.auth0.lock.enterprise.sso.title", comment: "SSO Header")
ssoBar.icon = UIImage(named: "ic_lock_full", in: bundleForLock())
return ssoBar
}
}
| mit | d03418511497587236d1e22cf122285b | 35.486239 | 120 | 0.687956 | 4.700946 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsPayloadKeysEnabled.swift | 1 | 14755 | //
// ProfileSettingsPayloadKeysEnabled.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileSettings {
// MARK: -
// MARK: Check Any Subkey
// if ANY payload has this subkey enabled
func isEnabled(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool) -> Bool {
let domainSettings = self.viewSettings(forDomainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType) ?? [[String: Any]]()
if domainSettings.isEmpty {
return self.isEnabled(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: 0)
} else {
for payloadIndex in domainSettings.indices {
if self.isEnabled(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) { return true }
}
}
return false
}
// MARK: -
// MARK: Is Enabled: Subkey
// MARK: -
// MARK: Is Enabled: By…
func isEnabledByRequired(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool, isRequired: Bool, payloadIndex: Int) -> Bool {
if !onlyByUser, parentIsEnabled, isRequired {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Required", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
return false
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByUser(_ subkey: PayloadSubkey, payloadIndex: Int) -> Bool? {
guard let isEnabled = self.viewValueEnabled(forSubkey: subkey, payloadIndex: payloadIndex) else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled) - User", category: String(describing: self))
#endif
return isEnabled
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByDefault(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool) -> Bool? {
guard !onlyByUser, parentIsEnabled, subkey.enabledDefault else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Default", category: String(describing: self))
#endif
return true
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByDynamicDictionary(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool, payloadIndex: Int) -> Bool? {
guard !onlyByUser, parentIsEnabled, subkey.parentSubkey?.type == .dictionary, (subkey.key == ManifestKeyPlaceholder.key || subkey.key == ManifestKeyPlaceholder.value) else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Dynamic Dictionary", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByArrayOfDictionaries(_ subkey: PayloadSubkey, parentIsEnabled: Bool, payloadIndex: Int, arrayIndex: Int) -> Bool? {
guard parentIsEnabled, subkey.isParentArrayOfDictionaries else { return nil }
let isEnabled: Bool
if arrayIndex == -1 || (arrayIndex != -1 && self.value(forSubkey: subkey, payloadIndex: payloadIndex) != nil) {
isEnabled = true
} else {
isEnabled = false
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled) - Child in Array of Dictionaries", category: String(describing: self))
#endif
return isEnabled
}
func isEnabled(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool, payloadIndex: Int, arrayIndex: Int = -1) -> Bool {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - onlyByUser: \(onlyByUser), ignoreConditionals: \(ignoreConditionals), payloadIndex: \(payloadIndex), arrayIndex: \(arrayIndex)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if the subkey has a cached isEnabled-value, if so return that
// ---------------------------------------------------------------------
if let isEnabledCache = self.cacheIsEnabled(subkey, payloadIndex: payloadIndex) { return isEnabledCache }
// ---------------------------------------------------------------------
// Check if all parent subkeys are enabled
// ---------------------------------------------------------------------
let isEnabledParent = self.isEnabledParent(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex, arrayIndex: arrayIndex)
// ---------------------------------------------------------------------
// Check if the parent subkey is an array and enabled, then this subkey is automatically enabled
// ---------------------------------------------------------------------
guard !self.isEnabledParentAnArray(isEnabledParent, subkey: subkey, onlyByUser: onlyByUser, payloadIndex: payloadIndex) else { return true }
// ---------------------------------------------------------------------
// Set the default isEnabled state
// ---------------------------------------------------------------------
var isEnabled = !self.disableOptionalKeys
// ---------------------------------------------------------------------
// Check if the subkey is required
// ---------------------------------------------------------------------
let isRequired = self.isRequired(subkey: subkey, ignoreConditionals: ignoreConditionals, isEnabledOnlyByUser: onlyByUser, payloadIndex: payloadIndex)
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isRequired: \(isRequired)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if the subkey is required, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
guard !isEnabledByRequired(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser, isRequired: isRequired, payloadIndex: payloadIndex) else { return true }
// ---------------------------------------------------------------------
// Check if the subkey is manually enabled/disabled by the user
// ---------------------------------------------------------------------
if let isEnabledByUser = self.isEnabledByUser(subkey, payloadIndex: payloadIndex) {
isEnabled = isEnabledByUser
// ---------------------------------------------------------------------
// Check if the subkey is enabled by default in the manifest, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
} else if let isEnabledByDefault = self.isEnabledByDefault(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser) {
isEnabled = isEnabledByDefault
// ---------------------------------------------------------------------
// Check if the subkey is a dynamic dictionary, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
} else if let isEnabledByDynamicDictionary = self.isEnabledByDynamicDictionary(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser, payloadIndex: payloadIndex) {
return isEnabledByDynamicDictionary
// ---------------------------------------------------------------------
// Check if the subkey is a child in an array of dictionaries, and if it's parent is enabled.
// ---------------------------------------------------------------------
} else if let isEnabledByArrayOfDictionaries = self.isEnabledByArrayOfDictionaries(subkey, parentIsEnabled: isEnabledParent, payloadIndex: payloadIndex, arrayIndex: arrayIndex) {
return isEnabledByArrayOfDictionaries
}
// ---------------------------------------------------------------------
// Check if key was not enabled, and if key is an array, then loop through each child subkeys and if any child is enabled this key should also be enabled
// ---------------------------------------------------------------------
// FIXME: Should this be typeInput aswell?
if !isEnabled, (subkey.type != .array || subkey.rangeMax as? Int == 1) {
isEnabled = self.isEnabled(childSubkeys: subkey.subkeys, forSubkey: subkey, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex)
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if enabled state should be cached
// ---------------------------------------------------------------------
if !ignoreConditionals && ( !onlyByUser || onlyByUser && !isRequired ) {
self.setCacheIsEnabled(isEnabled, forSubkey: subkey, payloadIndex: payloadIndex)
}
// ---------------------------------------------------------------------
// Return if key is enabled
// ---------------------------------------------------------------------
return isEnabled
}
// MARK: -
// MARK: Is Enabled: Parent
func isEnabledParent(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool, payloadIndex: Int, arrayIndex: Int) -> Bool {
guard !onlyByUser, let parentSubkeys = subkey.parentSubkeys else {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(true)", category: String(describing: self))
#endif
return true
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - Parents", category: String(describing: self))
#endif
// Loop through all parents
for parentSubkey in parentSubkeys {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - Parent: \(parentSubkey.keyPath)", category: String(describing: self))
#endif
// Ignore Dictionaries in Single Dictionary Arrays
if parentSubkey.type == .dictionary, (parentSubkey.parentSubkey?.type == .array && parentSubkey.parentSubkey?.rangeMax as? Int == 1) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - IGNORING parent: \(parentSubkey.keyPath) - Dictionary in single dictionary array", category: String(describing: self))
#endif
continue
} else {
if !self.isEnabled(parentSubkey, onlyByUser: false, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex, arrayIndex: arrayIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(false)", category: String(describing: self))
#endif
return false
}
}
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(true)", category: String(describing: self))
#endif
return true
}
// Check if parent is an array, except if the array key has rangeMax set to 1
func isEnabledParentAnArray(_ isEnabledParent: Bool, subkey: PayloadSubkey, onlyByUser: Bool, payloadIndex: Int) -> Bool {
if !onlyByUser, isEnabledParent, subkey.parentSubkey?.typeInput == .array, !(subkey.parentSubkey?.rangeMax as? Int == 1) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - ParentArray", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
return false
}
// MARK: -
// MARK: Check Child Subkeys
func isEnabled(childSubkeys: [PayloadSubkey], forSubkey subkey: PayloadSubkey, ignoreConditionals: Bool, payloadIndex: Int) -> Bool {
for childSubkey in childSubkeys {
if childSubkey.type == .dictionary, subkey.rangeMax as? Int == 1 {
for dictSubkey in subkey.subkeys {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking Child Dictionary Subkey: \(dictSubkey.keyPath)", category: String(describing: self))
#endif
if self.isEnabled(dictSubkey, onlyByUser: true, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Child: \(childSubkey.keyPath)", category: String(describing: self))
#endif
return true
}
}
} else {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking Child Subkey: \(childSubkey.keyPath)", category: String(describing: self))
#endif
if self.isEnabled(childSubkey, onlyByUser: true, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Child: \(childSubkey.keyPath)", category: String(describing: self))
#endif
return true
}
}
}
return false
}
}
| mit | 18802865fa9059ac57dda1d31e593a10 | 49.694158 | 248 | 0.564195 | 5.25918 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.