repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SuPair/firefox-ios | refs/heads/master | Client/Helpers/UserActivityHandler.swift | mpl-2.0 | 4 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import CoreSpotlight
import MobileCoreServices
import WebKit
private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing"
private let searchableIndex = CSSearchableIndex(name: "firefox")
class UserActivityHandler {
private var tabObservers: TabObservers!
init() {
self.tabObservers = registerFor(
.didLoseFocus,
.didGainFocus,
.didChangeURL,
.didLoadPageMetadata,
// .didLoadFavicon, // TODO: Bug 1390294
.didClose,
queue: .main)
}
deinit {
unregister(tabObservers)
}
class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) {
searchableIndex.deleteAllSearchableItems(completionHandler: completionHandler)
}
fileprivate func setUserActivityForTab(_ tab: Tab, url: URL) {
guard !tab.isPrivate, url.isWebPage(includeDataURIs: false), !url.isLocal else {
tab.userActivity?.resignCurrent()
tab.userActivity = nil
return
}
tab.userActivity?.invalidate()
let userActivity = NSUserActivity(activityType: browsingActivityType)
userActivity.webpageURL = url
userActivity.becomeCurrent()
tab.userActivity = userActivity
}
}
extension UserActivityHandler: TabEventHandler {
func tabDidGainFocus(_ tab: Tab) {
tab.userActivity?.becomeCurrent()
}
func tabDidLoseFocus(_ tab: Tab) {
tab.userActivity?.resignCurrent()
}
func tab(_ tab: Tab, didChangeURL url: URL) {
setUserActivityForTab(tab, url: url)
}
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
guard let url = URL(string: metadata.siteURL) else {
return
}
setUserActivityForTab(tab, url: url)
}
func tabDidClose(_ tab: Tab) {
guard let userActivity = tab.userActivity else {
return
}
tab.userActivity = nil
userActivity.invalidate()
}
}
| d0f2ddfff3b44be74dfdaa5db4bad3b0 | 28.192771 | 88 | 0.607099 | false | false | false | false |
danielhour/DINC | refs/heads/master | DINC/Parameters.swift | mit | 1 | //
// Parameters.swift
// DINC
//
// Created by dhour on 4/14/16.
// Copyright © 2016 DHour. All rights reserved.
//
//import Foundation
//
//
///**
// * Parameters for PlaidService requests
// */
//struct Parameters {
//
// ///
// var body = [String: AnyObject]()
//
//
// /**
// Init with `clientID` & `secret`
// */
// init() {
// body["client_id"] = Constants.Plaid.clientID
// body["secret"] = Constants.Plaid.secret
// }
//
//
//
// static func addUserParams(institution: String, username: String, password: String) -> Parameters {
// var params = Parameters()
// params.body["type"] = institution
// params.body["username"] = username
// params.body["password"] = password
//
// var options = [String: AnyObject]()
// options["list"] = true
// params.body["options"] = options
//
// return params
// }
//
//
// /**
// Add parameters to fetch transactions
//
// - parameter beginDate: date with `String` format `yyyy-MM-dd`
// - parameter endDate: date with `String` format `yyyy-MM-dd`
//
// - returns: `Parameters` object to send with request
// */
// static func addTransactionParams(beginDate: String, endDate: String) -> Parameters {
// var params = Parameters()
// params.body["access_token"] = Constants.Plaid.accessToken
//
// var options = [String: AnyObject]()
// options["pending"] = true
// options["gte"] = beginDate
// options["lte"] = endDate
// params.body["options"] = options
//
// return params
// }
//}
| 4876e9ef56470d262ef78e1529e1dc0b | 25.076923 | 104 | 0.538053 | false | false | false | false |
gigascorp/fiscal-cidadao | refs/heads/master | ios/FiscalCidadao/LocationController.swift | gpl-3.0 | 1 | /*
Copyright (c) 2009-2014, Apple Inc. All rights reserved.
Copyright (C) 2016 Andrea Mendonça, Emílio Weba, Guilherme Ribeiro, Márcio Oliveira, Thiago Nunes, Wallas Henrique
This file is part of Fiscal Cidadão.
Fiscal Cidadão 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.
Fiscal Cidadão 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 Fiscal Cidadão. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import MapKit
enum
LocationStatus
{
case NO_STATUS, LOCATION_RESTRICTED, LOCATION_DENIED, LOCATION_ALLOWED
}
class LocationController : BaseController, CLLocationManagerDelegate
{
static let InitializedLocationMessage = 1
static let sharedInstance = LocationController()
var locationManager: CLLocationManager!
var currentLocation : CLLocation?
var locationStatus = LocationStatus.NO_STATUS
override init()
{
super.init()
locationManager = CLLocationManager()
switch CLLocationManager.authorizationStatus()
{
case CLAuthorizationStatus.Restricted:
locationStatus = LocationStatus.LOCATION_RESTRICTED
case CLAuthorizationStatus.Denied:
locationStatus = LocationStatus.LOCATION_DENIED
case CLAuthorizationStatus.NotDetermined:
locationStatus = LocationStatus.NO_STATUS
case CLAuthorizationStatus.Authorized:
locationStatus = LocationStatus.LOCATION_ALLOWED
case CLAuthorizationStatus.AuthorizedWhenInUse:
locationStatus = LocationStatus.LOCATION_ALLOWED
}
if locationStatus == LocationStatus.LOCATION_ALLOWED
{
locationManager.startUpdatingLocation()
if locationManager.location != nil
{
currentLocation = locationManager.location
}
}
locationManager.delegate = self
}
func hasLocation() -> Bool
{
if locationStatus == LocationStatus.LOCATION_ALLOWED
{
if currentLocation != nil
{
return true
}
}
return false
}
func getLocation() -> (Double, Double)
{
let loc = currentLocation!
let coord = loc.coordinate
return (coord.latitude, coord.longitude)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
locationManager.stopUpdatingLocation()
print(error)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let isNewLocation = currentLocation == nil
currentLocation = locations.last
if isNewLocation
{
notify(LocationController.InitializedLocationMessage)
}
// print("Last location : \(currentLocation)")
}
func requestAuth()
{
let authorizationStatus = CLLocationManager.authorizationStatus()
if(authorizationStatus == CLAuthorizationStatus.Authorized)
{
locationManager.startUpdatingLocation()
}
else if #available(iOS 8.0, *)
{
if (authorizationStatus == .AuthorizedWhenInUse || authorizationStatus == .AuthorizedAlways)
{
locationManager.startUpdatingLocation()
}
else if self.locationManager.respondsToSelector(#selector(CLLocationManager.requestAlwaysAuthorization))
{
self.locationManager.requestWhenInUseAuthorization()
}
else
{
locationManager.startUpdatingLocation()
}
}
else
{
// TODO:
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
var shouldIAllow = false
switch status
{
case CLAuthorizationStatus.Restricted:
locationStatus = LocationStatus.LOCATION_RESTRICTED
case CLAuthorizationStatus.Denied:
locationStatus = LocationStatus.LOCATION_DENIED
case CLAuthorizationStatus.NotDetermined:
locationStatus = LocationStatus.NO_STATUS
case CLAuthorizationStatus.Authorized:
locationStatus = LocationStatus.LOCATION_ALLOWED
shouldIAllow = true
case CLAuthorizationStatus.AuthorizedWhenInUse:
locationStatus = LocationStatus.LOCATION_ALLOWED
shouldIAllow = true
}
if (shouldIAllow)
{
print("Location Allowed")
locationManager.startUpdatingLocation()
print(locationManager.location)
}
else
{
print("Denied access: \(locationStatus)")
}
}
} | 2a98264a789ac110d4d05c54cb53ec65 | 29.715084 | 116 | 0.617973 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripeCardScan/StripeCardScan/Source/CardVerify/Card Image Verification/CardImageVerificationController.swift | mit | 1 | //
// CardImageVerificationController.swift
// StripeCardScan
//
// Created by Jaime Park on 11/17/21.
//
import Foundation
@_spi(STP) import StripeCore
import UIKit
protocol CardImageVerificationControllerDelegate: AnyObject {
func cardImageVerificationController(
_ controller: CardImageVerificationController,
didFinishWithResult result: CardImageVerificationSheetResult
)
}
class CardImageVerificationController {
weak var delegate: CardImageVerificationControllerDelegate?
private let intent: CardImageVerificationIntent
private let configuration: CardImageVerificationSheet.Configuration
init(
intent: CardImageVerificationIntent,
configuration: CardImageVerificationSheet.Configuration
) {
self.intent = intent
self.configuration = configuration
}
func present(
with expectedCard: CardImageVerificationExpectedCard,
and acceptedImageConfigs: CardImageVerificationAcceptedImageConfigs?,
from presentingViewController: UIViewController,
animated: Bool = true
) {
/// Guard against basic user error
guard presentingViewController.presentedViewController == nil else {
assertionFailure("presentingViewController is already presenting a view controller")
let error = CardScanSheetError.unknown(
debugDescription: "presentingViewController is already presenting a view controller"
)
self.delegate?.cardImageVerificationController(
self,
didFinishWithResult: .failed(error: error)
)
return
}
// TODO(jaimepark): Create controller that has configurable view and handles coordination / business logic
if let expectedCardLast4 = expectedCard.last4 {
/// Create the view controller for card-set-verification with expected card's last4 and issuer
let vc = VerifyCardViewController(
acceptedImageConfigs: acceptedImageConfigs,
configuration: configuration,
expectedCardLast4: expectedCardLast4,
expectedCardIssuer: expectedCard.issuer
)
vc.verifyDelegate = self
presentingViewController.present(vc, animated: animated)
} else {
/// Create the view controller for card-add-verification
let vc = VerifyCardAddViewController(
acceptedImageConfigs: acceptedImageConfigs,
configuration: configuration
)
vc.verifyDelegate = self
presentingViewController.present(vc, animated: animated)
}
}
func dismissWithResult(
_ presentingViewController: UIViewController,
result: CardImageVerificationSheetResult
) {
/// Fire-and-forget uploading the scan stats
ScanAnalyticsManager.shared.generateScanAnalyticsPayload(with: configuration) {
[weak self] payload in
guard let self = self,
let payload = payload
else {
return
}
self.configuration.apiClient.uploadScanStats(
cardImageVerificationId: self.intent.id,
cardImageVerificationSecret: self.intent.clientSecret,
scanAnalyticsPayload: payload
)
}
/// Dismiss the view controller
presentingViewController.dismiss(animated: true) { [weak self] in
guard let self = self else { return }
self.delegate?.cardImageVerificationController(self, didFinishWithResult: result)
}
}
}
// MARK: Verify Card Add Delegate
extension CardImageVerificationController: VerifyViewControllerDelegate {
/// User scanned a card successfully. Submit verification frames data to complete verification flow
func verifyViewControllerDidFinish(
_ viewController: UIViewController,
verificationFramesData: [VerificationFramesData],
scannedCard: ScannedCard
) {
let completionLoopTask = TrackableTask()
/// Submit verification frames and wait for response for verification flow completion
configuration.apiClient.submitVerificationFrames(
cardImageVerificationId: intent.id,
cardImageVerificationSecret: intent.clientSecret,
verificationFramesData: verificationFramesData
).observe { [weak self] result in
switch result {
case .success:
completionLoopTask.trackResult(.success)
ScanAnalyticsManager.shared.trackCompletionLoopDuration(task: completionLoopTask)
self?.dismissWithResult(
viewController,
result: .completed(scannedCard: scannedCard)
)
case .failure(let error):
completionLoopTask.trackResult(.failure)
ScanAnalyticsManager.shared.trackCompletionLoopDuration(task: completionLoopTask)
self?.dismissWithResult(
viewController,
result: .failed(error: error)
)
}
}
}
/// User canceled the verification flow
func verifyViewControllerDidCancel(
_ viewController: UIViewController,
with reason: CancellationReason
) {
dismissWithResult(
viewController,
result: .canceled(reason: reason)
)
}
/// Verification flow has failed
func verifyViewControllerDidFail(
_ viewController: UIViewController,
with error: Error
) {
dismissWithResult(
viewController,
result: .failed(error: error)
)
}
}
| 1e96422972439e5fc7f494f21b0c2d0d | 35.21875 | 114 | 0.646764 | false | true | false | false |
nahive/doppelganger-swift | refs/heads/master | Doppelganger-Swift/Doppelganger.swift | unlicense | 1 | //
// Doppelganger.swift
// Doppelganger-Swift-Sample
//
// Created by Szymon Maślanka on 20/06/2018.
// Copyright © 2018 Szymon Maślanka. All rights reserved.
//
import Foundation
import UIKit
final class Doppelganger {
enum Difference {
case move(from: Int, to: Int)
case insert(new: Int)
case delete(old: Int)
var description: String {
switch self {
case .move(let from, let to):
return "\(String(describing: self)) {type=move; from=\(from); to=\(to)}"
case .insert(let new):
return "\(String(describing: self)) {type=insertion; new=\(new)}"
case .delete(let old):
return "\(String(describing: self)) {type=delete; old=\(old)}"
}
}
}
class func difference<T: Hashable>(currentArray: [T], previousArray: [T]) -> [Difference] {
let previousSet = Set(previousArray)
let currentSet = Set(currentArray)
print("previousSet : \(previousSet)")
print("currentSet : \(currentSet)")
let deletedObjects = previousSet.subtracting(currentSet)
let insertedObjects = currentSet.subtracting(previousSet)
print("deletedObjects : \(deletedObjects)")
print("insertedObjects : \(insertedObjects)")
let deletionDiffs = deletions(array: previousArray, deletedObjects: deletedObjects)
let insertionDiffs = insertions(array: currentArray, insertedObjects: insertedObjects)
let moveDiffs = moves(currentArray: currentArray, previousArray: previousArray, deletedObjects: deletedObjects, insertedObjects: insertedObjects)
return deletionDiffs + insertionDiffs + moveDiffs
}
private class func deletions<T: Hashable>(array: [T], deletedObjects: Set<T>) -> [Difference] {
var result = [Difference]()
for (index, obj) in array.enumerated() {
if !deletedObjects.contains(obj) {
continue
}
result.append(.delete(old: index))
}
return result
}
private class func insertions<T: Hashable>(array: [T], insertedObjects: Set<T>) -> [Difference] {
var result = [Difference]()
for (index, obj) in array.enumerated() {
if !insertedObjects.contains(obj) {
continue
}
result.append(.insert(new: index))
}
return result
}
private class func moves<T: Hashable>(currentArray: [T], previousArray: [T], deletedObjects: Set<T>, insertedObjects: Set<T>) -> [Difference] {
var delta = 0
var result = [Difference]()
for (indexPrevious, objPrevious) in previousArray.enumerated() {
if deletedObjects.contains(objPrevious) {
delta += 1
continue
}
var localDelta = delta
for (indexCurrent, objCurrent) in currentArray.enumerated() {
if insertedObjects.contains(objCurrent) {
localDelta -= 1
continue
}
if objCurrent != objPrevious {
continue
}
let adjustedIndexCurrent = indexCurrent + localDelta
if indexPrevious != indexCurrent && adjustedIndexCurrent != indexPrevious {
result.append(.move(from: indexPrevious, to: indexCurrent))
}
break
}
}
return result
}
typealias RowSplitResult = (insertion: [IndexPath], deletion: [IndexPath], move: [(IndexPath, IndexPath)])
fileprivate class func splitRows(array: [Difference], in section: Int) -> RowSplitResult {
var insertion = [IndexPath]()
var deletion = [IndexPath]()
var move = [(IndexPath, IndexPath)]()
for type in array {
switch type {
case .delete(let old):
deletion.append(IndexPath(row: old, section: section))
case .insert(let new):
insertion.append(IndexPath(row: new, section: section))
case .move(let from, let to):
move.append((IndexPath(row: from, section: section), IndexPath(row: to, section: section)))
}
}
return (insertion, deletion, move)
}
typealias SectionSplitResult = (insertion: IndexSet, deletion: IndexSet, move: [(Int, Int)])
fileprivate class func splitSections(array: [Difference]) -> SectionSplitResult {
let insertion = NSMutableIndexSet()
let deletion = NSMutableIndexSet()
var move = [(Int, Int)]()
for type in array {
switch type {
case .delete(let old):
deletion.add(old)
case .insert(let new):
insertion.add(new)
case .move(let from, let to):
move.append((from, to))
}
}
return (insertion as IndexSet, deletion as IndexSet, move)
}
}
extension UICollectionView {
func performItemUpdates(array: [Doppelganger.Difference], inSection section: Int) {
let result = Doppelganger.splitRows(array: array, in: section)
performBatchUpdates({
self.insertItems(at: result.insertion)
self.deleteItems(at: result.deletion)
result.move.forEach { self.moveItem(at: $0.0, to: $0.1) }
}) { (finished) in }
}
func performSectionUpdates(array: [Doppelganger.Difference]) {
let result = Doppelganger.splitSections(array: array)
performBatchUpdates({
self.insertSections(result.insertion)
self.deleteSections(result.deletion)
result.move.forEach { self.moveSection($0.0, toSection: $0.1) }
}) { (finished) in }
}
}
extension UITableView {
func performRowUpdates(array: [Doppelganger.Difference], inSection section: Int, withRowAnimation animation: UITableView.RowAnimation) {
let result = Doppelganger.splitRows(array: array, in: section)
beginUpdates()
deleteRows(at: result.deletion, with: animation)
insertRows(at: result.insertion, with: animation)
result.move.forEach { moveRow(at: $0.0, to: $0.1) }
endUpdates()
}
func performSectionUpdates(array: [Doppelganger.Difference], withRowAnimation animation: UITableView.RowAnimation) {
let result = Doppelganger.splitSections(array: array)
beginUpdates()
deleteSections(result.deletion, with: animation)
insertSections(result.insertion, with: animation)
result.move.forEach { moveSection($0.0, toSection: $0.1) }
endUpdates()
}
}
| 6ca5a312eb33c532f60c7c29179542bf | 36.12973 | 153 | 0.581598 | false | false | false | false |
miller-ms/ViewAnimator | refs/heads/master | ViewAnimator/TransitionController.swift | gpl-3.0 | 1 | //
// TransitionController.swift
// ViewAnimator
//
// Created by William Miller DBA Miller Mobilesoft on 5/13/17.
//
// This application is intended to be a developer tool for evaluating the
// options for creating an animation or transition using the UIView static
// methods UIView.animate and UIView.transition.
// Copyright © 2017 William Miller DBA Miller Mobilesoft
//
// 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/>.
//
// If you would like to reach the developer you may email me at
// [email protected] or visit my website at
// http://millermobilesoft.com
//
import UIKit
class TransitionController: AnimatorController {
enum ParamCellIdentifiers:Int {
case durationCell = 0
case optionsCell
case count
}
enum TransitionCellIdentifiers:Int {
case transitionCell = 0
case count
}
enum SectionIdentifiers:Int {
case transitionSection = 0
case parameterSection
case count
}
var duration = Double(1.0)
var options = OptionsModel(options: [UIViewAnimationOptions.transitionCrossDissolve])
override func viewDidLoad() {
super.viewDidLoad()
cellIdentifiers = [ "TransitionCell", "DurationCellId", "OptionsCellId"]
sectionHeaderTitles = ["Transition", "Parameters"]
identifierBaseIdx = [0,
TransitionCellIdentifiers.count.rawValue]
sectionCount = [TransitionCellIdentifiers.count.rawValue, ParamCellIdentifiers.count.rawValue]
rowHeights = [CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func transferParametersFromCells() {
let parameterPath = IndexPath(row:ParamCellIdentifiers.durationCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue)
let cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell
if cell != nil {
duration = Double(cell!.value)
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let propertySection = SectionIdentifiers(rawValue: indexPath.section) else {
fatalError("invalid section in properties controller")
}
switch propertySection {
case .parameterSection:
guard let paramCellId = ParamCellIdentifiers(rawValue: indexPath.row) else {
fatalError("Invalid row in parameter section")
}
if paramCellId == .durationCell {
let paramCell = cell as! FloatValueCell
paramCell.value = Float(duration)
}
default:
break
}
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let propertySection = SectionIdentifiers(rawValue: indexPath.section) else {
fatalError("invalid section in properties controller")
}
switch propertySection {
case .parameterSection:
guard let paramCellId = ParamCellIdentifiers(rawValue: indexPath.row) else {
fatalError("Invalid row in parameter section")
}
if paramCellId == .durationCell {
let paramCell = cell as! FloatValueCell
duration = Double(paramCell.value)
}
default:
break
}
}
/*
// 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
let optionsController = segue.destination as! TransitionOptionsController
optionsController.options = options
}
@IBAction func durationChanged(_ sender: UISlider) {
let cell = sender.superview!.superview as! FloatValueCell
duration = Double(cell.value)
}
@IBAction func executeTransition(_ sender: UIButton) {
let cell = sender.superview?.superview as! TransitionCell
var hex = String(format: "%x", options.animationOptions.rawValue)
print("Options for animate are \(hex)")
hex = String(format: "%x", UIViewAnimationOptions.transitionCrossDissolve.rawValue)
print("crosse dissolve value is \(hex)")
transferParametersFromCells()
cell.executeTransition(withDuration: duration, animationOptions: options.animationOptions)
}
}
| db2c139621208bcf3e380ad309c37c8c | 31.131868 | 140 | 0.636799 | false | false | false | false |
flovilmart/Carthage | refs/heads/master | Source/CarthageKit/GitHub.swift | mit | 1 | //
// GitHub.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-10.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Argo
import Foundation
import LlamaKit
import ReactiveCocoa
/// The User-Agent to use for GitHub requests.
private let userAgent: String = {
let bundle = NSBundle.mainBundle() ?? NSBundle(identifier: CarthageKitBundleIdentifier)
let version: AnyObject = bundle?.objectForInfoDictionaryKey("CFBundleShortVersionString") ?? bundle?.objectForInfoDictionaryKey(kCFBundleVersionKey) ?? "unknown"
let identifier = bundle?.bundleIdentifier ?? "CarthageKit-unknown"
return "\(identifier)/\(version)"
}()
/// The type of content to request from the GitHub API.
private let APIContentType = "application/vnd.github.v3+json"
/// Describes a GitHub.com repository.
public struct GitHubRepository: Equatable {
public let owner: String
public let name: String
/// The URL that should be used for cloning this repository over HTTPS.
public var HTTPSURL: GitURL {
return GitURL("https://github.com/\(owner)/\(name).git")
}
/// The URL that should be used for cloning this repository over SSH.
public var SSHURL: GitURL {
return GitURL("ssh://[email protected]/\(owner)/\(name).git")
}
/// The URL for filing a new GitHub issue for this repository.
public var newIssueURL: NSURL {
return NSURL(string: "https://github.com/\(owner)/\(name)/issues/new")!
}
public init(owner: String, name: String) {
self.owner = owner
self.name = name
}
/// Parses repository information out of a string of the form "owner/name".
public static func fromNWO(NWO: String) -> Result<GitHubRepository> {
let components = split(NWO, { $0 == "/" }, maxSplit: 1, allowEmptySlices: false)
if components.count < 2 {
return failure(CarthageError.ParseError(description: "invalid GitHub repository name \"\(NWO)\"").error)
}
return success(self(owner: components[0], name: components[1]))
}
}
public func ==(lhs: GitHubRepository, rhs: GitHubRepository) -> Bool {
return lhs.owner == rhs.owner && lhs.name == rhs.name
}
extension GitHubRepository: Hashable {
public var hashValue: Int {
return owner.hashValue ^ name.hashValue
}
}
extension GitHubRepository: Printable {
public var description: String {
return "\(owner)/\(name)"
}
}
/// Represents a Release on a GitHub repository.
public struct GitHubRelease: Equatable {
/// The unique ID for this release.
public let ID: Int
/// The name of this release.
public let name: String
/// The name of this release, with fallback to its tag when the name is an empty string.
public var nameWithFallback: String {
return name.isEmpty ? tag : name
}
/// The name of the tag upon which this release is based.
public let tag: String
/// Whether this release is a draft (only visible to the authenticted user).
public let draft: Bool
/// Whether this release represents a prerelease version.
public let prerelease: Bool
/// Any assets attached to the release.
public let assets: [Asset]
/// An asset attached to a GitHub Release.
public struct Asset: Equatable, Hashable, Printable, JSONDecodable {
/// The unique ID for this release asset.
public let ID: Int
/// The filename of this asset.
public let name: String
/// The MIME type of this asset.
public let contentType: String
/// The URL at which the asset can be downloaded directly.
public let downloadURL: NSURL
public var hashValue: Int {
return ID.hashValue
}
public var description: String {
return "Asset { name = \(name), contentType = \(contentType), downloadURL = \(downloadURL) }"
}
public static func create(ID: Int)(name: String)(contentType: String)(downloadURL: NSURL) -> Asset {
return self(ID: ID, name: name, contentType: contentType, downloadURL: downloadURL)
}
public static func decode(j: JSONValue) -> Asset? {
return self.create
<^> j <| "id"
<*> j <| "name"
<*> j <| "content_type"
<*> j <| "browser_download_url"
}
}
}
public func == (lhs: GitHubRelease, rhs: GitHubRelease) -> Bool {
return lhs.ID == rhs.ID
}
public func == (lhs: GitHubRelease.Asset, rhs: GitHubRelease.Asset) -> Bool {
return lhs.ID == rhs.ID
}
extension GitHubRelease: Hashable {
public var hashValue: Int {
return ID.hashValue
}
}
extension GitHubRelease: Printable {
public var description: String {
return "Release { ID = \(ID), name = \(name), tag = \(tag) } with assets: \(assets)"
}
}
extension GitHubRelease: JSONDecodable {
public static func create(ID: Int)(name: String)(tag: String)(draft: Bool)(prerelease: Bool)(assets: [Asset]) -> GitHubRelease {
return self(ID: ID, name: name, tag: tag, draft: draft, prerelease: prerelease, assets: assets)
}
public static func decode(j: JSONValue) -> GitHubRelease? {
return self.create
<^> j <| "id"
<*> j <| "name"
<*> j <| "tag_name"
<*> j <| "draft"
<*> j <| "prerelease"
<*> j <|| "assets"
}
}
/// Represents credentials suitable for logging in to GitHub.com.
internal struct GitHubCredentials {
let username: String
let password: String
/// Returns the credentials encoded into a value suitable for the
/// `Authorization` HTTP header.
var authorizationHeaderValue: String {
let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let encodedString = data.base64EncodedStringWithOptions(nil)
return "Basic \(encodedString)"
}
/// Attempts to load credentials from the Git credential store.
static func loadFromGit() -> ColdSignal<GitHubCredentials?> {
let data = "url=https://github.com".dataUsingEncoding(NSUTF8StringEncoding)!
return launchGitTask([ "credential", "fill" ], standardInput: ColdSignal.single(data))
.mergeMap { $0.linesSignal }
.reduce(initial: [:]) { (var values: [String: String], line) in
let parts = split(line, { $0 == "=" }, maxSplit: 1, allowEmptySlices: false)
if parts.count >= 2 {
let key = parts[0]
let value = parts[1]
values[key] = value
}
return values
}
.map { values -> GitHubCredentials? in
if let username = values["username"] {
if let password = values["password"] {
return self(username: username, password: password)
}
}
return nil
}
}
}
/// Creates a request to fetch the given GitHub URL, optionally authenticating
/// with the given credentials.
internal func createGitHubRequest(URL: NSURL, credentials: GitHubCredentials?) -> NSURLRequest {
let request = NSMutableURLRequest(URL: URL)
request.setValue(APIContentType, forHTTPHeaderField: "Accept")
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
if let credentials = credentials {
request.setValue(credentials.authorizationHeaderValue, forHTTPHeaderField: "Authorization")
}
return request
}
/// Parses the value of a `Link` header field into a list of URLs and their
/// associated parameter lists.
private func parseLinkHeader(linkValue: String) -> [(NSURL, [String])] {
let components = split(linkValue, { $0 == "," }, allowEmptySlices: false)
return reduce(components, []) { (var links, component) in
var pieces = split(component, { $0 == ";" }, allowEmptySlices: false)
if let URLPiece = pieces.first {
pieces.removeAtIndex(0)
let scanner = NSScanner(string: URLPiece)
var URLString: NSString?
if scanner.scanString("<", intoString: nil) && scanner.scanUpToString(">", intoString: &URLString) {
if let URL = NSURL(string: URLString!) {
let value: (NSURL, [String]) = (URL, pieces)
links.append(value)
}
}
}
return links
}
}
/// Fetches the given GitHub URL, automatically paginating to the end.
///
/// Returns a signal that will send one `NSData` for each page fetched.
private func fetchAllPages(URL: NSURL, credentials: GitHubCredentials?) -> ColdSignal<NSData> {
let request = createGitHubRequest(URL, credentials)
return NSURLSession.sharedSession()
.rac_dataWithRequest(request)
.mergeMap { data, response -> ColdSignal<NSData> in
let thisData = ColdSignal.single(data)
if let HTTPResponse = response as? NSHTTPURLResponse {
if let linkHeader = HTTPResponse.allHeaderFields["Link"] as? String {
let links = parseLinkHeader(linkHeader)
for (URL, parameters) in links {
if contains(parameters, "rel=\"next\"") {
// Automatically fetch the next page too.
return thisData.concat(fetchAllPages(URL, credentials))
}
}
}
}
return thisData
}
}
/// Fetches the release corresponding to the given tag on the given repository,
/// sending it along the returned signal. If no release matches, the signal will
/// complete without sending any values.
internal func releaseForTag(tag: String, repository: GitHubRepository, credentials: GitHubCredentials?) -> ColdSignal<GitHubRelease> {
return fetchAllPages(NSURL(string: "https://api.github.com/repos/\(repository.owner)/\(repository.name)/releases/tags/\(tag)")!, credentials)
.tryMap { data, error -> AnyObject? in
return NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error)
}
.catch { _ in .empty() }
.concatMap { releaseDictionary -> ColdSignal<GitHubRelease> in
if let release = GitHubRelease.decode(JSONValue.parse(releaseDictionary)) {
return .single(release)
} else {
return .empty()
}
}
}
/// Downloads the indicated release asset to a temporary file, returning the
/// URL to the file on disk.
///
/// The downloaded file will be deleted after the URL has been sent upon the
/// signal.
internal func downloadAsset(asset: GitHubRelease.Asset, credentials: GitHubCredentials?) -> ColdSignal<NSURL> {
let request = createGitHubRequest(asset.downloadURL, credentials)
return NSURLSession.sharedSession()
.carthage_downloadWithRequest(request)
.map { URL, _ in URL }
}
| e2389ae9bbcf102c4d02bcf90839e524 | 30.400641 | 162 | 0.703583 | false | false | false | false |
fleurdeswift/code-editor | refs/heads/master | CodeEditorCoreTests/ControllerTests.swift | mit | 1 | //
// ControllerTests.swift
// CodeEditorCore
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import XCTest
import CodeEditorCore;
class ControllerTests : XCTestCase {
func testMovePositionsForward(range: PositionRange, position: Position) -> Position {
var p = position;
XCTAssertFalse(Controller.movePositionsForward(range, position: &p));
return p;
}
func testMovePositionsForward() {
XCTAssertEqual(testMovePositionsForward(PositionRange(0, 0, 0, 1), position: Position(line: 0, column: 0)), Position(line: 0, column: 1));
XCTAssertEqual(testMovePositionsForward(PositionRange(0, 0, 1, 0), position: Position(line: 0, column: 0)), Position(line: 1, column: 0));
XCTAssertEqual(testMovePositionsForward(PositionRange(0, 0, 1, 0), position: Position(line: 2, column: 0)), Position(line: 3, column: 0));
XCTAssertEqual(testMovePositionsForward(PositionRange(1, 0, 2, 0), position: Position(line: 0, column: 0)), Position(line: 0, column: 0));
XCTAssertEqual(testMovePositionsForward(PositionRange(1, 1, 2, 0), position: Position(line: 1, column: 0)), Position(line: 1, column: 0));
XCTAssertEqual(testMovePositionsForward(PositionRange(1, 1, 1, 2), position: Position(line: 1, column: 3)), Position(line: 1, column: 4));
XCTAssertEqual(testMovePositionsForward(PositionRange(1, 1, 1, 2), position: Position(line: 1, column: 2)), Position(line: 1, column: 3));
}
func testMovePositionsBackward(range: PositionRange, position: Position) -> Position {
var p = position;
let willDiffer = Controller.movePositionsBackward(range, position: &p);
var np = p;
Controller.movePositionsForward(range, position: &np);
if willDiffer {
XCTAssertNotEqual(position, np);
}
else {
XCTAssertEqual(position, np);
}
return p;
}
func testMovePositionsBackward() {
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 0, 0, 1), position: Position(line: 0, column: 0)), Position(line: 0, column: 0));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 0, 2), position: Position(line: 0, column: 0)), Position(line: 0, column: 0));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 0, 2), position: Position(line: 0, column: 2)), Position(line: 0, column: 1));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 0, 8), position: Position(line: 0, column: 4)), Position(line: 0, column: 1));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 0, 1, 0), position: Position(line: 2, column: 0)), Position(line: 1, column: 0));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 0, 1, 8), position: Position(line: 1, column: 8)), Position(line: 0, column: 0));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 0, 1, 8), position: Position(line: 1, column: 9)), Position(line: 0, column: 1));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 1, 8), position: Position(line: 1, column: 9)), Position(line: 0, column: 2));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 0, 2, 0), position: Position(line: 1, column: 0)), Position(line: 0, column: 0));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 2, 1), position: Position(line: 1, column: 1)), Position(line: 0, column: 1));
XCTAssertEqual(testMovePositionsBackward(PositionRange(0, 1, 2, 2), position: Position(line: 2, column: 1)), Position(line: 0, column: 1));
}
func testMoveBackward() {
let doc = Document(defaultTextStyle: NSDictionary());
let controller = Controller(document: doc);
doc.addController(controller, strong: false);
defer { doc.removeController(controller); }
do {
try doc.modify() { (context: ModificationContext) in
try controller.type("a", context: context);
try controller.type("b", context: context);
try controller.type("c", context: context);
try controller.type("d", context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 4));
controller.moveCursorsBackward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 3));
controller.moveCursorsBackward(false, context: context);
controller.moveCursorsBackward(false, context: context);
controller.moveCursorsBackward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 0));
controller.moveCursorsBackward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 0));
controller.createCursor(.Edit, position: Position(line: 0, column: 0), context: context);
XCTAssertEqual(controller.cursors.count, 1);
controller.createCursor(.Edit, position: Position(line: 0, column: 1), context: context);
controller.createCursor(.Edit, position: Position(line: 0, column: 2), context: context);
controller.createCursor(.Edit, position: Position(line: 0, column: 3), context: context);
controller.createCursor(.Edit, position: Position(line: 0, column: 4), context: context);
XCTAssertEqual(controller.cursors.count, 5);
try controller.type("1", context: context);
XCTAssertEqual(doc.description(context), "1a1b1c1d1");
}
}
catch {
XCTFail();
}
}
func testMoveForward() {
let doc = Document(defaultTextStyle: NSDictionary());
let controller = Controller(document: doc);
doc.addController(controller, strong: false);
defer { doc.removeController(controller); }
do {
try doc.modify() { (context: ModificationContext) in
try controller.type("a", context: context);
try controller.type("b", context: context);
try controller.type("c", context: context);
try controller.type("d", context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 4));
controller.moveCursorsBackward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 3));
controller.moveCursorsForward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 4));
controller.moveCursorsForward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 4));
try controller.type("\n", context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 1, column: 0));
controller.moveCursorsBackward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 0, column: 4));
controller.moveCursorsForward(false, context: context);
XCTAssertEqual(controller.cursors[0].range.end, Position(line: 1, column: 0));
try controller.type("a", context: context);
try controller.type("b", context: context);
try controller.type("c", context: context);
try controller.type("d", context: context);
XCTAssertEqual(doc.description(context), "abcd\nabcd");
controller.setCursorPosition(Position(line: 0, column: 0), context: context);
controller.createCursor(.Edit, position: Position(line: 1, column: 0), context: context);
try controller.type(">", context: context);
XCTAssertEqual(doc.description(context), ">abcd\n>abcd");
controller.moveCursorsBackward(true, context: context);
try controller.type("@", context: context);
XCTAssertEqual(doc.description(context), "@abcd\n@abcd");
}
}
catch {
XCTFail();
}
}
func testDeleteDirectional() {
let doc = Document(defaultTextStyle: NSDictionary());
let controller = Controller(document: doc);
doc.addController(controller, strong: false);
defer { doc.removeController(controller); }
do {
try doc.modify() { (context: ModificationContext) in
try controller.type("a", context: context);
try controller.type("b", context: context);
try controller.type("c", context: context);
try controller.type("d", context: context);
controller.moveCursorsBackward(false, context: context);
controller.moveCursorsBackward(false, context: context);
try controller.deleteBackward(context);
try controller.deleteForward(context);
XCTAssertEqual(doc.description(context), "ad");
};
}
catch {
XCTFail();
}
}
}
| f9c46fb4e17d2ecba831dd55e2f93051 | 53.158192 | 147 | 0.613499 | false | true | false | false |
AlphaJian/LarsonApp | refs/heads/master | LarsonApp/LarsonApp/Class/JobDetail/Parts/JobPartsTableViewCell.swift | apache-2.0 | 1 | //
// JobPartsTableViewCell.swift
// LarsonApp
//
// Created by Jian Zhang on 11/8/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
class JobPartsTableViewCell: UITableViewCell {
@IBOutlet weak var partNameLbl: UILabel!
@IBOutlet weak var partInfoLbl: UILabel!
@IBOutlet weak var partQualityLbl: UILabel!
@IBOutlet weak var partNameLblHeight: NSLayoutConstraint!
var partModel : PartModel?
var indexPath : IndexPath?
var deleteHandler : CellTouchUpBlock?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func initUI(model : PartModel, index : IndexPath){
partModel = model
indexPath = index
let attrStr = NSMutableAttributedString(string: model.name)
attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13), range: NSMakeRange(0, model.name.characters.count))
let height = StringUtil.getAttributeString(str: attrStr, width: LCDW - 115)
partNameLblHeight.constant = height + 5
self.layoutIfNeeded()
partNameLbl.text = model.name
partInfoLbl.text = "#\(model.number) $\(model.price)"
}
@IBAction func deleteTapped(_ sender: AnyObject) {
if deleteHandler != nil
{
deleteHandler!(indexPath!, partModel!)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| ada6e27fa191db71e016f3c78d8ef33e | 29.346154 | 139 | 0.658428 | false | false | false | false |
zhxnlai/DongerListKeyboard | refs/heads/master | DongerListKeyboard/DLKeyboard/DLEmoticonCollectionView.swift | mit | 1 | //
// DLEmoticonCollectionView.swift
// DongerListKeyboard
//
// Created by Zhixuan Lai on 11/12/14.
// Copyright (c) 2014 Zhixuan Lai. All rights reserved.
//
import UIKit
class DLEmoticonCollectionView: UICollectionView {
override init() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 30)
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
layout.minimumLineSpacing = 0;
super.init(frame:CGRectZero, collectionViewLayout:layout)
self.registerClass(DLEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewIdentifier)
// self.categories = categories
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 6595612d4925eb19fd7add0183bbad6c | 30.666667 | 115 | 0.71345 | false | false | false | false |
gribozavr/swift | refs/heads/master | stdlib/public/core/StringStorage.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Having @objc stuff in an extension creates an ObjC category, which we don't
// want.
#if _runtime(_ObjC)
internal protocol _AbstractStringStorage: _NSCopying {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
var UTF16Length: Int { get }
}
#else
internal protocol _AbstractStringStorage {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
}
#endif
private typealias CountAndFlags = _StringObject.CountAndFlags
//
// TODO(String docs): Documentation about the runtime layout of these instances,
// which is a little complex. The second trailing allocation holds an
// Optional<_StringBreadcrumbs>.
//
// NOTE: older runtimes called this class _StringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __StringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
#if arch(i386) || arch(arm)
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
internal var _realCapacity: Int
internal var _count: Int
internal var _flags: UInt16
internal var _reserved: UInt16
@inline(__always)
internal var count: Int { return _count }
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
// The capacity of our allocation. Note that this includes the nul-terminator,
// which is not available for overriding.
internal var _realCapacityAndFlags: UInt64
internal var _countAndFlags: _StringObject.CountAndFlags
@inline(__always)
internal var count: Int { return _countAndFlags.count }
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
@inline(__always)
internal var _realCapacity: Int {
return Int(truncatingIfNeeded:
_realCapacityAndFlags & CountAndFlags.countMask)
}
#endif
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always)
get { return String(_StringGuts(self)) }
}
private init(_doNotCallMe: ()) {
_internalInvariantFailure("Use the create method")
}
deinit {
_breadcrumbsAddress.deinitialize(count: 1)
}
}
// Determine the actual number of code unit capacity to request from malloc. We
// round up the nearest multiple of 8 that isn't a mulitple of 16, to fully
// utilize malloc's small buckets while accounting for the trailing
// _StringBreadCrumbs.
//
// NOTE: We may still under-utilize the spare bytes from the actual allocation
// for Strings ~1KB or larger, though at this point we're well into our growth
// curve.
private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int {
#if arch(i386) || arch(arm)
// FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so
// that the instance size will be a multiple of 4.
let bias = Int(bitPattern: _StringObject.nativeBias)
let minimum = bias + desiredCapacity + 1
let size = (minimum + 3) & ~3
_internalInvariant(size % 4 == 0)
let capacity = size - bias
_internalInvariant(capacity > desiredCapacity)
return capacity
#else
// Bigger than _SmallString, and we need 1 extra for nul-terminator.
let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity)
_internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length")
// Round up to the nearest multiple of 8 that isn't also a multiple of 16.
let capacity = ((minCap + 7) & -16) + 8
_internalInvariant(
capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0)
return capacity
#endif
}
// Creation
extension __StringStorage {
@_effects(releasenone)
private static func create(
realCodeUnitCapacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
let storage = Builtin.allocWithTailElems_2(
__StringStorage.self,
realCodeUnitCapacity._builtinWordValue, UInt8.self,
1._builtinWordValue, Optional<_StringBreadcrumbs>.self)
#if arch(i386) || arch(arm)
storage._realCapacity = realCodeUnitCapacity
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._realCapacityAndFlags =
UInt64(truncatingIfNeeded: realCodeUnitCapacity)
storage._countAndFlags = countAndFlags
#endif
storage._breadcrumbsAddress.initialize(to: nil)
storage.terminator.pointee = 0 // nul-terminated
// NOTE: We can't _invariantCheck() now, because code units have not been
// initialized. But, _StringGuts's initializer will.
return storage
}
@_effects(releasenone)
private static func create(
capacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
_internalInvariant(capacity >= countAndFlags.count)
let realCapacity = determineCodeUnitCapacity(capacity)
_internalInvariant(realCapacity > capacity)
return __StringStorage.create(
realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags)
}
// The caller is expected to check UTF8 validity and ASCII-ness and update
// the resulting StringStorage accordingly
internal static func create(
uninitializedCapacity capacity: Int,
initializingUncheckedUTF8With initializer: (
_ buffer: UnsafeMutableBufferPointer<UInt8>
) throws -> Int
) rethrows -> __StringStorage {
let storage = __StringStorage.create(
capacity: capacity,
countAndFlags: CountAndFlags(mortalCount: 0, isASCII: false)
)
let buffer = UnsafeMutableBufferPointer(start: storage.mutableStart,
count: capacity)
let count = try initializer(buffer)
let countAndFlags = CountAndFlags(mortalCount: count, isASCII: false)
#if arch(i386) || arch(arm)
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._countAndFlags = countAndFlags
#endif
storage.terminator.pointee = 0 // nul-terminated
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>,
capacity: Int,
isASCII: Bool
) -> __StringStorage {
let countAndFlags = CountAndFlags(
mortalCount: bufPtr.count, isASCII: isASCII)
_internalInvariant(capacity >= bufPtr.count)
let storage = __StringStorage.create(
capacity: capacity, countAndFlags: countAndFlags)
let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
storage.mutableStart.initialize(from: addr, count: bufPtr.count)
storage._invariantCheck()
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool
) -> __StringStorage {
return __StringStorage.create(
initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII)
}
}
// Usage
extension __StringStorage {
@inline(__always)
private var mutableStart: UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self))
}
@inline(__always)
private var mutableEnd: UnsafeMutablePointer<UInt8> {
return mutableStart + count
}
@inline(__always)
internal var start: UnsafePointer<UInt8> {
return UnsafePointer(mutableStart)
}
@inline(__always)
private final var end: UnsafePointer<UInt8> {
return UnsafePointer(mutableEnd)
}
// Point to the nul-terminator.
@inline(__always)
private final var terminator: UnsafeMutablePointer<UInt8> {
return mutableEnd
}
@inline(__always)
internal var codeUnits: UnsafeBufferPointer<UInt8> {
return UnsafeBufferPointer(start: start, count: count)
}
// @opaque
internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> {
let raw = Builtin.getTailAddr_Word(
start._rawValue,
_realCapacity._builtinWordValue,
UInt8.self,
Optional<_StringBreadcrumbs>.self)
return UnsafeMutablePointer(raw)
}
// The total capacity available for code units. Note that this excludes the
// required nul-terminator.
internal var capacity: Int {
return _realCapacity &- 1
}
// The unused capacity available for appending. Note that this excludes the
// required nul-terminator.
//
// NOTE: Callers who wish to mutate this storage should enfore nul-termination
@inline(__always)
private var unusedStorage: UnsafeMutableBufferPointer<UInt8> {
return UnsafeMutableBufferPointer(
start: mutableEnd, count: unusedCapacity)
}
// The capacity available for appending. Note that this excludes the required
// nul-terminator.
internal var unusedCapacity: Int { return _realCapacity &- count &- 1 }
#if !INTERNAL_CHECKS_ENABLED
@inline(__always) internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self))
let rawStart = UnsafeRawPointer(start)
_internalInvariant(unusedCapacity >= 0)
_internalInvariant(count <= capacity)
_internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart)
_internalInvariant(self._realCapacity > self.count, "no room for nul-terminator")
_internalInvariant(self.terminator.pointee == 0, "not nul terminated")
let str = asString
_internalInvariant(str._guts._object.isPreferredRepresentation)
_countAndFlags._invariantCheck()
if isASCII {
_internalInvariant(_allASCII(self.codeUnits))
}
if let crumbs = _breadcrumbsAddress.pointee {
crumbs._invariantCheck(for: self.asString)
}
_internalInvariant(_countAndFlags.isNativelyStored)
_internalInvariant(_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
// Appending
extension __StringStorage {
// Perform common post-RRC adjustments and invariant enforcement.
@_effects(releasenone)
internal func _updateCountAndFlags(newCount: Int, newIsASCII: Bool) {
let countAndFlags = CountAndFlags(
mortalCount: newCount, isASCII: newIsASCII)
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
self.terminator.pointee = 0
// TODO(String performance): Consider updating breadcrumbs when feasible.
self._breadcrumbsAddress.pointee = nil
_invariantCheck()
}
// Perform common post-append adjustments and invariant enforcement.
@_effects(releasenone)
private func _postAppendAdjust(
appendedCount: Int, appendedIsASCII isASCII: Bool
) {
let oldTerminator = self.terminator
_updateCountAndFlags(
newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII)
_internalInvariant(oldTerminator + appendedCount == self.terminator)
}
@_effects(releasenone)
internal func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
_internalInvariant(self.capacity >= other.count)
let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked
let srcCount = other.count
self.mutableEnd.initialize(from: srcAddr, count: srcCount)
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
@_effects(releasenone)
internal func appendInPlace<Iter: IteratorProtocol>(
_ other: inout Iter, isASCII: Bool
) where Iter.Element == UInt8 {
var srcCount = 0
while let cu = other.next() {
_internalInvariant(self.unusedCapacity >= 1)
unusedStorage[srcCount] = cu
srcCount += 1
}
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
internal func clear() {
_updateCountAndFlags(newCount: 0, newIsASCII: true)
}
}
// Removing
extension __StringStorage {
@_effects(releasenone)
internal func remove(from lower: Int, to upper: Int) {
_internalInvariant(lower <= upper)
let lowerPtr = mutableStart + lower
let upperPtr = mutableStart + upper
let tailCount = mutableEnd - upperPtr
lowerPtr.moveInitialize(from: upperPtr, count: tailCount)
_updateCountAndFlags(
newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII)
}
// Reposition a tail of this storage from src to dst. Returns the length of
// the tail.
@_effects(releasenone)
internal func _slideTail(
src: UnsafeMutablePointer<UInt8>,
dst: UnsafeMutablePointer<UInt8>
) -> Int {
_internalInvariant(dst >= mutableStart && src <= mutableEnd)
let tailCount = mutableEnd - src
dst.moveInitialize(from: src, count: tailCount)
return tailCount
}
@_effects(releasenone)
internal func replace(
from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8>
) {
_internalInvariant(lower <= upper)
let replCount = replacement.count
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
lowerPtr.moveInitialize(
from: UnsafeMutablePointer(
mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked),
count: replCount)
let isASCII = self.isASCII && _allASCII(replacement)
_updateCountAndFlags(newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
@_effects(releasenone)
internal func replace<C: Collection>(
from lower: Int,
to upper: Int,
with replacement: C,
replacementCount replCount: Int
) where C.Element == UInt8 {
_internalInvariant(lower <= upper)
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
var isASCII = self.isASCII
var srcCount = 0
for cu in replacement {
if cu >= 0x80 { isASCII = false }
lowerPtr[srcCount] = cu
srcCount += 1
}
_internalInvariant(srcCount == replCount)
_updateCountAndFlags(
newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
}
// For shared storage and bridging literals
// NOTE: older runtimes called this class _SharedStringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __SharedStringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
internal var _owner: AnyObject?
internal var start: UnsafePointer<UInt8>
#if arch(i386) || arch(arm)
internal var _count: Int
internal var _flags: UInt16
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
internal var _countAndFlags: _StringObject.CountAndFlags
#endif
internal var _breadcrumbs: _StringBreadcrumbs? = nil
internal var count: Int { return _countAndFlags.count }
internal init(
immortal ptr: UnsafePointer<UInt8>,
countAndFlags: _StringObject.CountAndFlags
) {
self._owner = nil
self.start = ptr
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
super.init()
self._invariantCheck()
}
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
}
extension __SharedStringStorage {
#if !INTERNAL_CHECKS_ENABLED
@inline(__always)
internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
if let crumbs = _breadcrumbs {
crumbs._invariantCheck(for: self.asString)
}
_countAndFlags._invariantCheck()
_internalInvariant(!_countAndFlags.isNativelyStored)
_internalInvariant(!_countAndFlags.isTailAllocated)
let str = asString
_internalInvariant(!str._guts._object.isPreferredRepresentation)
}
#endif // INTERNAL_CHECKS_ENABLED
}
| 7e6836936f826fe9025c52290012a501 | 31.028626 | 86 | 0.707204 | false | false | false | false |
jbennett/Bugology | refs/heads/master | Bugology/ProjectsCoordinator.swift | mit | 1 | //
// ProjectsCoordinator.swift
// Bugology
//
// Created by Jonathan Bennett on 2016-01-18.
// Copyright © 2016 Jonathan Bennett. All rights reserved.
//
import UIKit
import BugKit
import BugUIKit
public class ProjectsCoordinator {
public weak var delegate: ProjectsCoordinatorDelegate?
let presentationContext: PresentationContext
public init(presentationContext: PresentationContext) {
self.presentationContext = presentationContext
}
public func showProjectsForAccount(account: Account, client: Client) {
let viewController = ProjectsViewController()
viewController.delegate = self
viewController.account = account
viewController.client = client
presentationContext.setStyleForService(account.serviceType)
presentationContext.showViewController(viewController, sender: nil)
}
}
extension ProjectsCoordinator: ProjectsViewControllerDelegate {
public func projectsViewController(projectsViewController: ProjectsViewController, didSelectProject project: Project) {
delegate?.projectsCoordinator(self, didSelectProject: project, inAccount: projectsViewController.account)
}
}
public protocol ProjectsCoordinatorDelegate: class {
func projectsCoordinator(projectsCoordinator: ProjectsCoordinator, didSelectProject project: Project, inAccount account: Account)
}
| 724a1dc7a077ad6ab887b8ea2664d61f | 27.869565 | 131 | 0.801958 | false | false | false | false |
elationfoundation/Reporta-iOS | refs/heads/master | IWMF/Helper/CommonLocation.swift | gpl-3.0 | 1 | //
// CommonLocation.swift
// IWMF
//
// This class is used for fetch user's current location. If location services are not enabled than it retuns location of New York or User's last known location.
//
//
import UIKit
import CoreLocation
class CommonLocation: NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
func intializeLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
let authstate = CLLocationManager.authorizationStatus()
if(authstate == CLAuthorizationStatus.NotDetermined){
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
func getUserCurrentLocation(){
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location : CLLocation = locations.first {
if(location.horizontalAccuracy > 0){
NSNotificationCenter.defaultCenter().postNotificationName(Structures.Constant.LocationUpdate, object:location)
Structures.Constant.appDelegate.prefrence.UsersLastKnownLocation[Structures.Constant.Latitude] = NSNumber(double: location.coordinate.latitude)
Structures.Constant.appDelegate.prefrence.UsersLastKnownLocation[Structures.Constant.Longitude] = NSNumber(double: location.coordinate.longitude)
AppPrefrences.saveAppPrefrences(Structures.Constant.appDelegate.prefrence)
locationManager.stopUpdatingLocation()
}
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
let location = Utility.getUsersLastKnownLocation() as CLLocation
NSNotificationCenter.defaultCenter().postNotificationName(Structures.Constant.LocationUpdate, object:location)
}
}
| d93fe2687475b518eaae2624c95f3362 | 44.204082 | 161 | 0.720993 | false | false | false | false |
aamct2/MCTDataStructures | refs/heads/master | Sources/MCTDataStructures/MCTDeque.swift | mit | 1 | //
// MCTDeque.swift
// MCTDataStructures
//
// Created by opensource on 8/19/15.
// Copyright © 2015 Aaron McTavish. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Generic implementation of a double-ended queue collection.
public struct MCTDeque<Element: CustomStringConvertible>: CustomStringConvertible, Sequence {
// MARK: - Properties
/// Underlying container (array) representation of deque.
fileprivate var items = [Element]()
/// The number of elements in the deque.
public var size: Int {
return items.count
}
/// Test whether the deque is empty.
public var empty: Bool {
return items.isEmpty
}
// MARK: - Initializers
public init() {}
// MARK: - C++11 Functions
/**
Remove the last element of the deque.
- returns: The last element of the deque, if it exists.
*/
public mutating func pop_back() -> Element? {
if empty {
return nil
}
return items.remove(at: size - 1)
}
/**
Remove the first element of the deque.
- returns: The first element of the deque, if it exists.
*/
public mutating func pop_front() -> Element? {
if empty {
return nil
}
return items.remove(at: 0)
}
/**
Insert element at the end of the deque.
- parameter newObject: Element to push onto the deque.
*/
public mutating func push_back(_ newObject: Element) {
items.append(newObject)
}
/**
Insert element at the beginning of the deque.
- parameter newObject: Element to push onto the deque.
*/
public mutating func push_front(_ newObject: Element) {
items.insert(newObject, at: 0)
}
/**
Access the next element of the deque without removing it.
- returns: The next element of the deque, if it exists.
*/
public func front() -> Element? {
if empty {
return nil
}
return items[0]
}
/**
Access the last element of the deque without removing it.
- returns: The last element of the deque, if it exists.
*/
public func back() -> Element? {
if empty {
return nil
}
return items[size - 1]
}
/**
Removes all elements from the deque.
*/
public mutating func clear() {
items.removeAll()
}
/**
Removes an element at a specific index.
- parameter index: Index at which to remove the element.
*/
public mutating func erase(_ index: Int) {
guard index >= 0 && index < size else {
return
}
items.remove(at: index)
}
/**
Removes a range of elements inclusive of the `startIndex` and exclusive of the `endIndex`.
Effectively, it is the range [`startIndex`, `endIndex`).
- parameter startIndex: Index of first object to remove.
- parameter endIndex: Index after the last object to remove.
*/
public mutating func erase(_ startIndex: Int, endIndex: Int) {
guard startIndex >= 0 && startIndex < size &&
endIndex > startIndex && endIndex <= size else { return }
items.removeSubrange(startIndex ..< endIndex)
}
}
// MARK: - Additional Convenience Functions
public extension MCTDeque {
/// A text representation of the deque.
public var description: String {
var result = ""
for curObject in items {
result += "::\(curObject)"
}
return result
}
/**
Returns a `MCTDeque` containing the elements of `self` in reverse order.
- returns: A `MCTDeque` containing the elements of `self` in reverse order.
*/
public func reverseDeque() -> MCTDeque<Element> {
var newDeque = MCTDeque<Element>()
newDeque.items = items.reversed()
return newDeque
}
/**
Returns the deque as an array object.
- returns: Array representation of the deque.
*/
public func dequeAsArray() -> [Element] {
return items
}
/// Return a *generator* over the elements.
///
/// - Complexity: O(1).
public func makeIterator() -> MCTDequeGenerator<Element> {
return MCTDequeGenerator<Element>(items: items[0 ..< items.count])
}
}
// MARK: - Deque Generator Type
public struct MCTDequeGenerator<Element> : IteratorProtocol {
public mutating func next() -> Element? {
if items.isEmpty {
return nil
}
let ret = items.first
items.removeFirst()
return ret
}
var items: ArraySlice<Element>
}
// MARK: - Relational Operators for Deques
/**
Returns true if these deques contain the same elements.
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: True if these deques contain the same elements. Otherwise returns false.
*/
public func ==<Element: Equatable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
guard lhs.size == rhs.size else {
return false
}
for index in 0 ..< lhs.size where lhs.items[index] != rhs.items[index] {
return false
}
return true
}
/**
Returns result of equivalent operation !(lhs == rhs).
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: Returns result of equivalent operation !(lhs == rhs).
*/
public func !=<Element: Equatable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
return !(lhs == rhs)
}
/**
Compares elements sequentially using operator< and stops at the first occurance where a<b or b<a.
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: Returns true if the first element in which the deques differ,
the left hand element is less than the right hand element. Otherwise returns false.
*/
public func <<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
for index in 0 ..< lhs.size {
if index >= rhs.size {
return false
}
if lhs.items[index] < rhs.items[index] {
return true
} else if rhs.items[index] < lhs.items[index] {
return false
}
}
return false
}
/**
Returns result of equivalent operation rhs < lhs.
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: Returns result of equivalent operation rhs < lhs.
*/
public func ><Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
return rhs < lhs
}
/**
Returns result of equivalent operation !(rhs < lhs).
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: Returns result of equivalent operation !(rhs < lhs).
*/
public func <=<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
return !(rhs < lhs)
}
/**
Returns result of equivalent operation !(lhs < rhs).
- parameter lhs: The left-hand deque.
- parameter rhs: The right-hand deque.
- returns: Returns result of equivalent operation !(lhs < rhs).
*/
public func >=<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool {
return !(lhs < rhs)
}
| da75a8d002cbed73b65c1b6220269f6c | 25.785489 | 97 | 0.623955 | false | false | false | false |
ryuichis/swift-ast | refs/heads/master | Sources/AST/Expression/TernaryConditionalOperatorExpression.swift | apache-2.0 | 2 | /*
Copyright 2016-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 TernaryConditionalOperatorExpression : ASTNode, BinaryExpression {
public let conditionExpression: Expression
public let trueExpression: Expression
public let falseExpression: Expression
public init(
conditionExpression: Expression,
trueExpression: Expression,
falseExpression: Expression
) {
self.conditionExpression = conditionExpression
self.trueExpression = trueExpression
self.falseExpression = falseExpression
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
let condText = conditionExpression.textDescription
let trueText = trueExpression.textDescription
let falseText = falseExpression.textDescription
return "\(condText) ? \(trueText) : \(falseText)"
}
}
| deba2479f542516ea3b56aed2ba9e5b3 | 34.475 | 90 | 0.763918 | false | false | false | false |
iOS-Swift-Developers/Swift | refs/heads/master | 实战前技术点/1.OOP到POP/OOP到POP/User.swift | mit | 1 | //
// User.swift
// OOP到POP
//
// Created by 韩俊强 on 2017/7/17.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
struct User {
var name : String = ""
var message : String = ""
init?(data : Data) {
guard let dictT = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] else {
return nil
}
let dict = dictT?["args"] as? [String : Any]
guard let name = dict?["username"] as? String else {
return nil
}
guard let message = dict?["age"] as? String else {
return nil
}
self.name = name
self.message = message
}
}
extension User: Decodable {
static func parse(_ data: Data) -> User? {
return User(data: data)
}
}
| 2a04b3c11b7ad86d60bed4c67250ae0b | 18.767442 | 126 | 0.523529 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Scripts/Localize.swift | mit | 1 | #!/usr/bin/env xcrun --sdk macosx swift
// swiftlint:disable all
import Foundation
// WHAT
// 1. Find Missing keys in other Localisation files
// 2. Find potentially untranslated keys
// 3. Find Duplicate keys
// 4. Find Unused keys and generate script to delete them all at once
// MARK: Start Of Configurable Section
/*
You can enable or disable the script whenever you want
*/
let enabled = true
/*
Flag to determine whether unused strings should be an error
*/
let careAboutUnused = false
/*
Flag to determine whether potentially untranslated strings should be a warning
*/
let careAboutUntranslated = false
/*
Put your path here, example -> Resources/Localizations/Languages
*/
let relativeLocalizableFolders = "/Rocket.Chat/Resources"
/*
This is the path of your source folder which will be used in searching
for the localization keys you actually use in your project
*/
let relativeSourceFolder = "/Rocket.Chat"
/*
Those are the regex patterns to recognize localizations.
*/
let patterns = [
"NSLocalized(Format)?String\\(\\s*@?\"([\\w\\.]+)\"", // Swift and Objc Native
"Localizations\\.((?:[A-Z]{1}[a-z]*[A-z]*)*(?:\\.[A-Z]{1}[a-z]*[A-z]*)*)", // Laurine Calls
"L10n.tr\\(key: \"(\\w+)\"", // SwiftGen generation
"ypLocalized\\(\"(.*)\"\\)",
"\"(.*)\".localized" // "key".localized pattern
]
/*
Those are the keys you don't want to be recognized as "unused"
For instance, Keys that you concatenate will not be detected by the parsing
so you want to add them here in order not to create false positives :)
*/
let ignoredFromUnusedKeys = [String]()
/* example
let ignoredFromUnusedKeys = [
"NotificationNoOne",
"NotificationCommentPhoto",
"NotificationCommentHisPhoto",
"NotificationCommentHerPhoto"
]
*/
let masterLanguage = "en"
/*
Sanitizing files will remove comments, empty lines and order your keys alphabetically.
*/
let sanitizeFiles = false
/*
Determines if there are multiple localizations or not.
*/
let singleLanguage = false
// MARK: End Of Configurable Section
// MARK: -
if enabled == false {
print("Localization check cancelled")
exit(000)
}
// Detect list of supported languages automatically
func listSupportedLanguages() -> [String] {
var sl = [String]()
let path = FileManager.default.currentDirectoryPath + relativeLocalizableFolders
if !FileManager.default.fileExists(atPath: path) {
print("Invalid configuration: \(path) does not exist.")
exit(1)
}
let enumerator: FileManager.DirectoryEnumerator? = FileManager.default.enumerator(atPath: path)
let extensionName = "lproj"
print("Found these languages:")
while let element = enumerator?.nextObject() as? String {
if element.hasSuffix(extensionName) {
print(element)
let name = element.replacingOccurrences(of: ".\(extensionName)", with: "")
sl.append(name)
}
}
return sl
}
let supportedLanguages = listSupportedLanguages()
var ignoredFromSameTranslation = [String:[String]]()
let path = FileManager.default.currentDirectoryPath + relativeLocalizableFolders
var numberOfWarnings = 0
var numberOfErrors = 0
struct LocalizationFiles {
var name = ""
var keyValue = [String:String]()
var linesNumbers = [String:Int]()
init(name: String) {
self.name = name
process()
}
mutating func process() {
if sanitizeFiles {
removeCommentsFromFile()
removeEmptyLinesFromFile()
sortLinesAlphabetically()
}
let location = singleLanguage ? "\(path)/Localizable.strings" : "\(path)/\(name).lproj/Localizable.strings"
if let string = try? String(contentsOfFile: location, encoding: .utf8) {
let lines = string.components(separatedBy: CharacterSet.newlines)
keyValue = [String:String]()
let pattern = "\"(.*)\" = \"(.+)\";"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
var ignoredTranslation = [String]()
for (lineNumber, line) in lines.enumerated() {
let range = NSRange(location:0, length:(line as NSString).length)
// Ignored pattern
let ignoredPattern = "\"(.*)\" = \"(.+)\"; *\\/\\/ *ignore-same-translation-warning"
let ignoredRegex = try? NSRegularExpression(pattern: ignoredPattern, options: [])
if let ignoredMatch = ignoredRegex?.firstMatch(in:line,
options: [],
range: range) {
let key = (line as NSString).substring(with: ignoredMatch.range(at:1))
ignoredTranslation.append(key)
}
if let firstMatch = regex?.firstMatch(in: line, options: [], range: range) {
let key = (line as NSString).substring(with: firstMatch.range(at:1))
let value = (line as NSString).substring(with: firstMatch.range(at:2))
if let _ = keyValue[key] {
let str = "\(path)/\(name).lproj"
+ "/Localizable.strings:\(linesNumbers[key]!): "
+ "error: [Redundance] \"\(key)\" "
+ "is redundant in \(name.uppercased()) file"
print(str)
numberOfErrors += 1
} else {
keyValue[key] = value
linesNumbers[key] = lineNumber+1
}
}
}
print(ignoredFromSameTranslation)
ignoredFromSameTranslation[name] = ignoredTranslation
}
}
func rebuildFileString(from lines: [String]) -> String {
return lines.reduce("") { (r: String, s: String) -> String in
return (r == "") ? (r + s) : (r + "\n" + s)
}
}
func removeEmptyLinesFromFile() {
let location = "\(path)/\(name).lproj/Localizable.strings"
if let string = try? String(contentsOfFile: location, encoding: .utf8) {
var lines = string.components(separatedBy: CharacterSet.newlines)
lines = lines.filter { $0.trimmingCharacters(in: CharacterSet.whitespaces) != "" }
let s = rebuildFileString(from: lines)
try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8)
}
}
func removeCommentsFromFile() {
let location = "\(path)/\(name).lproj/Localizable.strings"
if let string = try? String(contentsOfFile: location, encoding: .utf8) {
var lines = string.components(separatedBy: CharacterSet.newlines)
lines = lines.filter { !$0.hasPrefix("//") }
let s = rebuildFileString(from: lines)
try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8)
}
}
func sortLinesAlphabetically() {
let location = "\(path)/\(name).lproj/Localizable.strings"
if let string = try? String(contentsOfFile: location, encoding: .utf8) {
let lines = string.components(separatedBy: CharacterSet.newlines)
var s = ""
for (i,l) in sortAlphabetically(lines).enumerated() {
s += l
if (i != lines.count - 1) {
s += "\n"
}
}
try? s.write(toFile:location, atomically:false, encoding:String.Encoding.utf8)
}
}
func removeEmptyLinesFromLines(_ lines:[String]) -> [String] {
return lines.filter { $0.trimmingCharacters(in: CharacterSet.whitespaces) != "" }
}
func sortAlphabetically(_ lines:[String]) -> [String] {
return lines.sorted()
}
}
// MARK: - Load Localisation Files in memory
let masterLocalizationfile = LocalizationFiles(name: masterLanguage)
let localizationFiles = supportedLanguages
.filter { $0 != masterLanguage }
.map { LocalizationFiles(name: $0) }
// MARK: - Detect Unused Keys
let sourcesPath = FileManager.default.currentDirectoryPath + relativeSourceFolder
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(atPath:sourcesPath)
var localizedStrings = [String]()
while let swiftFileLocation = enumerator?.nextObject() as? String {
// checks the extension // TODO OBJC?
if swiftFileLocation.hasSuffix(".swift") || swiftFileLocation.hasSuffix(".m") || swiftFileLocation.hasSuffix(".mm") {
let location = "\(sourcesPath)/\(swiftFileLocation)"
if let string = try? String(contentsOfFile: location, encoding: .utf8) {
for p in patterns {
let regex = try? NSRegularExpression(pattern: p, options: [])
let range = NSRange(location:0, length:(string as NSString).length) //Obj c wa
regex?.enumerateMatches(in: string,
options: [],
range: range,
using: { (result, _, _) in
if let r = result {
let value = (string as NSString).substring(with:r.range(at:r.numberOfRanges-1))
localizedStrings.append(value)
}
})
}
}
}
}
var masterKeys = Set(masterLocalizationfile.keyValue.keys)
let usedKeys = Set(localizedStrings)
let ignored = Set(ignoredFromUnusedKeys)
let unused = masterKeys.subtracting(usedKeys).subtracting(ignored)
// Here generate Xcode regex Find and replace script to remove dead keys all at once!
var replaceCommand = "\"("
var counter = 0
if careAboutUnused {
for v in unused {
var str = "\(path)/\(masterLocalizationfile.name).lproj/Localizable.strings:\(masterLocalizationfile.linesNumbers[v]!): "
str += "error: [Unused Key] \"\(v)\" is never used"
print(str)
numberOfErrors += 1
if counter != 0 {
replaceCommand += "|"
}
replaceCommand += v
if counter == unused.count-1 {
replaceCommand += ")\" = \".*\";"
}
counter += 1
}
}
print(replaceCommand)
// MARK: - Compare each translation file against master (en)
for file in localizationFiles {
for k in masterLocalizationfile.keyValue.keys {
if let v = file.keyValue[k] {
if careAboutUntranslated && v == masterLocalizationfile.keyValue[k] {
if !ignoredFromSameTranslation[file.name]!.contains(k) {
let str = "\(path)/\(file.name).lproj/Localizable.strings"
+ ":\(file.linesNumbers[k]!): "
+ "warning: [Potentialy Untranslated] \"\(k)\""
+ "in \(file.name.uppercased()) file doesn't seem to be localized"
print(str)
numberOfWarnings += 1
}
}
} else {
var str = "\(path)/\(file.name).lproj/Localizable.strings:\(masterLocalizationfile.linesNumbers[k]!): "
str += "error: [Missing] \"\(k)\" missing form \(file.name.uppercased()) file"
print(str)
numberOfErrors += 1
}
}
}
print("Number of warnings : \(numberOfWarnings)")
print("Number of errors : \(numberOfErrors)")
if numberOfErrors > 0 {
exit(1)
}
// swiftlint:enable all
| 7852e51b03393375b7da07717b43473c | 34.480243 | 129 | 0.582455 | false | false | false | false |
BearchInc/Koloda | refs/heads/master | Example/Koloda/ViewController.swift | mit | 17 | //
// ViewController.swift
// TinderCardsSwift
//
// Created by Eugene Andreyev on 4/23/15.
// Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//
import UIKit
import Koloda
import pop
private var numberOfCards: UInt = 5
class ViewController: UIViewController, KolodaViewDataSource, KolodaViewDelegate {
@IBOutlet weak var kolodaView: KolodaView!
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
kolodaView.dataSource = self
kolodaView.delegate = self
self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
}
//MARK: IBActions
@IBAction func leftButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Left)
}
@IBAction func rightButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Right)
}
@IBAction func undoButtonTapped() {
kolodaView?.revertAction()
}
//MARK: KolodaViewDataSource
func kolodaNumberOfCards(koloda: KolodaView) -> UInt {
return numberOfCards
}
func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView {
return UIImageView(image: UIImage(named: "Card_like_\(index + 1)"))
}
func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? {
return NSBundle.mainBundle().loadNibNamed("OverlayView",
owner: self, options: nil)[0] as? OverlayView
}
//MARK: KolodaViewDelegate
func kolodaDidSwipedCardAtIndex(koloda: KolodaView, index: UInt, direction: SwipeResultDirection) {
//Example: loading more cards
if index >= 3 {
numberOfCards = 6
kolodaView.reloadData()
}
}
func kolodaDidRunOutOfCards(koloda: KolodaView) {
//Example: reloading
kolodaView.resetCurrentCardNumber()
}
func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://yalantis.com/")!)
}
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool {
return true
}
func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool {
return true
}
func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool {
return true
}
func kolodaBackgroundCardAnimation(koloda: KolodaView) -> POPPropertyAnimation? {
return nil
}
}
| 2cdb93f79f847df805ee04e7ebf50d5d | 26.086957 | 103 | 0.655698 | false | false | false | false |
xivol/MCS-V3-Mobile | refs/heads/master | assignments/task2/calculator/calculator/Calculator.swift | mit | 1 | //
// Calculator.swift
// calculator
//
// Created by Илья Лошкарёв on 21.09.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Foundation
enum Operation: String {
case add = "+",
sub = "-",
mul = "×",
div = "÷",
sign = "±",
perc = "%"
}
protocol Calculator: class {
var delegate: CalculatorDelegate? { get set }
init(inputLength len: UInt, fractionLength frac: UInt)
func addDigit(_ d: Int) // add digit to right value
func addPoint() // add point to right value
func addOperation(_ op: Operation) // add operation
func compute() // calculate result
func clear(); // clear right value
func reset(); // clear all data
var result: Double? { get } // current left value
var input: Double? { get } // current right value
var hasPoint: Bool { get } // current right value has point
var fractionDigits: UInt { get } // number of fraction digits in the right value
}
| e81945828cfde9b610a4e66246bbb4c2 | 24.897436 | 85 | 0.60099 | false | false | false | false |
ktmswzw/FeelClient | refs/heads/master | FeelingClient/common/utils/ImageUtils.swift | mit | 1 | //
// ImageUtils.swift
// feeling
//
// Created by vincent on 15/12/29.
// Copyright © 2015年 xecoder. All rights reserved.
//
import Foundation
import Photos
import UIKit
import ObjectMapper
func getImageFromPHAsset(asset: PHAsset) -> UIImage {
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.synchronous = true
manager.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.synchronous = true
manager.requestImageForAsset(asset, targetSize: CGSize(width: 50, height: 50), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
func imageResize (image:UIImage, sizeChange:CGSize)-> UIImage{
let hasAlpha = true
let scale: CGFloat = 0.0 // Use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage
}
let YUN = "http://habit-10005997.image.myqcloud.com";
/**
* 获取完整路径
* @return
*/
func getPath(url:String) -> String {
return "\(YUN)/" + url;
}
/**
* 获取完整路径small
* @return
*/
func getPathSmall(url:String) -> String {
return getPath(url) + "/small";
}
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiateWithOwner(nil, options: nil).first as? UIView
}
}
extension UITextField {
var notEmpty: Bool{
get {
return self.text != ""
}
}
func validate(RegEx: String) -> Bool {
let predicate = NSPredicate(format: "SELF MATCHES %@", RegEx)
return predicate.evaluateWithObject(self.text)
}
func validateEmail() -> Bool {
return self.validate("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}")
}
func validatePhoneNumber() -> Bool {
return self.validate("^\\d{11}$")
}
func validatePassword() -> Bool {
return self.validate("^[A-Z0-9a-z]{6,18}")
}
}
extension UIViewController {
/**
* Called when 'return' key pressed. return NO to ignore.
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
extension UIButton {
func disable() {
self.enabled = false
self.alpha = 0.5
}
func enable() {
self.enabled = true
self.alpha = 1
}
}
extension UITabBarController {
override public func preferredStatusBarStyle() -> UIStatusBarStyle {
guard selectedViewController != nil else { return .Default }
return selectedViewController!.preferredStatusBarStyle()
}
}
extension UINavigationController {
override public func preferredStatusBarStyle() -> UIStatusBarStyle {
if self.presentingViewController != nil {
// NavigationController的presentingViewController不会为nil时,通常意味着Modal
return self.presentingViewController!.preferredStatusBarStyle()
}
else {
guard self.topViewController != nil else { return .Default }
return (self.topViewController!.preferredStatusBarStyle());
}
}
}
| 3788ff69c5713c2c4fd3e36785c28975 | 25.715232 | 193 | 0.648984 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00184-swift-modulefile-lookupvalue.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var x1 = 1
var f1: Int -> Int = )
}
}lass func c()
}
cb() as ae.c()
var x1 = 1
=1 as a=1
s}
class a<f : b, : b where f.d == g> {
}
proto t
| e6f51e32465cb141b98d24cd8a01d5d8 | 26.15 | 79 | 0.679558 | false | false | false | false |
RxLeanCloud/rx-lean-swift | refs/heads/master | src/RxLeanCloudSwift/Public/RxAVSMS.swift | mit | 1 | //
// AVValidationSMS.swift
// RxLeanCloudSwift
//
// Created by WuJun on 14/12/2017.
// Copyright © 2017 LeanCloud. All rights reserved.
//
import Foundation
import RxSwift
public class AVSMS {
public var app: LeanCloudApp
public var mobilePhoneNumber: String = ""
public init(mobilePhoneNumber: String) {
self.mobilePhoneNumber = mobilePhoneNumber
self.app = RxAVClient.sharedInstance.takeApp(app: nil)
}
}
public class AVUserLogInSMS: AVSMS {
public func send() -> Observable<Bool> {
var payload = [String: Any]()
payload["mobilePhoneNumber"] = self.mobilePhoneNumber
let cmd = AVCommand(relativeUrl: "/requestLoginSmsCode", method: "POST", data: payload, app: self.app)
return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in
return avResponse.satusCode == 200
})
}
public var shortCode: String? = nil
public func setShortCode(receivedShortCode: String) {
self.shortCode = receivedShortCode
}
}
public class AVUserSignUpSMS: AVSMS {
public func send() -> Observable<Bool> {
var payload = [String: Any]()
payload["mobilePhoneNumber"] = self.mobilePhoneNumber
let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app)
return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in
return avResponse.satusCode == 200
})
}
public var shortCode: String? = nil
public func setShortCode(receivedShortCode: String) {
self.shortCode = receivedShortCode
}
}
public class AVValidationSMS: AVSMS {
public static func send(mobilePhoneNumber: String, ttl: Int = 10) -> Observable<Bool> {
return AVValidationSMS.send(mobilePhoneNumber: mobilePhoneNumber, appName: nil, operationName: nil)
}
public static func send(mobilePhoneNumber: String, appName: String?, operationName: String?, ttl: Int? = 10) -> Observable<Bool> {
let sms = AVValidationSMS(mobilePhoneNumber: mobilePhoneNumber, appName: appName, operationName: operationName, ttl: ttl)
return sms.send()
}
public var operationName: String? = nil
public var ttl: Int = 10
public var appName: String?
var shortCode: String? = nil
public init(mobilePhoneNumber: String, appName: String?, operationName: String?, ttl: Int?) {
self.operationName = operationName
self.appName = appName
if ttl != nil {
self.ttl = ttl!
}
super.init(mobilePhoneNumber: mobilePhoneNumber)
}
public func send() -> Observable<Bool> {
var payload = [String: Any]()
payload["mobilePhoneNumber"] = self.mobilePhoneNumber
if self.operationName != nil {
payload["op"] = self.operationName
}
if self.appName != nil {
payload["name"] = self.appName
}
if self.ttl != 10 {
payload["ttl"] = self.ttl
}
let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app)
return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in
return avResponse.satusCode == 200
})
}
public func setShortCode(receivedShortCode: String) {
self.shortCode = receivedShortCode
}
public func verify() -> Observable<Bool> {
if self.shortCode != nil {
let cmd = AVCommand(relativeUrl: "/verifySmsCode/\(String(describing: self.shortCode))?mobilePhoneNumber=\(self.mobilePhoneNumber)", method: "POST", data: nil, app: self.app)
return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in
return avResponse.satusCode == 200
})
}
return Observable.from([false])
}
}
public class AVNoticeSMS: AVSMS {
public init(mobilePhoneNumber: String, templateId: String, signatureId: String?, contentParameters: [String: Any]?) {
self.templateId = templateId
self.signatureId = signatureId
self.contentParameters = contentParameters
super.init(mobilePhoneNumber: mobilePhoneNumber)
}
public var templateId: String = ""
public var signatureId: String? = nil
public var contentParameters: [String: Any]? = nil
public func send() -> Observable<Bool> {
var payload = [String: Any]()
payload["mobilePhoneNumber"] = self.mobilePhoneNumber
payload["template"] = self.templateId
if self.signatureId != nil {
payload["sign"] = self.signatureId
}
if let env = contentParameters {
env.forEach({ (key, value) in
payload[key] = value
})
}
let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app)
return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in
return avResponse.satusCode == 200
})
}
}
| 80dfa3c141961abe42e65ae49c1108bb | 34.215278 | 186 | 0.638336 | false | false | false | false |
dzenbot/Iconic | refs/heads/master | Vendor/SwiftGen/GenumKit/Stencil/SwiftIdentifier.swift | mit | 1 | //
// GenumKit
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Foundation
func swiftIdentifier(fromString string: String, forbiddenChars exceptions: String = "", replaceWithUnderscores underscores: Bool = false) -> String {
let (head, tail) : (NSMutableCharacterSet, NSMutableCharacterSet) = {
let addRange: (NSMutableCharacterSet, Range<Int>) -> Void = { (mcs, range) in
mcs.addCharactersInRange(NSRange(location: range.startIndex, length: range.endIndex-range.startIndex))
}
let addChars: (NSMutableCharacterSet, String) -> Void = { (mcs, string) in
mcs.addCharactersInString(string)
}
// Official list from: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
let head = NSMutableCharacterSet()
addRange(head, 0x41...0x5A) // A-Z
addRange(head, 0x61...0x7A) // a-z
addChars(head, "_")
addChars(head, "\u{00A8}\u{00AA}\u{00AD}\u{00AF}")
addRange(head, 0x00B2...0x00B5)
addRange(head, 0x00B7...0x00BA)
addRange(head, 0x00BC...0x00BE)
addRange(head, 0x00C0...0x00D6)
addRange(head, 0x00D8...0x00F6)
addRange(head, 0x00F8...0x00FF)
addRange(head, 0x0100...0x02FF)
addRange(head, 0x0370...0x167F)
addRange(head, 0x1681...0x180D)
addRange(head, 0x180F...0x1DBF)
addRange(head, 0x1E00...0x1FFF)
addRange(head, 0x200B...0x200D)
addRange(head, 0x202A...0x202E)
addRange(head, 0x203F...0x2040)
addChars(head, "\u{2054}")
addRange(head, 0x2060...0x206F)
addRange(head, 0x2070...0x20CF)
addRange(head, 0x2100...0x218F)
addRange(head, 0x2460...0x24FF)
addRange(head, 0x2776...0x2793)
addRange(head, 0x2C00...0x2DFF)
addRange(head, 0x2E80...0x2FFF)
addRange(head, 0x3004...0x3007)
addRange(head, 0x3021...0x302F)
addRange(head, 0x3031...0x303F)
addRange(head, 0x3040...0xD7FF)
addRange(head, 0xF900...0xFD3D)
addRange(head, 0xFD40...0xFDCF)
addRange(head, 0xFDF0...0xFE1F)
addRange(head, 0xFE30...0xFE44)
addRange(head, 0xFE47...0xFFFD)
addRange(head, 0x10000...0x1FFFD)
addRange(head, 0x20000...0x2FFFD)
addRange(head, 0x30000...0x3FFFD)
addRange(head, 0x40000...0x4FFFD)
addRange(head, 0x50000...0x5FFFD)
addRange(head, 0x60000...0x6FFFD)
addRange(head, 0x70000...0x7FFFD)
addRange(head, 0x80000...0x8FFFD)
addRange(head, 0x90000...0x9FFFD)
addRange(head, 0xA0000...0xAFFFD)
addRange(head, 0xB0000...0xBFFFD)
addRange(head, 0xC0000...0xCFFFD)
addRange(head, 0xD0000...0xDFFFD)
addRange(head, 0xE0000...0xEFFFD)
let tail = head.mutableCopy() as! NSMutableCharacterSet
addChars(tail, "0123456789")
addRange(tail, 0x0300...0x036F)
addRange(tail, 0x1DC0...0x1DFF)
addRange(tail, 0x20D0...0x20FF)
addRange(tail, 0xFE20...0xFE2F)
return (head, tail)
}()
head.removeCharactersInString(exceptions)
tail.removeCharactersInString(exceptions)
let chars = string.unicodeScalars
let firstChar = chars[chars.startIndex]
let prefix = !head.longCharacterIsMember(firstChar.value) && tail.longCharacterIsMember(firstChar.value) ? "_" : ""
let parts = string.componentsSeparatedByCharactersInSet(tail.invertedSet)
let replacement = underscores ? "_" : ""
return prefix + parts.map({ string in
// Can't use capitalizedString here because it will lowercase all letters after the first
// e.g. "SomeNiceIdentifier".capitalizedString will because "Someniceidentifier" which is not what we want
let ns = string as NSString
if ns.length > 0 {
let firstLetter = ns.substringToIndex(1)
let rest = ns.substringFromIndex(1)
return firstLetter.uppercaseString + rest
} else {
return ""
}
}).joinWithSeparator(replacement)
}
| 451a8db60ae481614b36e772ccff3df1 | 36.754902 | 188 | 0.694105 | false | false | false | false |
kylef/RxHyperdrive | refs/heads/master | RxHyperdrive/RxHyperdrive.swift | mit | 1 | import RxSwift
import Hyperdrive
import Representor
extension Hyperdrive {
public func enter(uri:String) -> Observable<Representor<HTTPTransition>> {
return create { observer in
self.enter(uri) { result in
switch result {
case .Success(let representor):
observer.on(.Next(representor))
observer.on(.Completed)
case .Failure(let error):
observer.on(.Error(error))
}
}
return AnonymousDisposable {}
}
}
public func request(transition:HTTPTransition, parameters:[String:AnyObject]? = nil, attributes:[String:AnyObject]? = nil) -> Observable<Representor<HTTPTransition>> {
return create { observer in
self.request(transition, parameters: parameters, attributes: attributes) { result in
switch result {
case .Success(let representor):
observer.on(.Next(representor))
observer.on(.Completed)
case .Failure(let error):
observer.on(.Error(error))
}
}
return AnonymousDisposable {}
}
}
public func request(transition:HTTPTransition?, parameters:[String:AnyObject]? = nil, attributes:[String:AnyObject]? = nil) -> Observable<Representor<HTTPTransition>> {
if let transition = transition {
return request(transition, parameters: parameters, attributes: attributes)
}
return create { observer in
let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "Given transition was nil."])
observer.on(.Error(error))
return AnonymousDisposable {}
}
}
}
| 65be0685be5e2cfe77a0d440ec43113e | 32 | 170 | 0.664193 | false | false | false | false |
Subberbox/Subber-api | refs/heads/master | Sources/App/Middleware/LoggingMiddleware.swift | mit | 2 | //
// LoggingMiddleware.swift
// subber-api
//
// Created by Hakon Hanesand on 11/21/16.
//
//
import Foundation
import Vapor
import HTTP
import JSON
extension JSON {
var prettyString: String {
do {
return try String(bytes: serialize(prettyPrint: true))
} catch {
return "Error serializing json into string : \(error)"
}
}
}
extension Model {
var prettyString: String {
do {
return try makeJSON().prettyString
} catch {
return "Error making JSON from model : \(error)"
}
}
}
extension Status {
var isSuccessfulStatus: Bool {
return (statusCode > 199 && statusCode < 400) || statusCode == Status.conflict.statusCode
}
var description: String {
return "\(isSuccessfulStatus ? "Success" : "Failure") - \(statusCode) : \(reasonPhrase)"
}
}
class LoggingMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response: Response = try next.respond(to: request)
try log(request, response: response)
return response
}
func log(_ request: Request, response: Response) throws {
let failure = { (string: String?) in
if let string = string {
Droplet.logger?.error(string)
}
}
let info = { (string: String?) in
if let string = string {
Droplet.logger?.info(string)
}
}
let logger = response.status.isSuccessfulStatus ? info : failure
logger("")
logger("Request")
logger("URL : \(request.uri)")
logger("Headers : \(request.headers.description)")
if let json = request.json {
try logger("JSON : \(String(bytes: json.serialize(prettyPrint: true)))")
}
logger("Response - \(response.status.description)")
logger("")
}
}
| bb0c343feaf88c698d95ca451624e2a6 | 23.154762 | 97 | 0.552489 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SILGen/back_deploy_attribute_func.swift | apache-2.0 | 7 | // RUN: %target-swift-emit-sil -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 -verify
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.60 | %FileCheck %s
// REQUIRES: OS=macosx
// -- Fallback definition of trivialFunc()
// CHECK-LABEL: sil non_abi [serialized] [available 10.51] [ossa] @$s11back_deploy11trivialFuncyyFTwB : $@convention(thin) () -> ()
// CHECK: bb0:
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: return [[RESULT]] : $()
// -- Back deployment thunk for trivialFunc()
// CHECK-LABEL: sil non_abi [serialized] [thunk] [available 10.51] [ossa] @$s11back_deploy11trivialFuncyyFTwb : $@convention(thin) () -> ()
// CHECK: bb0:
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]]
//
// CHECK: [[UNAVAIL_BB]]:
// CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy11trivialFuncyyFTwB : $@convention(thin) () -> ()
// CHECK: {{%.*}} = apply [[FALLBACKFN]]() : $@convention(thin) () -> ()
// CHECK: br [[RETURN_BB:bb[0-9]+]]
//
// CHECK: [[AVAIL_BB]]:
// CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy11trivialFuncyyF : $@convention(thin) () -> ()
// CHECK: {{%.*}} = apply [[ORIGFN]]() : $@convention(thin) () -> ()
// CHECK: br [[RETURN_BB]]
//
// CHECK: [[RETURN_BB]]
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: return [[RESULT]] : $()
// -- Original definition of trivialFunc()
// CHECK-LABEL: sil [available 10.51] [ossa] @$s11back_deploy11trivialFuncyyF : $@convention(thin) () -> ()
@available(macOS 10.51, *)
@_backDeploy(before: macOS 10.52)
public func trivialFunc() {}
// -- Fallback definition of isNumber(_:)
// CHECK-LABEL: sil non_abi [serialized] [available 10.51] [ossa] @$s11back_deploy8isNumberySbSiFTwB : $@convention(thin) (Int) -> Bool
// CHECK: bb0([[ARG_X:%.*]] : $Int):
// ...
// CHECK: return {{%.*}} : $Bool
// -- Back deployment thunk for isNumber(_:)
// CHECK-LABEL: sil non_abi [serialized] [thunk] [available 10.51] [ossa] @$s11back_deploy8isNumberySbSiFTwb : $@convention(thin) (Int) -> Bool
// CHECK: bb0([[ARG_X:%.*]] : $Int):
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]]
//
// CHECK: [[UNAVAIL_BB]]:
// CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy8isNumberySbSiFTwB : $@convention(thin) (Int) -> Bool
// CHECK: [[RESULT:%.*]] = apply [[FALLBACKFN]]([[ARG_X]]) : $@convention(thin) (Int) -> Bool
// CHECK: br [[RETURN_BB:bb[0-9]+]]([[RESULT]] : $Bool)
//
// CHECK: [[AVAIL_BB]]:
// CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy8isNumberySbSiF : $@convention(thin) (Int) -> Bool
// CHECK: [[RESULT:%.*]] = apply [[ORIGFN]]([[ARG_X]]) : $@convention(thin) (Int) -> Bool
// CHECK: br [[RETURN_BB]]([[RESULT]] : $Bool)
//
// CHECK: [[RETURN_BB]]([[RETURN_BB_ARG:%.*]] : $Bool)
// CHECK: return [[RETURN_BB_ARG]] : $Bool
// -- Original definition of isNumber(_:)
// CHECK-LABEL: sil [available 10.51] [ossa] @$s11back_deploy8isNumberySbSiF : $@convention(thin) (Int) -> Bool
@available(macOS 10.51, *)
@_backDeploy(before: macOS 10.52)
public func isNumber(_ x: Int) -> Bool {
return true
}
// CHECK-LABEL: sil hidden [available 10.51] [ossa] @$s11back_deploy6calleryyF : $@convention(thin) () -> ()
@available(macOS 10.51, *)
func caller() {
// -- Verify the thunk is called
// CHECK: {{%.*}} = function_ref @$s11back_deploy11trivialFuncyyFTwb : $@convention(thin) () -> ()
trivialFunc()
// CHECK: {{%.*}} = function_ref @$s11back_deploy8isNumberySbSiFTwb : $@convention(thin) (Int) -> Bool
_ = isNumber(6)
}
| 8224e662d4bdb9c30316002620e85712 | 53.494382 | 167 | 0.62268 | false | false | false | false |
lieonCX/Hospital | refs/heads/master | Hospital/Hospital/View/News/GithubSignupVC.swift | mit | 1 | //
// GithubSignupVC.swift
// Hospital
//
// Created by lieon on 2017/5/9.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class GithubSignupVC: BaseViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidationOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidationOutlet: UILabel!
@IBOutlet weak var repeatedPasswordOutlet: UITextField!
@IBOutlet weak var repeatedPasswordValidationOutlet: UILabel!
@IBOutlet weak var signupOutlet: UIButton!
@IBOutlet weak var signingUpOulet: UIActivityIndicatorView!
private let usernameminLength: Int = 5
private let passwordminLength: Int = 6
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
fileprivate func setupUI() {
let signupVM = GithubSignupViewModel(
input: (
username: usernameOutlet.rx.text.orEmpty.asObservable(),
password: passwordOutlet.rx.text.orEmpty.asObservable(),
repeatPassword: repeatedPasswordOutlet.rx.text.orEmpty.asObservable(),
signupTaps: signupOutlet.rx.tap.asObservable()),
dependency: (
API: GithubDefaultAPI.sahred,
service: GitHubDefaultValidationService.shared)
)
signupVM.validatedUsername
.bind(to: usernameValidationOutlet.rx.validationResult)
.disposed(by: disposeBag)
signupVM.validatedPassword
.bind(to: passwordValidationOutlet.rx.validationResult)
.disposed(by: disposeBag)
signupVM.validatedRepeatPassword
.bind(to: repeatedPasswordValidationOutlet.rx.validationResult)
.disposed(by: disposeBag)
signupVM.signingin
.bind(to: signingUpOulet.rx.isAnimating)
.disposed(by: disposeBag)
signupVM.signedin
.subscribe(onNext: { signedIn in
print("User signed in \(signedIn)")
})
.disposed(by: disposeBag)
signupVM.signupEnable
.subscribe(onNext: { signed in
self.signupOutlet.isEnabled = signed
self.signupOutlet.alpha = signed ? 1.0 : 0.5
})
.disposed(by: disposeBag)
let tap = UITapGestureRecognizer()
tap.rx.event.subscribe(onNext: { [weak self] _ in
self?.view.endEditing(true)
}).disposed(by: disposeBag)
view.addGestureRecognizer(tap)
}
}
| 2db8d9ed81bef877b1be52db7ef716ad | 33.6875 | 106 | 0.607207 | false | false | false | false |
atrick/swift | refs/heads/main | test/IDE/complete_at_top_level.swift | apache-2.0 | 7 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
// NORESULT: Token
// NORESULT-NOT: Begin completions
// Test code completion in top-level code.
//
// This test is not meant to test that we can correctly form all kinds of
// completion results in general; that should be tested elsewhere.
var topLevelVar3 = #^TOP_LEVEL_VAR_INIT_3?check=TOP_LEVEL_VAR_INIT_3_NEGATIVE^#
// TOP_LEVEL_VAR_INIT_3_NEGATIVE-NOT: topLevelVar3
struct FooStruct {
var instanceVar = 0
func instanceFunc(_ a: Int) {}
// Add more stuff as needed.
}
var fooObject : FooStruct
func fooFunc1() {}
func fooFunc2(_ a: Int, _ b: Double) {}
func erroneous1(_ x: Undeclared) {}
// FIXME: Hides all other string interpolation completion.
//extension DefaultStringInterpolation {
// mutating func appendInterpolation(interpolate: Double) {}
//}
//===--- Test code completions of expressions that can be typechecked.
// Although the parser can recover in most of these test cases, we resync it
// anyway to ensure that there parser recovery does not interfere with code
// completion.
func resyncParser1() {}
fooObject#^TYPE_CHECKED_EXPR_1^#
// TYPE_CHECKED_EXPR_1: Begin completions
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: End completions
func resyncParser2() {}
// Test that we can code complete after a top-level var decl.
var _tmpVar1 : FooStruct
fooObject#^TYPE_CHECKED_EXPR_2^#
// TYPE_CHECKED_EXPR_2: Begin completions
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: End completions
func resyncParser3() {}
fooObject#^TYPE_CHECKED_EXPR_3^#.bar
// TYPE_CHECKED_EXPR_3: Begin completions
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: End completions
func resyncParser4() {}
fooObject.#^TYPE_CHECKED_EXPR_4^#
// TYPE_CHECKED_EXPR_4: Begin completions
// TYPE_CHECKED_EXPR_4-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: End completions
func resyncParser5() {}
fooObject.#^TYPE_CHECKED_EXPR_5^#.bar
// TYPE_CHECKED_EXPR_5: Begin completions
// TYPE_CHECKED_EXPR_5-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: End completions
func resyncParser6() {}
fooObject.instanceFunc(#^TYPE_CHECKED_EXPR_6?check=PLAIN_TOP_LEVEL^#
func resyncParser6() {}
fooObject.is#^TYPE_CHECKED_EXPR_KW_1?check=NORESULT^#
func resyncParser7() {}
// We have an error in the initializer here, but the type is explicitly written
// in the source.
var fooObjectWithErrorInInit : FooStruct = unknown_var
fooObjectWithErrorInInit.#^TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1^#
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1: Begin completions
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: End completions
func resyncParser6a() {}
var topLevelVar1 = #^TOP_LEVEL_VAR_INIT_1?check=TOP_LEVEL_VAR_INIT_1;check=TOP_LEVEL_VAR_INIT_1_NEGATIVE;check=NEGATIVE^#
// TOP_LEVEL_VAR_INIT_1: Begin completions
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1: End completions
// Check that the variable itself does not show up.
// TOP_LEVEL_VAR_INIT_1_NEGATIVE-NOT: topLevelVar1
func resyncParser7() {}
var topLevelVar2 = FooStruct#^TOP_LEVEL_VAR_INIT_2^#
// TOP_LEVEL_VAR_INIT_2: Begin completions
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(self): FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ()[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ({#instanceVar: Int#})[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ()[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct.Type#]; name=self
// TOP_LEVEL_VAR_INIT_2-NEXT: Keyword/CurrNominal: .Type[#FooStruct.Type#]; name=Type
// TOP_LEVEL_VAR_INIT_2-NEXT: End completions
func resyncParser8() {}
#^PLAIN_TOP_LEVEL_1?check=PLAIN_TOP_LEVEL;check=PLAIN_TOP_LEVEL_NO_DUPLICATES;check=NEGATIVE^#
// PLAIN_TOP_LEVEL: Begin completions
// PLAIN_TOP_LEVEL-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL: End completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES: Begin completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc2({#(a): Int#}, {#(b): Double#})[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc1
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc2
// PLAIN_TOP_LEVEL_NO_DUPLICATES: End completions
func resyncParser9() {}
// Test that we can code complete immediately after a decl with a syntax error.
func _tmpFuncWithSyntaxError() { if return }
#^PLAIN_TOP_LEVEL_2?check=PLAIN_TOP_LEVEL^#
func resyncParser10() {}
_ = {
#^TOP_LEVEL_CLOSURE_1^#
}()
// TOP_LEVEL_CLOSURE_1: Begin completions
// TOP_LEVEL_CLOSURE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1: End completions
func resyncParser11() {}
//===--- Test code completions of types.
func resyncParserA1() {}
var topLevelVarType1 : #^TOP_LEVEL_VAR_TYPE_1?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#
// TOP_LEVEL_VAR_TYPE_1: Begin completions
// TOP_LEVEL_VAR_TYPE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_TYPE_1: End completions
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[GlobalVar
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[FreeFunc
func resyncParserA1_1() {}
var topLevelVarType2 : [#^TOP_LEVEL_VAR_TYPE_2?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#]
func resyncParserA1_2() {}
var topLevelVarType3 : [#^TOP_LEVEL_VAR_TYPE_3?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#: Int]
func resyncParserA1_3() {}
var topLevelVarType4 : [Int: #^TOP_LEVEL_VAR_TYPE_4?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#]
func resyncParserA1_4() {}
if let topLevelVarType5 : [#^TOP_LEVEL_VAR_TYPE_5?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#] {}
func resyncParserA1_5() {}
guard let topLevelVarType6 : [#^TOP_LEVEL_VAR_TYPE_6?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#] else {}
func resyncParserA1_6() {}
_ = ("a" as #^TOP_LEVEL_EXPR_TYPE_1?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#)
func resyncParserA1_7() {}
_ = ("a" as! #^TOP_LEVEL_EXPR_TYPE_2?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#)
func resyncParserA1_8() {}
_ = ("a" as? #^TOP_LEVEL_EXPR_TYPE_3?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#)
func resyncParserA1_9() {}
_ = ("a" is #^TOP_LEVEL_EXPR_TYPE_4?check=TOP_LEVEL_VAR_TYPE_1;check=TOP_LEVEL_VAR_TYPE_NEGATIVE_1;check=NEGATIVE^#)
func resyncParserA2() {}
//===--- Test code completion in statements.
func resyncParserB1() {}
if (true) {
#^TOP_LEVEL_STMT_1?check=PLAIN_TOP_LEVEL^#
}
func resyncParserB2() {}
while (true) {
#^TOP_LEVEL_STMT_2?check=PLAIN_TOP_LEVEL^#
}
func resyncParserB3() {}
repeat {
#^TOP_LEVEL_STMT_3?check=PLAIN_TOP_LEVEL^#
} while true
func resyncParserB4() {}
for ; ; {
#^TOP_LEVEL_STMT_4?check=PLAIN_TOP_LEVEL^#
}
func resyncParserB5() {}
for var i = 0; ; {
#^TOP_LEVEL_STMT_5?check=PLAIN_TOP_LEVEL;check=TOP_LEVEL_STMT_5^#
// TOP_LEVEL_STMT_5: Begin completions
// TOP_LEVEL_STMT_5: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// TOP_LEVEL_STMT_5: End completions
}
func resyncParserB6() {}
for i in [] {
#^TOP_LEVEL_STMT_6?check=PLAIN_TOP_LEVEL;check=TOP_LEVEL_STMT_6^#
// TOP_LEVEL_STMT_6: Begin completions
// TOP_LEVEL_STMT_6: Decl[LocalVar]/Local: i[#Any#]{{; name=.+$}}
// TOP_LEVEL_STMT_6: End completions
}
func resyncParserB7() {}
for i in [1, 2, 3] {
#^TOP_LEVEL_STMT_7?check=PLAIN_TOP_LEVEL;check=TOP_LEVEL_STMT_7^#
// TOP_LEVEL_STMT_7: Begin completions
// TOP_LEVEL_STMT_7: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// TOP_LEVEL_STMT_7: End completions
}
func resyncParserB8() {}
for i in unknown_var {
#^TOP_LEVEL_STMT_8?check=PLAIN_TOP_LEVEL;check=TOP_LEVEL_STMT_8^#
// TOP_LEVEL_STMT_8: Begin completions
// TOP_LEVEL_STMT_8: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// TOP_LEVEL_STMT_8: End completions
}
func resyncParserB9() {}
switch (0, 42) {
case (0, 0):
#^TOP_LEVEL_STMT_9?check=PLAIN_TOP_LEVEL^#
}
func resyncParserB10() {}
// rdar://20738314
if true {
var z = #^TOP_LEVEL_STMT_10?check=PLAIN_TOP_LEVEL^#
} else {
assertionFailure("Shouldn't be here")
}
func resyncParserB11() {}
// rdar://21346928
func optStr() -> String? { return nil }
let x = (optStr() ?? "autoclosure").#^TOP_LEVEL_AUTOCLOSURE_1?check=AUTOCLOSURE_STRING^#
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal/IsSystem: unicodeScalars[#String.UnicodeScalarView#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal/IsSystem: utf16[#String.UTF16View#]
func resyncParserB12() {}
// rdar://21661308
switch 1 {
case #^TOP_LEVEL_SWITCH_CASE_1^#
}
// TOP_LEVEL_SWITCH_CASE_1: Begin completions
func resyncParserB13() {}
#^TOP_LEVEL_BEFORE_GUARD_NAME_1?check=TOP_LEVEL_BEFORE_GUARD_NAME^#
// TOP_LEVEL_BEFORE_GUARD_NAME-NOT: name=guardedName
guard let guardedName = 1 as Int? {
#^TOP_LEVEL_BEFORE_GUARD_NAME_2?check=TOP_LEVEL_BEFORE_GUARD_NAME^#
}
#^TOP_LEVEL_GUARD_1?check=TOP_LEVEL_GUARD^#
func interstitial() {}
#^TOP_LEVEL_GUARD_2?check=TOP_LEVEL_GUARD^#
// TOP_LEVEL_GUARD: Decl[LocalVar]/Local: guardedName[#Int#]; name=guardedName
func resyncParserB14() {}
"\(#^STRING_INTERP_1?check=STRING_INTERP^#)"
"\(1) \(#^STRING_INTERP_2?check=STRING_INTERP^#) \(2)"
var stringInterp = "\(#^STRING_INTERP_3?check=STRING_INTERP^#)"
_ = "" + "\(#^STRING_INTERP_4?check=STRING_INTERP^#)" + ""
// STRING_INTERP: Begin completions
// STRING_INTERP-DAG: Decl[InstanceMethod]/CurrNominal/Flair[ArgLabels]/IsSystem: ['(']{#(value): T#}[')'][#Void#];
// STRING_INTERP-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: FooStruct[#FooStruct#]; name=FooStruct
// STRING_INTERP-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: fooFunc1()[#Void#];
// STRING_INTERP-DAG: Decl[FreeFunction]/CurrModule: optStr()[#String?#];
// STRING_INTERP-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#];
// STRING_INTERP: End completions
func resyncParserC1() {}
// FOR_COLLECTION-NOT: forIndex
for forIndex in [#^FOR_COLLECTION_1?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#] {}
for forIndex in [1,#^FOR_COLLECTION_2?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#] {}
for forIndex in [1:#^FOR_COLLECTION_3?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#] {}
for forIndex in [#^FOR_COLLECTION_4?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#:] {}
for forIndex in [#^FOR_COLLECTION_5?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#:2] {}
for forIndex in [1:2, #^FOR_COLLECTION_6?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#] {}
for forIndex in [1:2, #^FOR_COLLECTION_7?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#:] {}
for forIndex in [1:2, #^FOR_COLLECTION_8?check=PLAIN_TOP_LEVEL;check=FOR_COLLECTION^#:2] {}
//
//===--- DON'T ADD ANY TESTS AFTER THIS LINE.
//
// These declarations should not show up in top-level code completion results
// because forward references are not allowed at the top level.
struct StructAtEOF {}
// NEGATIVE-NOT: StructAtEOF
extension FooStruct {
func instanceFuncAtEOF() {}
// NEGATIVE-NOT: instanceFuncAtEOF
}
var varAtEOF : Int
// NEGATIVE-NOT: varAtEOF
| dcd081aa1fcdef33345424d4e54e0f4f | 37.706044 | 141 | 0.701398 | false | false | false | false |
cocoaheadsru/server | refs/heads/develop | Sources/App/Controllers/Event/Registration/AutoapproveController.swift | mit | 1 | import Foundation
import Vapor
import Fluent
final class AutoapproveController {
private let autoapprove: Approval
init() throws {
guard let count = try? Approval.count() else {
fatalError("There are problems with call Approve.count()")
}
if count < 1 {
autoapprove = Approval(
visitedEvents: 2,
skippedEvents: 2,
periodInMonths: 6)
try autoapprove.save()
} else {
autoapprove = try Approval.all().first!
}
}
func grandApprove(to user: User, on event: Event) throws -> Bool? {
guard let userId = user.id else {
return nil
}
let visitedEvents = try EventReg
.makeQuery()
.filter(EventReg.Keys.userId, userId)
.filter(EventReg.Keys.status, EventReg.RegistrationStatus.approved.string)
.count()
guard visitedEvents >= autoapprove.visitedEvents else {
return false
}
guard
let date = Calendar.current.date(byAdding: .month, value: -autoapprove.periodInMonths, to: Date()),
let eventId = event.id
else {
return nil
}
let events = try Event.makeQuery()
.filter(Event.Keys.id != eventId)
.filter(Event.Keys.endDate >= date)
.filter(Event.Keys.endDate < Date())
.all()
let regForms = try RegForm.makeQuery()
.filter(RegForm.Keys.eventId, in: events.array.map { $0.id! })
.all()
guard regForms.count >= autoapprove.skippedEvents else {
return true
}
let skippedEventsCount = try EventReg
.makeQuery()
.filter(EventReg.Keys.regFormId, in: regForms.array.map { $0.id!.int })
.filter(EventReg.Keys.userId, user.id!)
.filter(EventReg.Keys.status, EventReg.RegistrationStatus.skipped.string)
.count()
guard skippedEventsCount >= autoapprove.skippedEvents else {
return true
}
return false
}
}
| 11fd3b6b8c2f10cbd57f6a8b37845671 | 24.342105 | 105 | 0.618899 | false | false | false | false |
StorageKit/StorageKit | refs/heads/develop | Example/Source/SubExamples/API response/Components/APIResponseTableViewController.swift | mit | 1 | //
// APIResponseTableViewController.swift
// Example
//
// Created by Santarossa, Marco (iOS Developer) on 17/07/2017.
// Copyright © 2017 MarcoSantaDev. All rights reserved.
//
import StorageKit
import UIKit
class APIResponseTableViewController: UITableViewController {
weak var storage: Storage?
var storageType: StorageKit.StorageType?
private var apiUsers: [APIUser]?
func reloadTable() {
storage?.performBackgroundTask { [unowned self] context in
guard let context = context, let storageType = self.storageType, let storage = self.storage, let mainContext = storage.mainContext else { return }
let sort = SortDescriptor(key: "username", ascending: true)
switch storageType {
case .CoreData:
do {
try context.fetch(predicate: nil, sortDescriptors: [sort]) { [unowned self] (users: [APIUserCoreData]?) in
guard let users = users else { return }
do {
try storage.getThreadSafeEntities(for: mainContext, originalContext: context, originalEntities: users) { [unowned self] safeUsers in
DispatchQueue.main.async {
self.apiUsers = safeUsers
self.tableView.reloadData()
}
}
} catch {}
}
} catch {}
case .Realm:
do {
try context.fetch(predicate: nil, sortDescriptors: [sort]) { [unowned self] (users: [APIUserRealm]?) in
guard let users = users else { return }
do {
try storage.getThreadSafeEntities(for: mainContext, originalContext: context, originalEntities: users) { [unowned self] safeUsers in
DispatchQueue.main.async {
self.apiUsers = safeUsers
self.tableView.reloadData()
}
}
} catch {}
}
} catch {}
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return apiUsers?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if let user = apiUsers?[indexPath.row] {
cell.textLabel?.text = user.username
cell.detailTextLabel?.text = user.fullname
}
return cell
}
}
| 08ea83cb1c3ba7568e5586d2ccf18691 | 36.447368 | 160 | 0.53338 | false | false | false | false |
neonichu/Decodable | refs/heads/spm-linux-compatibility | Sources/Parse.swift | mit | 1 | //
// Parse.swift
// Decodable
//
// Created by Johannes Lund on 2015-08-13.
// Copyright © 2015 anviking. All rights reserved.
//
import Foundation
public func parse<T>(json: AnyObject, path: [String], decode: (AnyObject throws -> T)) throws -> T {
var object = json
if let lastKey = path.last {
var path = path
path.removeLast()
var currentDict = try NSDictionary.decode(json)
var currentPath: [String] = []
func objectForKey(dictionary: NSDictionary, key: String) throws -> AnyObject {
guard let result = dictionary[NSString(string: key)] else {
let info = DecodingError.Info(object: dictionary, rootObject: json, path: currentPath)
throw DecodingError.MissingKey(key: key, info: info)
}
return result
}
for key in path {
currentDict = try NSDictionary.decode(objectForKey(currentDict, key: key))
currentPath.append(key)
}
object = try objectForKey(currentDict, key: lastKey)
}
return try catchAndRethrow(json, path) { try decode(object) }
}
// MARK: - Helpers
func catchAndRethrow<T>(json: AnyObject, _ path: [String], block: Void throws -> T) throws -> T {
do {
return try block()
} catch let error as DecodingError {
var new_error = error
new_error.info.path = path + error.info.path
new_error.info.rootObject = json
throw new_error
} catch let error {
throw error
}
}
| db33739c57068567801b9651875a7684 | 26.517241 | 102 | 0.584586 | false | false | false | false |
dzahariev/samples-ios | refs/heads/master | MasterDetail/MasterDetail/DetailViewController.swift | apache-2.0 | 1 | //
// DetailViewController.swift
// MasterDetail
//
// Created by Zahariev, Dobromir on 6/23/14.
// Copyright (c) 2014 dzahariev. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UISplitViewControllerDelegate {
@IBOutlet var detailDescriptionLabel: UILabel
var masterPopoverController: UIPopoverController? = nil
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| ba38949ec730861fb8d63725613e2f46 | 36.970149 | 238 | 0.712264 | false | false | false | false |
informmegp2/inform-me | refs/heads/master | InformME/AddEventViewController.swift | mit | 1 | //
// AddEventViewController.swift
// InformME
//
// Created by nouf abdullah on 4/28/1437 AH.
// Copyright © 1437 King Saud University. All rights reserved.
//
import UIKit
import Foundation
class AddEventViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var UserID: Int = NSUserDefaults.standardUserDefaults().integerForKey("id");
@IBOutlet var EventLogoo: UIButton!
@IBOutlet var EventDate: UITextField!
@IBOutlet var EventWebsite: UITextField!
@IBOutlet var EventName: UITextField!
@IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
EventDate.delegate = self
EventWebsite.delegate = self
EventName.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func uploadImage(sender: AnyObject) {
print("button pressed")
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
EventLogoo.setBackgroundImage(info[UIImagePickerControllerOriginalImage] as? UIImage, forState: .Normal)
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func dp(sender: UITextField) {
/* var datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)*/
let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240))
let datePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0))
datePickerView.datePickerMode = UIDatePickerMode.Date
inputView.addSubview(datePickerView) // add date picker to UIView
let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50))
doneButton.setTitle("Done", forState: UIControlState.Normal)
doneButton.setTitle("Done", forState: UIControlState.Highlighted)
doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
inputView.addSubview(doneButton) // add Button to UIView
doneButton.addTarget(self, action: #selector(AddEventViewController.doneButton(_:)), forControlEvents: UIControlEvents.TouchUpInside) // set button click event
sender.inputView = inputView
datePickerView.addTarget(self, action: #selector(AddEventViewController.handleDatePicker(_:)), forControlEvents: UIControlEvents.ValueChanged)
handleDatePicker(datePickerView) // Set the date on start.
}
func doneButton(sender:UIButton)
{
EventDate.resignFirstResponder() // To resign the inputView on clicking done.
}
func handleDatePicker(sender: UIDatePicker) {
sender.minimumDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
EventDate.text = dateFormatter.stringFromDate(sender.date)
}
func checkDate (ddate: String) -> Bool {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let todaysDate:NSDate = NSDate()
let dayWothFormat = dateFormatter.stringFromDate(todaysDate)
print(dayWothFormat)
let date = dateFormatter.dateFromString(dayWothFormat)
let date1 = dateFormatter.dateFromString(ddate)
if date1!.compare(date!) == NSComparisonResult.OrderedDescending
{
print("date1 after date2");
return true
} else if date1!.compare(date!) == NSComparisonResult.OrderedAscending
{
return false
} else
{
return true
}
}
@IBAction func save(sender: AnyObject) {
let name = EventName.text!
let website = EventWebsite.text!
let date = EventDate.text!
if (EventName.text == "" || EventDate.text == "") {
displayAlert("", message: "يرجى إدخال كافة الحقول")
}
else if(EventDate.text != "" && !checkDate(date)){
displayAlert("", message: "يرجى إدخال تاريخ الحدث بشكل الصحيح")
}
else {
print(EventName.text)
if(Reachability.isConnectedToNetwork()){
let e : Event = Event()
e.AddEvent (UserID, name: name, web: website, date: date, logo: EventLogoo.backgroundImageForState(.Normal)!){
(flag:Bool) in
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("addEvent", sender:sender)
}}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
}
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title:title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "موافق", style: .Default, handler: nil ))
self.presentViewController(alert, animated: true, completion: nil)
}//end fun display alert
func textFieldDidBeginEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 150)), animated: true)
}
func textFieldDidEndEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 0)), animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
var window:UIWindow!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("eventsMng") as? CenterViewController
print(window!.rootViewController)
window!.rootViewController = containerViewController
print(window!.rootViewController)
window!.makeKeyAndVisible()
containerViewController.centerViewController.delegate?.collapseSidePanels!()
}
func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) }
}
| 09c48e4a2899c06caf2d836f3ae5f01d | 35.47619 | 167 | 0.637728 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureKYC/Sources/FeatureKYCDomainMock/MockKYCTiersService.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import PlatformKit
import RxSwift
public final class MockKYCTiersService: PlatformKit.KYCTiersServiceAPI {
public struct RecordedInvocations {
public var fetchTiers: [Void] = []
public var fetchOverview: [Void] = []
public var simplifiedDueDiligenceEligibility: [KYC.Tier] = []
public var checkSimplifiedDueDiligenceEligibility: [KYC.Tier] = []
public var checkSimplifiedDueDiligenceVerification: [KYC.Tier] = []
}
public struct StubbedResponses {
public var fetchTiers: AnyPublisher<KYC.UserTiers, Nabu.Error> = .empty()
public var simplifiedDueDiligenceEligibility: AnyPublisher<SimplifiedDueDiligenceResponse, Never> = .empty()
public var checkSimplifiedDueDiligenceEligibility: AnyPublisher<Bool, Never> = .empty()
public var checkSimplifiedDueDiligenceVerification: AnyPublisher<Bool, Never> = .empty()
public var fetchOverview: AnyPublisher<KYCLimitsOverview, Nabu.Error> = .empty()
}
public private(set) var recordedInvocations = RecordedInvocations()
public var stubbedResponses = StubbedResponses()
public var tiers: AnyPublisher<KYC.UserTiers, Nabu.Error> {
fetchTiers()
}
public var tiersStream: AnyPublisher<KYC.UserTiers, Nabu.Error> {
fetchTiers()
}
public func fetchTiers() -> AnyPublisher<KYC.UserTiers, Nabu.Error> {
recordedInvocations.fetchTiers.append(())
return stubbedResponses.fetchTiers
}
public func simplifiedDueDiligenceEligibility(for tier: KYC.Tier) -> AnyPublisher<SimplifiedDueDiligenceResponse, Never> {
recordedInvocations.simplifiedDueDiligenceEligibility.append(tier)
return stubbedResponses.simplifiedDueDiligenceEligibility
}
public func checkSimplifiedDueDiligenceEligibility() -> AnyPublisher<Bool, Never> {
checkSimplifiedDueDiligenceEligibility(for: .tier0)
}
public func checkSimplifiedDueDiligenceEligibility(for tier: KYC.Tier) -> AnyPublisher<Bool, Never> {
recordedInvocations.checkSimplifiedDueDiligenceEligibility.append(tier)
return stubbedResponses.checkSimplifiedDueDiligenceEligibility
}
public func checkSimplifiedDueDiligenceVerification(
for tier: KYC.Tier,
pollUntilComplete: Bool
) -> AnyPublisher<Bool, Never> {
recordedInvocations.checkSimplifiedDueDiligenceVerification.append(tier)
return stubbedResponses.checkSimplifiedDueDiligenceVerification
}
public func checkSimplifiedDueDiligenceVerification(pollUntilComplete: Bool) -> AnyPublisher<Bool, Never> {
checkSimplifiedDueDiligenceVerification(for: .tier0, pollUntilComplete: pollUntilComplete)
}
public func fetchOverview() -> AnyPublisher<KYCLimitsOverview, Nabu.Error> {
recordedInvocations.fetchOverview.append(())
return stubbedResponses.fetchOverview
}
}
| 538ccc6680f7ffc5118a720ca92ad8ad | 40.5 | 126 | 0.742972 | false | false | false | false |
kylesnowschwartz/shop-share | refs/heads/master | Goojle Retain/Goojle Retain/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Goojle Retain
//
// Created by Timothy Barraclough on 17/08/17.
// Copyright © 2017 Shop Share Industries. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let s = GRWebSocket.shared
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Goojle_Retain")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 50c4bb7b735094565635b9c6b4d40ac5 | 47.957895 | 285 | 0.686734 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Pods/LeanCloud/Sources/Storage/DataType/Dictionary.swift | gpl-3.0 | 1 | //
// LCDictionary.swift
// LeanCloud
//
// Created by Tang Tianyong on 2/27/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
LeanCloud dictionary type.
It is a wrapper of `Swift.Dictionary` type, used to store a dictionary value.
*/
@dynamicMemberLookup
public final class LCDictionary: NSObject, LCValue, LCValueExtension, Collection, ExpressibleByDictionaryLiteral {
public typealias Key = String
public typealias Value = LCValue
public typealias Index = DictionaryIndex<Key, Value>
public private(set) var value: [Key: Value] = [:]
var elementDidChange: ((Key, Value?) -> Void)?
public override init() {
super.init()
}
public convenience init(_ value: [Key: Value]) {
self.init()
self.value = value
}
public convenience init(_ value: [Key: LCValueConvertible]) {
self.init()
self.value = value.mapValue { value in value.lcValue }
}
/**
Create copy of dictionary.
- parameter dictionary: The dictionary to be copied.
*/
public convenience init(_ dictionary: LCDictionary) {
self.init()
self.value = dictionary.value
}
public convenience required init(dictionaryLiteral elements: (Key, Value)...) {
self.init(Dictionary<Key, Value>(elements: elements))
}
public convenience init(unsafeObject: Any) throws {
self.init()
guard let object = unsafeObject as? [Key: Any] else {
throw LCError(
code: .malformedData,
reason: "Failed to construct LCDictionary with non-dictionary object.")
}
value = try object.mapValue { value in
try ObjectProfiler.shared.object(jsonValue: value)
}
}
public required init?(coder aDecoder: NSCoder) {
/* Note: We have to make type casting twice here, or it will crash for unknown reason.
It seems that it's a bug of Swift. */
value = (aDecoder.decodeObject(forKey: "value") as? [String: AnyObject] as? [String: LCValue]) ?? [:]
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
public func copy(with zone: NSZone?) -> Any {
return LCDictionary(value)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? LCDictionary {
return object === self || object.value == value
} else {
return false
}
}
public func makeIterator() -> DictionaryIterator<Key, Value> {
return value.makeIterator()
}
public var startIndex: DictionaryIndex<Key, Value> {
return value.startIndex
}
public var endIndex: DictionaryIndex<Key, Value> {
return value.endIndex
}
public func index(after i: DictionaryIndex<Key, Value>) -> DictionaryIndex<Key, Value> {
return value.index(after: i)
}
public subscript(position: DictionaryIndex<Key, Value>) -> (key: Key, value: Value) {
return value[position]
}
public subscript(key: Key) -> Value? {
get { return value[key] }
set {
value[key] = newValue
elementDidChange?(key, newValue)
}
}
public subscript(dynamicMember key: String) -> LCValueConvertible? {
get {
return self[key]
}
set {
self[key] = newValue?.lcValue
}
}
/**
Removes the given key and its associated value from dictionary.
- parameter key: The key to remove along with its associated value.
- returns: The value that was removed, or `nil` if the key was not found.
*/
@discardableResult
public func removeValue(forKey key: Key) -> Value? {
return value.removeValue(forKey: key)
}
func set(_ key: String, _ value: LCValue?) {
self.value[key] = value
}
public var jsonValue: Any {
return value.compactMapValue { value in value.jsonValue }
}
func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String {
if value.isEmpty {
return "{}"
}
let lastIndent = " " * (numberOfSpacesForOneIndentLevel * indentLevel)
let bodyIndent = " " * (numberOfSpacesForOneIndentLevel * (indentLevel + 1))
let body = value
.map { (key, value) in (key, (value as! LCValueExtension).formattedJSONString(indentLevel: indentLevel + 1, numberOfSpacesForOneIndentLevel: numberOfSpacesForOneIndentLevel)) }
.sorted { (left, right) in left.0 < right.0 }
.map { (key, value) in "\"\(key.doubleQuoteEscapedString)\": \(value)" }
.joined(separator: ",\n" + bodyIndent)
return "{\n\(bodyIndent)\(body)\n\(lastIndent)}"
}
public var jsonString: String {
return formattedJSONString(indentLevel: 0)
}
public var rawValue: LCValueConvertible {
let dictionary = value.mapValue { value in value.rawValue }
return dictionary as! LCValueConvertible
}
var lconValue: Any? {
return value.compactMapValue { value in (value as? LCValueExtension)?.lconValue }
}
static func instance() -> LCValue {
return self.init([:])
}
func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows {
try forEach { (_, element) in try body(element) }
}
func add(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be added.")
}
func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be concatenated.")
}
func differ(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be differed.")
}
}
| f8590c42e39d97e8b5f34634a069c950 | 29.210256 | 192 | 0.615855 | false | false | false | false |
DRybochkin/Spika.swift | refs/heads/master | Spika/Views/VideoPreviewView/CSVideoPreviewView.swift | mit | 1 | //
// VideoPreviewView.h
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import UIKit
import MediaPlayer
//import AFNetworking
class CSVideoPreviewView: CSBasePreviewView {
var filePath: String = ""
var moviePlayer: MPMoviePlayerController!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var backGroundView: UIView!
@IBAction func onClose(_ sender: Any) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer)
dismiss()
}
override func initializeView(message: CSMessageModel!, size: Float, dismiss: dismissPreview!) {
self.dismiss = dismiss
self.message = message
var viewRect: CGRect = UIScreen.main.bounds
viewRect.size.height = viewRect.size.height - CGFloat(size)
var className: String = String(describing: type(of: self))
className = className.replacingOccurrences(of: Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as! String, with: "")
className = className.replacingOccurrences(of: ".", with: "")
let path: String! = Bundle.main.path(forResource: className, ofType: "nib")
if (!FileManager.default.fileExists(atPath: path)) {
return
}
var array: [Any]! = Bundle.main.loadNibNamed(className, owner: self, options: nil)
assert(array.count == 1, "Invalid number of nibs")
frame = viewRect
let backGR: UIView! = array[0] as! UIView
backGR?.frame = viewRect
addSubview(backGR)
closeButton.layer.cornerRadius = closeButton.frame.size.width / 2
closeButton.layer.masksToBounds = true
closeButton.backgroundColor = kAppDefaultColor(0.8)
backGroundView.layer.cornerRadius = 10
backGroundView.layer.masksToBounds = true
filePath = CSUtils.getFileFrom(message.file)
if (!CSUtils.isFileExists(withFileName: filePath)) {
let downloadManager = CSDownloadManager()
downloadManager.downloadFile(with: URL(string: CSUtils.generateDownloadURLFormFileId(message.file.file.id)), destination: URL(string: filePath), viewForLoading: self, completition: {(_ success: Bool) -> Void in
self.playVideo()
})
} else {
playVideo()
}
}
func playVideo() {
moviePlayer = MPMoviePlayerController(contentURL: URL(fileURLWithPath: filePath))
if (moviePlayer != nil) {
NotificationCenter.default.addObserver(self, selector: #selector(moviePlaybackComplete), name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer)
moviePlayer.allowsAirPlay = true
var videoViewRect: CGRect = frame
videoViewRect.origin.x = videoViewRect.origin.x + 20
videoViewRect.origin.y = videoViewRect.origin.y + 20
videoViewRect.size.height = videoViewRect.size.height - 90
videoViewRect.size.width = videoViewRect.size.width - 90
moviePlayer.view.frame = videoViewRect
backGroundView.addSubview(moviePlayer.view)
moviePlayer.play()
}
}
func moviePlaybackComplete(_ notification: Notification) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer)
}
}
| 8e0e148c7ea3eb9a708a7a75045648ef | 43.525641 | 222 | 0.678088 | false | false | false | false |
nathantannar4/NTComponents | refs/heads/master | NTComponents/Extensions/Array.swift | mit | 1 | //
// Array.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by Nathan Tannar on 6/26/17.
//
public extension Array {
/**
Shuffle the array in-place using the Fisher-Yates algorithm.
*/
public mutating func shuffle() {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
if j != i {
self.swapAt(i, j)
}
}
}
/**
Return a shuffled version of the array using the Fisher-Yates
algorithm.
- returns: Returns a shuffled version of the array.
*/
public func shuffled() -> [Element] {
var list = self
list.shuffle()
return list
}
/**
Return a random element from the array.
- returns: Returns a random element from the array or `nil` if the
array is empty.
*/
public func random() -> Element? {
return (count > 0) ? self.shuffled()[0] : nil
}
/**
Return a random subset of `cnt` elements from the array.
- returns: Returns a random subset of `cnt` elements from the array.
*/
public func random(_ count : Int = 1) -> [Element] {
let result = shuffled()
return (count > result.count) ? result : Array(result[0..<count])
}
}
| b58ef2586c97bba5838a077e9c7657d3 | 32.791667 | 82 | 0.638718 | false | false | false | false |
caicai0/ios_demo | refs/heads/master | load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/ArrayExt.swift | mit | 1 | //
// ArrayExt.swift
// SwifSoup
//
// Created by Nabil Chatbi on 05/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
extension Array {
func binarySearch<T: Comparable>(_ collection: [T], _ target: T) -> Int {
let min = 0
let max = collection.count - 1
return binaryMakeGuess(min: min, max: max, target: target, collection: collection)
}
func binaryMakeGuess<T: Comparable>(min: Int, max: Int, target: T, collection: [T]) -> Int {
let guess = (min + max) / 2
if max < min {
// illegal, guess not in array
return -1
} else if collection[guess] == target {
// guess is correct
return guess
} else if collection[guess] > target {
// guess is too high
return binaryMakeGuess(min: min, max: guess - 1, target: target, collection: collection)
} else {
// array[guess] < target
// guess is too low
return binaryMakeGuess(min: guess + 1, max: max, target: target, collection: collection)
}
}
}
extension Array where Element : Equatable {
func lastIndexOf(_ e: Element) -> Int {
for pos in (0..<self.count).reversed() {
let next = self[pos]
if (next == e) {
return pos
}
}
return -1
}
}
| 348705bc1248e8559ec0474dc49f91ea | 22.566667 | 100 | 0.539604 | false | false | false | false |
DannyKG/BoLianEducation | refs/heads/master | BoLianEducation/Mine/ViewController/UCAddFriendsController.swift | apache-2.0 | 1 | //
// UCAddFriendsController.swift
// BoLianEducation
//
// Created by BoLian on 2017/6/9.
// Copyright © 2017年 BoLian. All rights reserved.
//
import UIKit
class UCAddFriendsController: UIViewController {
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var reasonTextView: UITextView!
@IBOutlet weak var reasonLabel: UILabel!
@IBOutlet weak var inviteLabel: UILabel!
@IBOutlet weak var backView: UIView!
@IBOutlet weak var backViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var inviteWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var textViewConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var reasonTopConstraint: NSLayoutConstraint!
@IBOutlet weak var backViewTopConstraint: NSLayoutConstraint!
var targetUserName: String?
var targetUserId: String?
var phone: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
subviews()
}
func subviews() {
view.backgroundColor = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha:0)
let inviteWidth = 200 * ApplicationStyle.proportion_weight()
inviteWidthConstraint.constant = inviteWidth
inviteLabel.layer.cornerRadius = inviteWidth/2.0
inviteLabel.clipsToBounds = true
reasonTopConstraint.constant = inviteWidth/2.0 + 30
textViewConstraint.constant = 238 * ApplicationStyle.proportion_weight()
buttonHeightConstraint.constant = 88 * ApplicationStyle.proportion_weight()
addButton.layer.cornerRadius = 10
addButton.clipsToBounds = true
backView.layer.cornerRadius = 50
backView.clipsToBounds = true
backViewTopConstraint.constant = inviteWidth/2.0
backViewHeightConstraint.constant = 418 - 169 + 238 * ApplicationStyle.proportion_weight() - 44 + 88 * ApplicationStyle.proportion_weight()
if let userName = targetUserName {
reasonLabel.text = String.init(format: "您将添加%@为好友,请输入留言:", userName)
}
if let name = AccountTool.shared().account.name {
reasonTextView.text = String.init(format: "我是%@", name)
}
}
@IBAction func buttonAction(_ sender: UIButton) {
let reason = reasonTextView.text;
if reason?.isEmpty == false {
self.mz_dismissFormSheetController(animated: true, completionHandler: nil)
addFreindsRequest()
}
}
//MARK:添加好友的请求
func addFreindsRequest() {
if let useId = targetUserId {
RCDHttpTool.shareInstance().sendAddFriendSystemMessage(AccountTool.shared().account.userId, toUserId: useId, content: reasonTextView.text, complete: { [weak self] (reponse: Any) in
if reponse is NSString {
if reponse as! NSString != "200" {
let tips = (reponse as! NSString) as String!
self?.postNotification(tips: tips!)
}
}
})
} else if let userPhone = phone {
RCDHttpTool.shareInstance().sendAddFriendMessage(AccountTool.shared().account.userId, withPhone: userPhone, content: reasonTextView.text, complete: { [weak self] (response: Any) in
if response is NSString {
if response as! NSString != "200" {
let tips = (response as! NSString) as String!
self?.postNotification(tips: tips!)
}
}
})
}
}
func postNotification(tips: String) {
let notificaionName = Notification.Name(rawValue: "SwiftTips")
NotificationCenter.default.post(name: notificaionName, object: tips)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cf9d4afa62c25caa940c979bd7f2b677 | 38.242718 | 192 | 0.636566 | false | false | false | false |
liuchuo/iOS9-practise | refs/heads/master | Todo/Todo/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// Todo
//
// Created by ChenXin on 16/3/8.
// Copyright © 2016年 ChenXin. All rights reserved.
//
import UIKit
//定义一个全局变量。作为本地的数据库(运行时的数据库,只保存在内存里面)
//定义全局变量,使得整个app里面的其他代码文件都能访问它
var todos: [TodoModel] = []
var filteredTodos:[TodoModel] = []
func dateFromString(dateStr: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.dateFromString(dateStr)
return date
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
todos = [TodoModel(id: "1", image: "child-selected", title: "1.去玩", date: dateFromString("2014-11-02")!),
TodoModel(id: "2", image: "shopping-cart-selected", title: "2.去购物", date: dateFromString("2014-10-28")!),
TodoModel(id: "3", image: "phone-selected", title: "3.打电话", date: dateFromString("2015-11-11")!),
TodoModel(id: "4", image: "travel-selected", title: "4.Travel to Europe", date: dateFromString("1995-01-01")!)]
//激活edit模式
navigationItem.leftBarButtonItem = editButtonItem()
}
//MARK-UITableViewDataSource
@available(iOS 2.0, *)
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplayController?.searchResultsTableView {
return filteredTodos.count
}
return todos.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
@available(iOS 2.0, *)
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("todoCell")! as UITableViewCell
var todo: TodoModel
if tableView == searchDisplayController?.searchResultsTableView {
todo = filteredTodos[indexPath.row] as TodoModel
}
else {
todo = todos[indexPath.row] as TodoModel
}
var image = cell.viewWithTag(101) as! UIImageView
var title = cell.viewWithTag(102) as! UILabel
var date = cell.viewWithTag(103) as! UILabel
image.image = UIImage(named: todo.image)
title.text = todo.title
let locale = NSLocale.currentLocale()
let dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy-MM-dd", options: 0, locale: locale)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
date.text = dateFormatter.stringFromDate(todo.date)
return cell
}
//MARK-UITableViewDeleage
public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
todos.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
//Edit Mode
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.setEditing(editing, animated: animated)
}
// Move cell
public func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return editing
}
public func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let todo = todos.removeAtIndex(sourceIndexPath.row)
todos.insert(todo, atIndex: destinationIndexPath.row)
}
// Search
public func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String?) -> Bool {
filteredTodos = todos.filter(){$0.title.rangeOfString(searchString!) != nil}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func close(segue: UIStoryboardSegue) {
print("closed")
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditTodo" {
var vc = segue.destinationViewController as! DetailViewController
var indexPath = tableView.indexPathForSelectedRow
if let index = indexPath {
vc.todo = todos[index.row]
}
}
}
}
| 10033733d0fb1861b48e4758ac69e16c | 34.437086 | 188 | 0.663241 | false | false | false | false |
shralpmeister/shralptide2 | refs/heads/main | ShralpTide/Shared/Components/ChartView/InteractiveChartViewModifier.swift | gpl-3.0 | 1 | //
// InteractiveChartViewModifier.swift
// SwiftTides
//
// Created by Michael Parlee on 12/29/20.
//
import ShralpTideFramework
import SwiftUI
import Combine
struct InteractiveChartViewModifier: ViewModifier {
@EnvironmentObject var appState: AppState
@Binding private var pageIndex: Int
@Binding private var cursorLocation: CGPoint
private var tideData: SDTide
private var idiom: UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom }
init(tide: SDTide, currentIndex: Binding<Int>, cursorLocation: Binding<CGPoint>) {
tideData = tide
_pageIndex = currentIndex
_cursorLocation = cursorLocation
}
private func timeInMinutes(x xPosition: CGFloat, xRatio: CGFloat) -> Int {
return Int(round(xPosition / xRatio))
}
func body(content: Content) -> some View {
return GeometryReader { proxy in
let screenMinutes =
appState.tidesForDays[self.pageIndex].startTime.hoursInDay() * ChartConstants.minutesPerHour
let xRatio = proxy.size.width / CGFloat(screenMinutes)
let midpointX = proxy.size.width / 2.0
let xPosition =
cursorLocation.x > .zero
? cursorLocation.x : CGFloat(currentTimeInMinutes(tideData: tideData)) * xRatio
content
.overlay(
ZStack {
if idiom == .phone && (pageIndex == 0 || cursorLocation.x > 0) {
Cursor(height: proxy.size.height)
.position(x: xPosition, y: proxy.size.height / 2.0)
let dataPoint = appState.tidesForDays[self.pageIndex].nearestDataPoint(
forTime: timeInMinutes(x: xPosition, xRatio: xRatio))
TideOverlay(
dataPoint: dataPoint, unit: tideData.unitShort,
startDate: appState.tidesForDays[self.pageIndex].startTime
)
.position(x: midpointX, y: 90)
} else if idiom == .pad {
if tideData.startTime == Date().startOfDay() || cursorLocation.x > 0 {
Cursor(height: proxy.size.height)
.position(x: xPosition, y: proxy.size.height / 2.0)
}
if cursorLocation.x > 0 {
let dataPoint = tideData.nearestDataPoint(
forTime: timeInMinutes(x: xPosition, xRatio: xRatio))
TideOverlay(
dataPoint: dataPoint, unit: tideData.unitShort,
startDate: appState.tidesForDays[self.pageIndex].startTime
)
.position(x: midpointX, y: 90)
}
}
}
.frame(alignment: .top)
)
}
}
}
struct Cursor: View {
let height: CGFloat
var body: some View {
Rectangle()
.fill(Color.red)
.frame(width: 4.0, height: height)
.animation(.interactiveSpring(response: 0.3, dampingFraction: 0.6, blendDuration: 0))
}
}
struct TideOverlay: View {
let dataPoint: CGPoint
let unit: String
let startDate: Date
private let timeFormatter = DateFormatter()
init(dataPoint: CGPoint, unit: String, startDate: Date) {
self.dataPoint = dataPoint
self.unit = unit
self.startDate = startDate
timeFormatter.timeStyle = .short
}
var body: some View {
ZStack {
let xDate = dateTime(fromMinutesSinceMidnight: Int(dataPoint.x))
RoundedRectangle(cornerRadius: 5)
.fill(Color.black.opacity(0.6))
Text(String(format: "%0.2f %@ @ %@", dataPoint.y, unit, timeFormatter.string(from: xDate)))
.font(.title)
.frame(maxWidth: 300)
.minimumScaleFactor(0.2)
.foregroundColor(Color.white)
}
.transition(.opacity)
.frame(maxWidth: 360, maxHeight: 50)
}
private func dateTime(fromMinutesSinceMidnight minutes: Int) -> Date {
let hours = minutes / ChartConstants.minutesPerHour
let minutes = minutes % ChartConstants.secondsPerMinute
let cal = Calendar.current
let components = DateComponents(hour: hours, minute: minutes)
return cal.date(byAdding: components, to: startDate)!
}
}
| fc03a52b9efcda719bed2291ab73ac9d | 36.388889 | 108 | 0.541711 | false | false | false | false |
swernimo/iOS | refs/heads/master | iOS Networking with Swift/OnTheMap/OnTheMap/Constants.swift | mit | 1 | //
// Constants.swift
// OnTheMap
//
// Created by Sean Wernimont on 1/26/16.
// Copyright © 2016 Just One Guy. All rights reserved.
//
import Foundation
struct Constants{
struct InvalidLogin {
static let message = "Invalid Username/Password Combination";
static let title = "Invalid Login Attempt";
}
struct MissingUsername{
static let title = "Empty Username";
static let message = "Username is required";
}
struct MissingPassword{
static let title = "Empty Password";
static let message = "Password is required";
}
struct MissingUserNamePassword{
static let title = "Missing Username / Password";
static let message = "Username and Password are required";
}
struct LoginMessages{
static let successfulTitle = "Login Success!!";
static let successMessage = "You have successfully logged into Udacity";
static let errorTitle = "Login Error";
static let errorMessage = "We're sorry. Something went wrong :(";
}
struct ParseKeys{
static let APIKey = "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY";
static let ApplicationID = "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr";
}
struct APIMethods{
static let Base = "https://www.udacity.com/api/";
static let Login = "session";
static let ParseBase = "https://api.parse.com/1/classes/";
static let StudentLocations = "StudentLocation";
static let GetUserInfo = "users/";
}
struct Error {
static let ErrorDescription = "Description";
}
struct LoginResultsDictionaryKeys {
static let Session = "Session";
static let UserKey = "UserKey";
}
struct UserInfoKeys{
static let FirstName = "FirstName";
static let LastName = "LastName";
}
enum LoginStatusCodes{
case Successful
case Error
case Invalid
}
} | d94fb66d95bf834a74192c7c82f0cbe7 | 27.084507 | 80 | 0.626693 | false | false | false | false |
JGiola/swift-corelibs-foundation | refs/heads/master | Foundation/NSCFArray.swift | apache-2.0 | 2 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal final class _NSCFArray : NSMutableArray {
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
required init(coder: NSCoder) {
fatalError()
}
required init(objects: UnsafePointer<AnyObject>?, count cnt: Int) {
fatalError()
}
required public convenience init(arrayLiteral elements: Any...) {
fatalError()
}
override var count: Int {
return CFArrayGetCount(_cfObject)
}
override func object(at index: Int) -> Any {
let value = CFArrayGetValueAtIndex(_cfObject, index)
return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self))
}
override func insert(_ value: Any, at index: Int) {
let anObject = __SwiftValue.store(value)
CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self))
}
override func removeObject(at index: Int) {
CFArrayRemoveValueAtIndex(_cfMutableObject, index)
}
override var classForCoder: AnyClass {
return NSMutableArray.self
}
}
internal func _CFSwiftArrayGetCount(_ array: AnyObject) -> CFIndex {
return (array as! NSArray).count
}
internal func _CFSwiftArrayGetValueAtIndex(_ array: AnyObject, _ index: CFIndex) -> Unmanaged<AnyObject> {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
return Unmanaged.passUnretained(arr._storage[index])
} else {
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
return Unmanaged.passUnretained(value)
}
}
internal func _CFSwiftArrayGetValues(_ array: AnyObject, _ range: CFRange, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>) {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
for idx in 0..<range.length {
values[idx] = Unmanaged.passUnretained(arr._storage[idx + range.location])
}
} else {
for idx in 0..<range.length {
let index = idx + range.location
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
values[idx] = Unmanaged.passUnretained(value)
}
}
}
internal func _CFSwiftArrayAppendValue(_ array: AnyObject, _ value: AnyObject) {
(array as! NSMutableArray).add(value)
}
internal func _CFSwiftArraySetValueAtIndex(_ array: AnyObject, _ value: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayReplaceValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayInsertValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).insert(value, at: idx)
}
internal func _CFSwiftArrayExchangeValuesAtIndices(_ array: AnyObject, _ idx1: CFIndex, _ idx2: CFIndex) {
(array as! NSMutableArray).exchangeObject(at: idx1, withObjectAt: idx2)
}
internal func _CFSwiftArrayRemoveValueAtIndex(_ array: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).removeObject(at: idx)
}
internal func _CFSwiftArrayRemoveAllValues(_ array: AnyObject) {
(array as! NSMutableArray).removeAllObjects()
}
internal func _CFSwiftArrayReplaceValues(_ array: AnyObject, _ range: CFRange, _ newValues: UnsafeMutablePointer<Unmanaged<AnyObject>>, _ newCount: CFIndex) {
NSUnimplemented()
// (array as! NSMutableArray).replaceObjectsInRange(NSRange(location: range.location, length: range.length), withObjectsFrom: newValues.array(newCount))
}
| cd1c5deb91247cc081f7a04b03e5d06e | 35.330769 | 158 | 0.668219 | false | false | false | false |
EasySwift/EasySwift | refs/heads/master | Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/TextFieldViewController.swift | apache-2.0 | 2 | //
// TextFieldViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class TextFieldViewController: UIViewController, UITextViewDelegate, UIPopoverPresentationControllerDelegate {
@IBOutlet fileprivate var textField3 : UITextField!
@IBOutlet var textView1: IQTextView!
@IBOutlet fileprivate var dropDownTextField : IQDropDownTextField!
@IBOutlet fileprivate var buttonPush : UIButton!
@IBOutlet fileprivate var buttonPresent : UIButton!
func previousAction(_ sender : UITextField) {
print("PreviousAction")
}
func nextAction(_ sender : UITextField) {
print("nextAction")
}
func doneAction(_ sender : UITextField) {
print("doneAction")
}
override func viewDidLoad() {
super.viewDidLoad()
textView1.delegate = self
textField3.setCustomPreviousTarget(self, action: #selector(self.previousAction(_:)))
textField3.setCustomNextTarget(self, action: #selector(self.nextAction(_:)))
textField3.setCustomDoneTarget(self, action: #selector(self.doneAction(_:)))
dropDownTextField.keyboardDistanceFromTextField = 150;
var itemLists = [NSString]()
itemLists.append("Zero Line Of Code")
itemLists.append("No More UIScrollView")
itemLists.append("No More Subclasses")
itemLists.append("No More Manual Work")
itemLists.append("No More #imports")
itemLists.append("Device Orientation support")
itemLists.append("UITextField Category for Keyboard")
itemLists.append("Enable/Desable Keyboard Manager")
itemLists.append("Customize InputView support")
itemLists.append("IQTextView for placeholder support")
itemLists.append("Automanage keyboard toolbar")
itemLists.append("Can set keyboard and textFiled distance")
itemLists.append("Can resign on touching outside")
itemLists.append("Auto adjust textView's height")
itemLists.append("Adopt tintColor from textField")
itemLists.append("Customize keyboardAppearance")
itemLists.append("Play sound on next/prev/done")
dropDownTextField.itemList = itemLists
}
override func viewWillAppear(_ animated : Bool) {
super.viewWillAppear(animated)
if (self.presentingViewController != nil)
{
buttonPush.isHidden = true
buttonPresent.setTitle("Dismiss", for:UIControlState())
}
}
@IBAction func presentClicked (_ sender: AnyObject!) {
if self.presentingViewController == nil {
let controller: UIViewController = (storyboard?.instantiateViewController(withIdentifier: "TextFieldViewController"))!
let navController : UINavigationController = UINavigationController(rootViewController: controller)
navController.navigationBar.tintColor = self.navigationController?.navigationBar.tintColor
navController.navigationBar.barTintColor = self.navigationController?.navigationBar.barTintColor
navController.navigationBar.titleTextAttributes = self.navigationController?.navigationBar.titleTextAttributes
// navController.modalTransitionStyle = Int(arc4random()%4)
// TransitionStylePartialCurl can only be presented by FullScreen style.
// if (navController.modalTransitionStyle == UIModalTransitionStyle.PartialCurl) {
// navController.modalPresentationStyle = UIModalPresentationStyle.FullScreen
// } else {
// navController.modalPresentationStyle = UIModalPresentationStyle.PageSheet
// }
present(navController, animated: true, completion: nil)
} else {
dismiss(animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destination
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height);
controller.preferredContentSize = CGSize(width: heightWidth, height: heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
func textViewDidBeginEditing(_ textView: UITextView) {
print("textViewDidBeginEditing");
}
override var shouldAutorotate : Bool {
return true
}
}
| 75fd2ab7357e0a05271a50131143c3cf | 37.925373 | 130 | 0.66852 | false | false | false | false |
blinksh/blink | refs/heads/raw | BlinkFiles/BlinkFiles.swift | gpl-3.0 | 1 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2021 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import Combine
public typealias BlinkFilesAttributeKey = FileAttributeKey
// NOTE We are bending the compiler a bit here. If we just extend FileAttributeKey,
// whenever you export the package, you will get an execution time error because the extension
// may not have applied (and name does not exist). By applying this redirection, we get it
// to work while still respecting the proper interface everywhere.
public extension BlinkFilesAttributeKey {
static let name: FileAttributeKey = FileAttributeKey("fileName")
}
public typealias FileAttributes = [BlinkFilesAttributeKey: Any]
public protocol Translator: CopierFrom {
var fileType: FileAttributeType { get }
var isDirectory: Bool { get }
var current: String { get }
var isConnected: Bool { get }
func clone() -> Translator
// The walk offers a way to traverse the remote filesystem, without dealing with internal formats.
// It is responsible to extend paths and define objects along the way.
func walkTo(_ path: String) -> AnyPublisher<Translator, Error>
// Equivalent to a directory read, it returns all the elements and attrs from stating the containing objects
func directoryFilesAndAttributes() -> AnyPublisher<[FileAttributes], Error>
// Creates the file name at the current walked path with the given permissions.
// Default mode = S_IRWXU
func create(name: String, flags: Int32, mode: mode_t) -> AnyPublisher<File, Error>
// Creates the directory name at the current walked path with the given permissions.
// Default mode = S_IRWUX | S_IRWXG | S_IRWXO
func mkdir(name: String, mode: mode_t) -> AnyPublisher<Translator, Error>
// Opens a Stream to the object
func open(flags: Int32) -> AnyPublisher<File, Error>
// Remove the object
func remove() -> AnyPublisher<Bool, Error>
func rmdir() -> AnyPublisher<Bool, Error>
// Change attributes
func stat() -> AnyPublisher<FileAttributes, Error>
func wstat(_ attrs: FileAttributes) -> AnyPublisher<Bool, Error>
}
// Could do it with a generic for types to read and write
public protocol Reader {
// One time read or continuous? If it is one time, I would make it more explicit through Future,
// or whatever the URLRequest also uses.
func read(max length: Int) -> AnyPublisher<DispatchData, Error>
}
public protocol Writer {
func write(_ buf: DispatchData, max length: Int) -> AnyPublisher<Int, Error>
}
public protocol WriterTo {
// Or make it to Cancellable
func writeTo(_ w: Writer) -> AnyPublisher<Int, Error>
}
public protocol ReaderFrom {
// Or make it to Cancellable
func readFrom(_ r: Reader) -> AnyPublisher<Int, Error>
}
public protocol File: Reader, Writer {
func close() -> AnyPublisher<Bool, Error>
}
// The Copy algorithms will report the progress of each file as it gets copied.
// As they are recursive, we provide information on what file is being reported.
// Report progress as (name, total bytes written, length)
// FileAttributeKey.Size is an NSNumber with a UInt64. It is the standard.
public struct CopyProgressInfo {
public let name: String
public let written: UInt64
public let size: UInt64
public init(name: String, written: UInt64, size: UInt64) {
self.name = name
self.written = written
self.size = size
}
}
public typealias CopyProgressInfoPublisher = AnyPublisher<CopyProgressInfo, Error>
public protocol CopierFrom {
func copy(from ts: [Translator], args: CopyArguments) -> CopyProgressInfoPublisher
}
public protocol CopierTo {
func copy(to ts: Translator) -> CopyProgressInfoPublisher
}
extension AnyPublisher {
@inlinable public static func just(_ output: Output) -> Self {
.init(Just(output).setFailureType(to: Failure.self))
}
@inlinable public static func fail(error: Failure) -> Self {
.init(Fail(error: error))
}
}
//
//// Server side Copy and Rename are usually best when performing operations inside the Translator, but
//// not all protocols support them.
//public protocol Copier {
// func copy(at dst: Translator) throws -> Translator
//}
//
//public protocol Renamer {
// func rename(at dst: Translator, newName: String) throws -> Translator
//}
| 051ec00bbe8841872d28d02b5870bc0c | 35.213333 | 110 | 0.710788 | false | false | false | false |
knutigro/AppReviews | refs/heads/develop | AppReviews/NSApplication+Startup.swift | gpl-3.0 | 1 | //
// NSApplication+Startup.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-05-29.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
extension NSApplication {
// MARK: Public methods
class func shouldLaunchAtStartup() -> Bool {
return (itemReferencesInLoginItems().existingReference != nil)
}
class func toggleShouldLaunchAtStartup() {
let itemReferences = itemReferencesInLoginItems()
if (itemReferences.existingReference == nil) {
NSApplication.addToStartupItems(itemReferences.lastReference)
} else {
NSApplication.removeFromStartupItems(itemReferences.existingReference)
}
}
class func setShouldLaunchAtStartup(launchAtStartup : Bool) {
let itemReferences = itemReferencesInLoginItems()
if (launchAtStartup && itemReferences.existingReference == nil) {
NSApplication.addToStartupItems(itemReferences.lastReference)
} else if (!launchAtStartup) {
NSApplication.removeFromStartupItems(itemReferences.existingReference)
}
}
// MARK: Private methods
private class func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItemRef?, lastReference: LSSharedFileListItemRef?) {
let itemUrl : UnsafeMutablePointer<Unmanaged<CFURL>?> = UnsafeMutablePointer<Unmanaged<CFURL>?>.alloc(1)
if let appUrl : NSURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
let loginItemsRef = LSSharedFileListCreate(
nil,
kLSSharedFileListSessionLoginItems.takeRetainedValue(),
nil
).takeRetainedValue() as LSSharedFileListRef?
if loginItemsRef != nil {
let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray
let lastItemRef: LSSharedFileListItemRef? = (loginItems.lastObject as! LSSharedFileListItemRef)
for var i = 0; i < loginItems.count; ++i {
let currentItemRef: LSSharedFileListItemRef = loginItems.objectAtIndex(i) as! LSSharedFileListItemRef
// let url = LSSharedFileListItemCopyResolvedURL(currentItemRef, 0, nil).takeRetainedValue()
if LSSharedFileListItemResolve(currentItemRef, 0, itemUrl, nil) == noErr {
if let urlRef: NSURL = itemUrl.memory?.takeRetainedValue() {
if urlRef.isEqual(appUrl) {
return (currentItemRef, lastItemRef)
}
}
} else {
print("Unknown login application")
}
}
//The application was not found in the startup list
return (nil, lastItemRef)
}
}
return (nil, nil)
}
private class func removeFromStartupItems(existingReference: LSSharedFileListItemRef?) {
if let existingReference = existingReference,
let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
LSSharedFileListItemRemove(loginItemsRef, existingReference);
}
}
private class func addToStartupItems(lastReference: LSSharedFileListItemRef?) {
if let lastReference = lastReference,
let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
if let appUrl : CFURLRef = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
LSSharedFileListInsertItemURL(loginItemsRef, lastReference, nil, nil, appUrl, nil, nil)
}
}
}
} | 2940b6a04548f95654b1cfcf5e912e2c | 44.62069 | 166 | 0.630544 | false | false | false | false |
argon/mas | refs/heads/master | MasKit/Commands/Upgrade.swift | mit | 1 | //
// Upgrade.swift
// mas-cli
//
// Created by Andrew Naylor on 30/12/2015.
// Copyright © 2015 Andrew Naylor. All rights reserved.
//
import Commandant
import CommerceKit
/// Command which upgrades apps with new versions available in the Mac App Store.
public struct UpgradeCommand: CommandProtocol {
public typealias Options = UpgradeOptions
public let verb = "upgrade"
public let function = "Upgrade outdated apps from the Mac App Store"
private let appLibrary: AppLibrary
/// Public initializer.
/// - Parameter appLibrary: AppLibrary manager.
public init() {
self.init(appLibrary: MasAppLibrary())
}
/// Internal initializer.
/// - Parameter appLibrary: AppLibrary manager.
init(appLibrary: AppLibrary = MasAppLibrary()) {
self.appLibrary = appLibrary
}
/// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> {
let updateController = CKUpdateController.shared()
let updates: [CKUpdate]
let apps = options.apps
if apps.count > 0 {
// convert input into a list of appId's
let appIds: [UInt64]
appIds = apps.compactMap {
if let appId = UInt64($0) {
return appId
}
if let appId = appLibrary.appIdsByName[$0] {
return appId
}
return nil
}
// check each of those for updates
updates = appIds.compactMap {
updateController?.availableUpdate(withItemIdentifier: $0)
}
guard updates.count > 0 else {
printWarning("Nothing found to upgrade")
return .success(())
}
} else {
updates = updateController?.availableUpdates() ?? []
// Upgrade everything
guard updates.count > 0 else {
print("Everything is up-to-date")
return .success(())
}
}
print("Upgrading \(updates.count) outdated application\(updates.count > 1 ? "s" : ""):")
print(updates.map({ "\($0.title) (\($0.bundleVersion))" }).joined(separator: ", "))
let updateResults = updates.compactMap {
download($0.itemIdentifier.uint64Value)
}
switch updateResults.count {
case 0:
return .success(())
case 1:
return .failure(updateResults[0])
default:
return .failure(.downloadFailed(error: nil))
}
}
}
public struct UpgradeOptions: OptionsProtocol {
let apps: [String]
static func create(_ apps: [String]) -> UpgradeOptions {
return UpgradeOptions(apps: apps)
}
public static func evaluate(_ mode: CommandMode) -> Result<UpgradeOptions, CommandantError<MASError>> {
return create
<*> mode <| Argument(defaultValue: [], usage: "app(s) to upgrade")
}
}
| feccfb4487488ba73045c1656b24dc51 | 29.212121 | 107 | 0.570712 | false | false | false | false |
AlexanderMazaletskiy/SAHistoryNavigationViewController | refs/heads/master | SAHistoryNavigationViewController/NSLayoutConstraint+Fit.swift | mit | 2 | //
// NSLayoutConstraint+Fit.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/03/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
class func applyAutoLayout(superview: UIView, target: UIView, index: Int?, top: Float?, left: Float?, right: Float?, bottom: Float?, height: Float?, width: Float?) {
target.translatesAutoresizingMaskIntoConstraints = false
if let index = index {
superview.insertSubview(target, atIndex: index)
} else {
superview.addSubview(target)
}
var verticalFormat = "V:"
if let top = top {
verticalFormat += "|-(\(top))-"
}
verticalFormat += "[target"
if let height = height {
verticalFormat += "(\(height))"
}
verticalFormat += "]"
if let bottom = bottom {
verticalFormat += "-(\(bottom))-|"
}
let verticalConstrains = NSLayoutConstraint.constraintsWithVisualFormat(verticalFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "target" : target ])
superview.addConstraints(verticalConstrains)
var horizonFormat = "H:"
if let left = left {
horizonFormat += "|-(\(left))-"
}
horizonFormat += "[target"
if let width = width {
horizonFormat += "(\(width))"
}
horizonFormat += "]"
if let right = right {
horizonFormat += "-(\(right))-|"
}
let horizonConstrains = NSLayoutConstraint.constraintsWithVisualFormat(horizonFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "target" : target ])
superview.addConstraints(horizonConstrains)
}
}
| c963d60ba7bae47d5c4b08cfd8f03272 | 35.24 | 184 | 0.593819 | false | false | false | false |
beeth0ven/BNKit | refs/heads/master | BNKit/Source/Rx+/Operators.swift | mit | 1 | //
// Operators.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import UIKit
// Two way binding operator between control property and variable, that's all it takes {
infix operator <-> : DefaultPrecedence
public func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
public func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bind(to: textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
public func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx_text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx_text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bind(to: property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
| a880f1fa2de90f33152e3e53b31b38dc | 35.360825 | 211 | 0.623193 | false | false | false | false |
yoha/Thoughtless | refs/heads/master | Thoughtless/NoteDocument.swift | mit | 1 |
/*
* NoteDocument.swift
* Thoughtless
*
* Created by Yohannes Wijaya on 1/27/17.
* Copyright © 2017 Yohannes Wijaya. 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
class NoteDocument: UIDocument {
// MARK: - Stored Properties
var note: Note!
let archiveKey = "Note"
// MARK: - UIDocument Methods
override func contents(forType typeName: String) throws -> Any {
let mutableData = NSMutableData()
let archiver = NSKeyedArchiver.init(forWritingWith: mutableData)
archiver.encode(self.note, forKey: self.archiveKey)
archiver.finishEncoding()
return mutableData
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
let unarchiver = NSKeyedUnarchiver.init(forReadingWith: contents as! Data)
guard let validNote = unarchiver.decodeObject(forKey: self.archiveKey) as? Note else { return }
self.note = validNote
unarchiver.finishDecoding()
}
}
| a0dc9bee7eede2aaf5581e0f64a1c35c | 37.37037 | 103 | 0.719595 | false | false | false | false |
iOSTestApps/SwiftNote | refs/heads/master | SwiftNote/NotesTableViewController.swift | mit | 2 | //
// NotesTableViewController.swift
// SwiftNote
//
// Created by AppBrew LLC (appbrewllc.com) on 6/3/14.
// Copyright (c) 2014 Matt Lathrop. All rights reserved.
//
import CoreData
import UIKit
class NotesTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var managedObjectContext: NSManagedObjectContext {
get {
if !(_managedObjectContext != nil) {
_managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
}
return _managedObjectContext!
}
}
var _managedObjectContext: NSManagedObjectContext? = nil
var fetchedResultsController: NSFetchedResultsController {
get {
if !(_fetchedResultsController != nil) {
// set up fetch request
var fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(kEntityNameNoteEntity, inManagedObjectContext: (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext)
// sort by last updated
var sortDescriptor = NSSortDescriptor(key: "modifiedAt", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
_fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext, sectionNameKeyPath: nil, cacheName: "allNotesCache")
_fetchedResultsController!.delegate = self
}
return _fetchedResultsController!;
}
}
var _fetchedResultsController: NSFetchedResultsController? = nil
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.fetchedResultsController.performFetch(nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == kSegueIdentifierNotesTableToNoteDetailEdit) {
let entity = self.fetchedResultsController.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) as NSManagedObject
let note = Note.noteFromNoteEntity(entity)
let viewController = segue.destinationViewController as NoteDetailViewController
viewController.note = note
}
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return self.fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections?[section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(_: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kReuseIdentifierNotesTableViewCell, forIndexPath: indexPath) as NotesTableViewCell
let entity = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
let note = Note.noteFromNoteEntity(entity)
cell.configure(note: note, indexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let entity = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
let note = Note.noteFromNoteEntity(entity)
note.deleteInManagedObjectContext((UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext)
(UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
}
// MARK: - fetched results controller delegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
let cell = tableView.cellForRowAtIndexPath(indexPath) as NotesTableViewCell
let note = self.fetchedResultsController.sections?[indexPath.section][indexPath.row] as Note
cell.configure(note: note, indexPath: indexPath)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
| f895b2569f63425239f5b4fa708d4c55 | 43.208955 | 251 | 0.708643 | false | false | false | false |
dhatto/myFirstSwift | refs/heads/master | mySwiftConsole/ramen.swift | apache-2.0 | 1 | //
// ramen.swift
// mySwiftConsole
//
// Created by daigoh on 2016/11/22.
// Copyright © 2016年 touhu. All rights reserved.
//
import Foundation
typealias CompletionHandler = ((Void)?) -> Name
class Ramen {
var ingredient:Ingredient // 素材
let instruction = ["茹で方":"固めに茹でる", "スープの作り方":"にぼしはたっぷり", "チャーシューの作り方":"じっくりコトコト"]
init(ingredient:Ingredient) {
self.ingredient = ingredient
}
func cook2(handler: (()->Void)?) {
if let completion = handler {
completion()
}
}
// 引数にString、戻り値がvoidのクロージャを引数に持つ
func cook(handler: ((String) -> Void)?) -> Void {
print("ラーメンの説明書を参照する")
for(key, val) in instruction {
print("\(key)")
print("\(val)")
}
print("材料:")
print("\(ingredient.noodles) + \(ingredient.soup) + \(ingredient.topping)")
// クロージャが指定されているか確認
if let completion = handler {
// yesなのでtrue
completion("出来上がりっ!")
}
}
}
| c9bd0fa98431986a6e3470453c0651da | 21.622222 | 85 | 0.554028 | false | false | false | false |
saidmarouf/SMZoomTransition | refs/heads/master | ZoomTransition/SMZoomModalAnimator.swift | mit | 1 | //
// SMZoomModalAnimator.swift
// ZoomTransition
//
// Created by Said Marouf on 8/28/15.
// Copyright © 2015 Said Marouf. All rights reserved.
//
import Foundation
import UIKit
/// Zoom transition that suits presenting view controllers modally
class SMZoomModalAnimator: NSObject {
private var presenting: Bool = true
}
extension SMZoomModalAnimator: SMZoomAnimatedTransitioning {
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let containerView = transitionContext.containerView(),
fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
transitionContext.completeTransition(false)
return
}
if presenting {
containerView.addSubview(toViewController.view)
toViewController.view.frame = containerView.bounds
toViewController.view.alpha = 0.5
UIView.animateWithDuration(animationDuration,
animations: {
toViewController.view.alpha = 1.0
},
completion: { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
)
}
else {
UIView.animateWithDuration(animationDuration,
animations: {
fromViewController.view.alpha = 0.0
toViewController.view.alpha = 1.0
},
completion: { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
)
}
imageAnimationBlock(transitionContext)?()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return animationDuration
}
}
extension SMZoomModalAnimator: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
| bbe239a9fe64b5b7858e5d7383ea5922 | 35.347222 | 217 | 0.662973 | false | false | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/BottomCenterWidth.Individual.swift | apache-2.0 | 1 | //
// BottomCenterWidth.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct BottomCenterWidth {
let bottomCenter: LayoutElement.Point
let width: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.BottomCenterWidth {
private func makeFrame(bottomCenter: Point, width: Float, height: Float) -> Rect {
let x = bottomCenter.x - width.half
let y = bottomCenter.y - height
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Height
extension IndividualProperty.BottomCenterWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType {
public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let bottomCenter = self.bottomCenter.evaluated(from: parameters)
let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0))
let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width))
return self.makeFrame(bottomCenter: bottomCenter, width: width, height: height)
}
}
| 4f795b3904f8d154884fef4d340d500b | 22.826923 | 116 | 0.733656 | false | false | false | false |
RxSugar/RxSugar | refs/heads/master | RxSugar/ValueSetter.swift | mit | 1 | import RxSwift
public struct ValueSetter<HostType: AnyObject, T>: ObserverType {
public typealias E = T
private weak var host: HostType?
private let setter: (HostType, T)->()
public init(host: HostType, setter: @escaping (HostType, T)->()) {
self.host = host
self.setter = setter
}
public func on(_ event: Event<T>) {
guard case .next(let value) = event, let host = host else { return }
setter(host, value)
}
}
| 6b0a35a0b128f2df03caa9031c26aabd | 24.352941 | 70 | 0.677494 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Library/ViewModels/ProjectCreatorViewModel.swift | apache-2.0 | 1 | import KsApi
import Prelude
import ReactiveSwift
import WebKit
public protocol ProjectCreatorViewModelInputs {
/// Call with the project given to the view.
func configureWith(project: Project)
/// Call with the navigation action given to the webview's delegate method. Returns the policy that can
/// be returned from the delegate method.
func decidePolicy(forNavigationAction action: WKNavigationActionData) -> WKNavigationActionPolicy
/// Call when the view loads.
func viewDidLoad()
}
public protocol ProjectCreatorViewModelOutputs {
/// Emits when we should return to project page.
var goBackToProject: Signal<(), Never> { get }
/// Emits when the LoginToutViewController should be presented.
var goToLoginTout: Signal<LoginIntent, Never> { get }
/// Emits when we should navigate to the message dialog.
var goToMessageDialog: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never> { get }
/// Emits when we should open a safari browser with the URL.
var goToSafariBrowser: Signal<URL, Never> { get }
/// Emits a request that should be loaded into the web view.
var loadWebViewRequest: Signal<URLRequest, Never> { get }
}
public protocol ProjectCreatorViewModelType {
var inputs: ProjectCreatorViewModelInputs { get }
var outputs: ProjectCreatorViewModelOutputs { get }
}
public final class ProjectCreatorViewModel: ProjectCreatorViewModelType, ProjectCreatorViewModelInputs,
ProjectCreatorViewModelOutputs {
public init() {
let navigationAction = self.navigationAction.signal.skipNil()
let project = Signal.combineLatest(self.projectProperty.signal.skipNil(), self.viewDidLoadProperty.signal)
.map(first)
let messageCreatorRequest = navigationAction
.filter { $0.navigationType == .linkActivated }
.filter { isMessageCreator(request: $0.request) }
.map { $0.request }
self.loadWebViewRequest = project.map {
URL(string: $0.urls.web.project)?.appendingPathComponent("creator_bio")
}
.skipNil()
.map { AppEnvironment.current.apiService.preparedRequest(forURL: $0) }
self.decidedPolicy <~ navigationAction
.map { $0.navigationType == .other ? .allow : .cancel }
self.goToLoginTout = messageCreatorRequest.ignoreValues()
.filter { AppEnvironment.current.currentUser == nil }
.map { .messageCreator }
self.goToMessageDialog = project
.takeWhen(messageCreatorRequest)
.filter { _ in AppEnvironment.current.currentUser != nil }
.map { (MessageSubject.project($0), .projectPage) }
self.goBackToProject = Signal.combineLatest(project, navigationAction)
.filter { $1.navigationType == .linkActivated }
.filter { project, navigation in
project.urls.web.project == navigation.request.url?.absoluteString
}
.ignoreValues()
self.goToSafariBrowser = Signal.combineLatest(project, navigationAction)
.filter { $1.navigationType == .linkActivated }
.filter { !isMessageCreator(request: $1.request) }
.filter { project, navigation in
project.urls.web.project != navigation.request.url?.absoluteString
}
.map { $1.request.url }
.skipNil()
}
fileprivate let projectProperty = MutableProperty<Project?>(nil)
public func configureWith(project: Project) {
self.projectProperty.value = project
}
fileprivate let navigationAction = MutableProperty<WKNavigationActionData?>(nil)
fileprivate let decidedPolicy = MutableProperty(WKNavigationActionPolicy.cancel)
public func decidePolicy(forNavigationAction action: WKNavigationActionData) -> WKNavigationActionPolicy {
self.navigationAction.value = action
return self.decidedPolicy.value
}
fileprivate let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
public let goBackToProject: Signal<(), Never>
public let goToLoginTout: Signal<LoginIntent, Never>
public let goToMessageDialog: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never>
public let goToSafariBrowser: Signal<URL, Never>
public let loadWebViewRequest: Signal<URLRequest, Never>
public var inputs: ProjectCreatorViewModelInputs { return self }
public var outputs: ProjectCreatorViewModelOutputs { return self }
}
private func isMessageCreator(request: URLRequest) -> Bool {
if let nav = Navigation.match(request), case .project(_, .messageCreator, _) = nav { return true }
return false
}
| fcbf2eb8ecb42508571a60491f7bf61d | 37.239316 | 110 | 0.740277 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCPageViewController.swift | lgpl-2.1 | 2 | //
// NCPageViewController.swift
// Neocom
//
// Created by Artem Shimanski on 21.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
class NCPageViewController: UIViewController, UIScrollViewDelegate {
lazy var pageControl: NCSegmentedPageControl = NCSegmentedPageControl()
lazy var scrollView: UIScrollView = UIScrollView()
var viewControllers: [UIViewController]? {
didSet {
for controller in oldValue ?? [] {
controller.removeObserver(self, forKeyPath: "title")
}
for controller in viewControllers ?? [] {
controller.addObserver(self, forKeyPath: "title", options: [], context: nil)
}
pageControl.titles = viewControllers?.map({$0.title?.uppercased() ?? "-"}) ?? []
if (currentPage == nil || viewControllers?.contains(currentPage!) != true) && viewControllers?.isEmpty == false {
currentPage = scrollView.bounds.size.width > 0
? viewControllers![Int((scrollView.contentOffset.x / scrollView.bounds.size.width).rounded()).clamped(to: 0...(viewControllers!.count - 1))]
: viewControllers?.first
let noParent = currentPage?.parent == nil
if noParent {
addChild(viewController: currentPage!)
}
let appearance: Appearance? = isViewLoaded && transitionCoordinator == nil ? Appearance(true, controller: currentPage!) : nil
if currentPage?.view.superview == nil {
let view = UIView(frame: currentPage!.view.bounds)
view.backgroundColor = .clear
view.addSubview(currentPage!.view)
scrollView.addSubview(view)
}
appearance?.finish()
if noParent {
currentPage?.didMove(toParentViewController: self)
}
}
if isViewLoaded {
view.setNeedsLayout()
}
}
}
var currentPage: UIViewController? {
didSet {
guard toolbarItemsOverride == nil else {return}
setToolbarItems(currentPage?.toolbarItems, animated: true)
}
}
private var toolbarItemsOverride: [UIBarButtonItem]?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.canCancelContentTouches = false
// scrollView.delaysContentTouches = false
self.toolbarItemsOverride = self.toolbarItems
pageControl.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pageControl)
view.addSubview(scrollView)
pageControl.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor)
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[top]-0-[page]-0-[scrollView]", options: [], metrics: nil, views: ["top": topLayoutGuide, "page": pageControl, "scrollView": scrollView]))
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
else {
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[top]-0-[page]-0-[scrollView]-0-[bottom]", options: [], metrics: nil, views: ["top": topLayoutGuide, "bottom": bottomLayoutGuide, "page": pageControl, "scrollView": scrollView]))
}
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[page]-0-|", options: [], metrics: nil, views: ["page": pageControl]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollView]-0-|", options: [], metrics: nil, views: ["scrollView": scrollView]))
pageControl.scrollView = scrollView
scrollView.delegate = self
scrollView.isPagingEnabled = true
}
deinit {
for controller in viewControllers ?? [] {
controller.removeObserver(self, forKeyPath: "title")
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
pageControl.titles = viewControllers?.map({$0.title?.uppercased() ?? "-"}) ?? []
}
else {
return super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let contentSize = CGSize(width: scrollView.bounds.size.width * CGFloat(viewControllers?.count ?? 0), height: scrollView.bounds.size.height)
if scrollView.contentSize != contentSize {
scrollView.contentSize = CGSize(width: scrollView.bounds.size.width * CGFloat(viewControllers?.count ?? 0), height: scrollView.bounds.size.height)
for (i, controller) in (viewControllers ?? []).enumerated() {
if let view = controller.view.superview {
view.frame = frameForPage(at: i)
controller.view.frame = view.bounds
}
}
if let currentPage = currentPage, let i = viewControllers?.index(of: currentPage) {
self.scrollView.contentOffset.x = CGFloat(i) * scrollView.bounds.size.width
}
if !scrollView.isDragging && !scrollView.isDecelerating {
scrollViewDidEndScrolling()
}
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
for controller in viewControllers ?? [] {
controller.setEditing(editing, animated: animated)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// if let currentPage = currentPage, let i = viewControllers?.index(of: currentPage) {
// coordinator.animate(alongsideTransition: { _ in
// self.scrollView.contentOffset.x = CGFloat(i) * size.width
// }, completion: nil)
//
// }
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
scrollViewDidEndScrolling()
}
//MARK: - UIScrollViewDelegate
private class Appearance {
let controller: UIViewController
let isAppearing: Bool
init(_ isAppearing: Bool, controller: UIViewController) {
self.isAppearing = isAppearing
controller.beginAppearanceTransition(isAppearing, animated: false)
self.controller = controller
}
private var isFinished: Bool = false
func finish() {
guard !isFinished else {return}
controller.endAppearanceTransition()
isFinished = true
}
deinit {
finish()
}
}
private var appearances: [Appearance] = []
private var pendingChildren: [UIViewController] = []
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.setNeedsLayout()
for (i, controller) in (viewControllers ?? []).enumerated() {
if appearances.first(where: {$0.controller === controller}) == nil {
let frame = frameForPage(at: i)
if frame.intersects(scrollView.bounds) {
if controller == currentPage {
appearances.append(Appearance(false, controller: controller))
}
else {
if controller.parent == nil {
addChild(viewController: controller)
pendingChildren.append(controller)
}
appearances.append(Appearance(true, controller: controller))
if controller.view.superview == nil {
controller.view.translatesAutoresizingMaskIntoConstraints = true
let view = UIView(frame: frame)
controller.view.frame = view.bounds
view.backgroundColor = .clear
view.addSubview(controller.view)
scrollView.addSubview(view)
}
}
}
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidEndScrolling()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollViewDidEndScrolling()
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollViewDidEndScrolling()
}
//MARK: - Private
private func addChild(viewController: UIViewController) {
addChildViewController(viewController)
}
private func scrollViewDidEndScrolling() {
let copy = appearances
for appearance in copy {
let controller = appearance.controller
guard let i = viewControllers?.index(of: controller) else {continue}
if frameForPage(at: i).intersects(scrollView.bounds) {
if !appearance.isAppearing {
controller.beginAppearanceTransition(true, animated: false)
}
currentPage = controller
}
else {
if appearance.isAppearing {
controller.beginAppearanceTransition(false, animated: false)
}
controller.view.superview?.removeFromSuperview()
controller.view.removeFromSuperview()
}
}
for controller in pendingChildren {
controller.didMove(toParentViewController: self)
}
pendingChildren = []
appearances = []
}
private func frameForPage(at index: Int) -> CGRect {
var frame = scrollView.bounds
frame.origin.y = 0
frame.origin.x = frame.size.width * CGFloat(index)
return frame
}
}
| c6c271b19a76b8fa4f716b25b0c6152c | 31.244526 | 261 | 0.714884 | false | false | false | false |
futomtom/DynoOrder | refs/heads/branch | Dyno/Pods/Segmentio/Segmentio/Source/Cells/SegmentioCellWithImageOverLabel.swift | mit | 3 | //
// SegmentioCellWithImageOverLabel.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
class SegmentioCellWithImageOverLabel: SegmentioCell {
override func setupConstraintsForSubviews() {
super.setupConstraintsForSubviews()
guard let imageContainerView = imageContainerView else {
return
}
guard let containerView = containerView else {
return
}
let metrics = ["labelHeight": segmentTitleLabelHeight]
let views = [
"imageContainerView": imageContainerView,
"containerView": containerView
]
// main constraints
let segmentImageViewHorizontConstraint = NSLayoutConstraint.constraints(
withVisualFormat: "|-[imageContainerView]-|",
options: [],
metrics: nil,
views: views)
NSLayoutConstraint.activate(segmentImageViewHorizontConstraint)
let segmentTitleLabelHorizontConstraint = NSLayoutConstraint.constraints(
withVisualFormat: "|-[containerView]-|",
options: [.alignAllCenterX],
metrics: nil,
views: views
)
NSLayoutConstraint.activate(segmentTitleLabelHorizontConstraint)
let contentViewVerticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:[imageContainerView]-[containerView(labelHeight)]",
options: [],
metrics: metrics,
views: views)
NSLayoutConstraint.activate(contentViewVerticalConstraints)
// custom constraints
topConstraint = NSLayoutConstraint(
item: imageContainerView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: padding
)
topConstraint?.isActive = true
bottomConstraint = NSLayoutConstraint(
item: contentView,
attribute: .bottom,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1,
constant: padding
)
bottomConstraint?.isActive = true
}
}
| f08f1b2690207f24e6176ebfccfc5147 | 29.278481 | 84 | 0.588629 | false | false | false | false |
microlimbic/Matrix | refs/heads/master | Matrix/Sources/Operations/Operators.swift | mit | 1 | //
// Operators.swift
// Matrix
//
// Created by Grady Zhuo on 11/29/15.
// Copyright © 2015 Limbic. All rights reserved.
//
import Accelerate
infix operator ** {
}
//Outer
infix operator >** {
}
//Inner
infix operator <** {
}
infix operator +! {
}
infix operator +? {
}
infix operator -! {
}
infix operator -? {
}
infix operator *! {
}
infix operator *? {
}
prefix operator -! {
}
prefix operator -? {
}
prefix operator ^ {
}
//MARK: - Equatable Protocol Implement
public func ==<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs: T) -> Bool {
guard let lEntries = try? lhs.entries() else{
return false
}
guard let rEntries = try? rhs.entries() else{
return false
}
guard lhs.colsCount == rhs.colsCount && lhs.rowsCount == rhs.rowsCount else {
return false
}
return lEntries.elementsEqual(rEntries)
}
//MARK: - Operator Function
public func +<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:U) throws -> T {
return try lhs.summed(right: rhs)
}
public func +<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Double) -> T {
return lhs.summed(by: rhs)
}
public func +<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: Double, rhs:T) -> T {
return rhs.summed(by: lhs)
}
public func +<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Float) -> T {
return lhs.summed(by: rhs)
}
public func +<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: Float, rhs:T) -> T {
return rhs.summed(by: lhs)
}
public func -<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:U) throws -> T {
return try lhs.differenced(right: rhs)
}
public func -<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Double) -> T {
return lhs.differenced(by: rhs)
}
public func -<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: Double, rhs:T) -> T {
return rhs.differenced(by: lhs)
}
public func -<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Float) -> T {
return lhs.differenced(by: rhs)
}
public func -<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: Float, rhs:T) -> T {
return rhs.differenced(by: lhs)
}
public prefix func -<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(rhs: T) throws -> T {
return try rhs.inversed()
}
public prefix func ^<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(rhs: T) -> T {
return rhs.transposed
}
public func *<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:U) throws -> T {
return try lhs.producted(right: rhs)
}
public func *<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Double) -> T {
return lhs.producted(by: rhs)
}
public func *<T:Basic, U:Basic where T.Count == la_count_t, T.RawValue == la_object_t, U.Count == la_count_t, U.RawValue == la_object_t>(lhs: T, rhs:Float) -> T {
return lhs.producted(by: rhs)
}
public func **<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T) throws -> T {
return try lhs.producted(elementwise: rhs)
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Int) -> T {
return lhs.producted(scalar: Double(rhs))
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Double) -> T {
return lhs.producted(scalar: rhs)
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Float) -> T {
return lhs.producted(scalar: rhs)
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Int, rhs:T) -> T {
return rhs.producted(scalar: Double(lhs))
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Double, rhs:T) -> T {
return rhs.producted(scalar: lhs)
}
public func *<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Float, rhs:T) -> T {
return rhs.producted(scalar: lhs)
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Int) -> T {
return lhs.producted(scalar: 1.0/Double(rhs))
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Double) -> T {
return lhs.producted(scalar: 1.0/rhs)
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:Float) -> T {
return lhs.producted(scalar: 1.0/rhs)
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Int, rhs:T) -> T {
return rhs.producted(scalar: 1.0/Double(lhs))
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Double, rhs:T) -> T {
return rhs.producted(scalar: 1.0/lhs)
}
public func /<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: Float, rhs:T) -> T {
return rhs.producted(scalar: 1.0/lhs)
}
public func ~>(lhs:Matrix, rhs:Vector) throws -> Matrix {
return try lhs.solved(rightObject: rhs)
}
//MARK: - Convenience Operator
public func +!<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T)-> T!{
return try! lhs.summed(right: rhs)
}
public func +?<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T)-> T!{
return try? lhs.summed(right: rhs)
}
public func -?<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T) -> T? {
return try? lhs.differenced(right: rhs)
}
public func -!<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T) -> T! {
return try! lhs.differenced(right: rhs)
}
public prefix func -!<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(rhs: T) -> T! {
return try! rhs.inversed()
}
public prefix func -?<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(rhs: T) -> T? {
return try? rhs.inversed()
}
public func *!<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T) -> T! {
return try! lhs.producted(elementwise: rhs)
}
public func *?<T:Basic where T.Count == la_count_t, T.RawValue == la_object_t>(lhs: T, rhs:T) -> T? {
return try? lhs.producted(elementwise: rhs)
}
| f362aeea5c53083cfd5ec1a293c44bf7 | 29.748918 | 165 | 0.632268 | false | false | false | false |
apple/swift | refs/heads/main | stdlib/public/Cxx/std/String.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension std.string {
public init(_ string: String) {
self.init()
for char in string.utf8 {
self.push_back(value_type(bitPattern: char))
}
}
}
extension std.string: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
}
extension String {
public init(cxxString: std.string) {
let buffer = UnsafeBufferPointer<CChar>(
start: cxxString.__c_strUnsafe(),
count: cxxString.size())
self = buffer.withMemoryRebound(to: UInt8.self) {
String(decoding: $0, as: UTF8.self)
}
withExtendedLifetime(cxxString) {}
}
}
| 86ff293a6a4c02dd05947572e0c42582 | 28.789474 | 80 | 0.590989 | false | false | false | false |
wangyuanou/Coastline | refs/heads/master | Coastline/UI/View+Design.swift | mit | 1 | //
// View+Design.swift
// Coastline
//
// Created by 王渊鸥 on 2016/10/22.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import UIKit
public extension UIView {
@IBInspectable var borderWidth:CGFloat {
set { self.layer.borderWidth = newValue }
get { return self.layer.borderWidth }
}
@IBInspectable var boarderColor:UIColor {
set { self.layer.borderColor = newValue.cgColor }
get {
guard let c = self.layer.borderColor else { return UIColor.black }
return UIColor(cgColor: c)
}
}
@IBInspectable var clipMask:Bool {
set { self.layer.masksToBounds = newValue }
get { return self.layer.masksToBounds }
}
@IBInspectable var cornerRadius:CGFloat {
set { self.layer.cornerRadius = newValue }
get { return self.layer.cornerRadius }
}
@IBInspectable var shadowOpacity:CGFloat {
set { self.layer.shadowOpacity = Float(newValue) }
get { return CGFloat(self.layer.shadowOpacity) }
}
@IBInspectable var shadowRadius:CGFloat {
set { self.layer.shadowRadius = newValue }
get { return self.layer.shadowRadius }
}
@IBInspectable var shadowOffset:CGSize {
set { self.layer.shadowOffset = newValue }
get { return self.layer.shadowOffset }
}
@IBInspectable var shadowColor:UIColor {
set { self.layer.shadowColor = newValue.cgColor }
get {
guard let c = self.layer.shadowColor else { return UIColor.black }
return UIColor(cgColor: c)
}
}
}
| cad52455379989a5ee7b19e520880bce | 23.258621 | 69 | 0.707178 | false | false | false | false |
zisko/swift | refs/heads/master | test/Index/roles.swift | apache-2.0 | 1 | // RUN: rm -rf %t
// RUN: mkdir -p %t
//
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/imported_swift_module.swift
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s -I %t | %FileCheck %s
import func imported_swift_module.importedFunc
// CHECK: [[@LINE-1]]:35 | function/Swift | importedFunc() | s:21imported_swift_module0A4FuncyyF | Ref | rel: 0
import var imported_swift_module.importedGlobal
// CHECK: [[@LINE-1]]:34 | variable/Swift | importedGlobal | s:21imported_swift_module0A6GlobalSivp | Ref | rel: 0
// Definition
let x = 2
// CHECK: [[@LINE-1]]:5 | variable/Swift | x | s:14swift_ide_test1xSivp | Def | rel: 0
// Definition + Read of x
var y = x + 1
// CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:14swift_ide_test1ySivp | Def | rel: 0
// CHECK: [[@LINE-2]]:9 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
// CHECK: [[@LINE-3]]:11 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref | rel: 0
// Read of x + Write of y
y = x + 1
// CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Writ | rel: 0
// CHECK: [[@LINE-2]]:5 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
// CHECK: [[@LINE-3]]:7 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref | rel: 0
// Read of y + Write of y
y += x
// CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Read,Writ | rel: 0
// CHECK: [[@LINE-2]]:3 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref | rel: 0
// CHECK: [[@LINE-3]]:6 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
var z: Int {
// CHECK: [[@LINE-1]]:5 | variable/Swift | z | s:14swift_ide_test1zSivp | Def | rel: 0
get {
// CHECK: [[@LINE-1]]:3 | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg | Def,RelChild,RelAcc | rel: 1
return y
// CHECK: [[@LINE-1]]:12 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg
}
set {
// CHECK: [[@LINE-1]]:3 | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs | Def,RelChild,RelAcc | rel: 1
y = newValue
// CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Writ,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs
}
}
// Write + Read of z
z = z + 1
// CHECK: [[@LINE-1]]:1 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Writ | rel: 0
// CHECK: [[@LINE-2]]:1 | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs | Ref,Call,Impl | rel: 0
// CHECK: [[@LINE-3]]:5 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Read | rel: 0
// CHECK: [[@LINE-4]]:5 | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg | Ref,Call,Impl | rel: 0
// Call
func aCalledFunction(a: Int, b: inout Int) {
// CHECK: [[@LINE-1]]:6 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Def | rel: 0
// CHECK: [[@LINE-2]]:22 | param/Swift | a | s:{{.*}} | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
// CHECK: [[@LINE-4]]:30 | param/Swift | b | s:{{.*}} | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
var _ = a + b
// CHECK: [[@LINE-1]]:11 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
// CHECK: [[@LINE-3]]:15 | param/Swift | b | s:{{.*}} | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
b = a + 1
// CHECK: [[@LINE-1]]:3 | param/Swift | b | s:{{.*}} | Ref,Writ,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
// CHECK: [[@LINE-3]]:7 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
_ = { ignored in ignored + 1}
// CHECK-NOT: [[@LINE-1]]:9 {{.*}} | ignored | {{.*}}
}
aCalledFunction(a: 1, b: &z)
// CHECK: [[@LINE-1]]:1 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call | rel: 0
// CHECK: [[@LINE-2]]:27 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Read,Writ | rel: 0
func aCaller() {
// CHECK: [[@LINE-1]]:6 | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF | Def | rel: 0
aCalledFunction(a: 1, b: &z)
// CHECK: [[@LINE-1]]:3 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call,RelCall,RelCont | rel: 1
// CHECK-NEXT: RelCall,RelCont | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF
}
let aRef = aCalledFunction
// CHECK: [[@LINE-1]]:12 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref | rel: 0
// RelationChildOf, Implicit
struct AStruct {
// CHECK: [[@LINE-1]]:8 | struct/Swift | AStruct | [[AStruct_USR:.*]] | Def | rel: 0
let y: Int = 2
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | y | [[AStruct_y_USR:.*]] | Def,RelChild | rel: 1
var x: Int
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | x | [[AStruct_x_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]]
mutating func aMethod() {
// CHECK: [[@LINE-1]]:17 | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]]
x += 1
// CHECK: [[@LINE-1]]:5 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Read,Writ,RelCont | rel: 1
// CHECK-NEXT: RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
// CHECK: [[@LINE-3]]:5 | instance-method/acc-get/Swift | getter:x | s:14swift_ide_test7AStructV1xSivg | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
// CHECK-NEXT: RelRec | struct/Swift | AStruct | [[AStruct_USR]]
// CHECK: [[@LINE-6]]:5 | instance-method/acc-set/Swift | setter:x | s:14swift_ide_test7AStructV1xSivs | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
// CHECK-NEXT: RelRec | struct/Swift | AStruct | [[AStruct_USR]]
// CHECK: [[@LINE-9]]:7 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
}
// RelationChildOf, RelationAccessorOf
subscript(index: Int) -> Int {
// CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]]
get {
// CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | s:14swift_ide_test7AStructVyS2icig | Def,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip
return x
}
set {
// CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | s:14swift_ide_test7AStructVyS2icis | Def,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2ici
x = newValue
}
}
}
class AClass {
// CHECK: [[@LINE-1]]:7 | class/Swift | AClass | [[AClass_USR:.*]] | Def | rel: 0
var y: AStruct
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | y | [[AClass_y_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR:.*]] | Def,Dyn,Impl,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | y | [[AClass_y_USR]]
// CHECK: [[@LINE-4]]:7 | instance-method/acc-set/Swift | setter:y | [[AClass_y_set_USR:.*]] | Def,Dyn,Impl,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | y | [[AClass_y_USR]]
var z: [Int]
var computed_p: Int { return 0 }
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | computed_p | [[AClass_computed_p_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:23 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | computed_p | [[AClass_computed_p_USR]]
// CHECK-NOT: acc-set/Swift | setter:computed_p |
init(x: Int) {
y = AStruct(x: x)
// CHECK: [[@LINE-1]]:17 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,RelCont | rel: 1
// CHECK: [[@LINE-2]]:9 | struct/Swift | AStruct | [[AStruct_USR]] | Ref,RelCont | rel: 1
self.z = [1, 2, 3]
}
subscript(index: Int) -> Int {
// CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR:.*]] | Def,RelChild | rel: 1
get { return z[0] }
// CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | [[AClass_subscript_get_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1
set { z[0] = newValue }
// CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | [[AClass_subscript_set_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1
}
func foo() -> Int { return z[0] }
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | [[AClass_foo_USR:.*]] | Def,Dyn,RelChild | rel: 1
}
let _ = AClass.foo
// CHECK: [[@LINE-1]]:16 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref | rel: 0
let _ = AClass(x: 1).foo
// CHECK: [[@LINE-1]]:22 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref | rel: 0
let _ = AClass(x: 1)[1]
// CHECK: [[@LINE-1]]:21 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:21 | instance-method/acc-get/Swift | getter:subscript(_:) | [[AClass_subscript_get_USR]] | Ref,Call,Dyn,Impl,RelRec | rel: 1
let _ = AClass(x: 1)[1] = 2
// CHECK: [[@LINE-1]]:21 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Writ | rel: 0
// CHECK: [[@LINE-2]]:21 | instance-method/acc-set/Swift | setter:subscript(_:) | [[AClass_subscript_set_USR]] | Ref,Call,Dyn,Impl,RelRec | rel: 1
extension AClass {
func test_property_refs1() -> AStruct {
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR:.*]] | Def,Dyn,RelChild | rel: 1
_ = y
// CHECK: [[@LINE-1]]:9 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:9 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]]
// CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]]
return y
// CHECK: [[@LINE-1]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:12 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]]
// CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]]
}
func test_property_refs2() -> Int {
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR:.*]] | Def,Dyn,RelChild | rel: 1
_ = computed_p
// CHECK: [[@LINE-1]]:9 | instance-property/Swift | computed_p | [[AClass_computed_p_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:9 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]]
// CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]]
return computed_p
// CHECK: [[@LINE-1]]:12 | instance-property/Swift | computed_p | [[AClass_computed_p_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:12 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2
// CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]]
// CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]]
}
}
// RelationBaseOf, RelationOverrideOf
protocol X {
// CHECK: [[@LINE-1]]:10 | protocol/Swift | X | [[X_USR:.*]] | Def | rel: 0
var reqProp: Int { get }
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | reqProp | [[reqProp_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:22 | instance-method/acc-get/Swift | getter:reqProp | {{.*}} | Def,Dyn,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | reqProp | [[reqProp_USR]]
}
protocol Y {}
// CHECK: [[@LINE-1]]:10 | protocol/Swift | Y | [[Y_USR:.*]] | Def | rel: 0
class ImplementsX : X, Y {
// CHECK: [[@LINE-1]]:7 | class/Swift | ImplementsX | [[ImplementsX_USR:.*]] | Def | rel: 0
// CHECK: [[@LINE-2]]:21 | protocol/Swift | X | [[X_USR]] | Ref,RelBase | rel: 1
// CHECK-NEXT: RelBase | class/Swift | ImplementsX | [[ImplementsX_USR]]
var reqProp: Int { return 1 }
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | reqProp | [[reqPropImpl_USR:.*]] | Def,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-property/Swift | reqProp | [[reqProp_USR]]
// CHECK-NEXT: RelChild | class/Swift | ImplementsX | [[ImplementsX_USR]]
}
func TestX(x: X) {
_ = x.reqProp
// CHECK: [[@LINE-1]]:9 | instance-property/Swift | reqProp | [[reqProp_USR]] | Ref,Read,RelCont | rel: 1
}
protocol AProtocol {
// CHECK: [[@LINE-1]]:10 | protocol/Swift | AProtocol | [[AProtocol_USR:.*]] | Def | rel: 0
associatedtype T : X where T:Y
// CHECK: [[@LINE-1]]:18 | type-alias/associated-type/Swift | T | [[AProtocol_T_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | protocol/Swift | AProtocol | [[AProtocol_USR]]
// CHECK: [[@LINE-3]]:22 | protocol/Swift | X | [[X_USR]] | Ref | rel: 0
// CHECK: [[@LINE-4]]:30 | type-alias/associated-type/Swift | T | [[AProtocol_T_USR]] | Ref | rel: 0
// CHECK: [[@LINE-5]]:32 | protocol/Swift | Y | [[Y_USR]] | Ref | rel: 0
func foo() -> Int
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | s:14swift_ide_test9AProtocolP3fooSiyF | Def,Dyn,RelChild | rel: 1
// CHECK-NEXT: RelChild | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP
}
protocol Q where Self: AProtocol {}
// CHECK: [[@LINE-1]]:24 | protocol/Swift | AProtocol | [[AProtocol_USR]] | Ref | rel: 0
class ASubClass : AClass, AProtocol {
// CHECK: [[@LINE-1]]:7 | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC | Def | rel: 0
// CHECK: [[@LINE-2]]:19 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelBase | rel: 1
// CHECK-NEXT: RelBase | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC
// CHECK: [[@LINE-4]]:27 | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP | Ref,RelBase | rel: 1
// CHECK-NEXT: RelBase | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC
typealias T = ImplementsX
override func foo() -> Int {
// CHECK: [[@LINE-1]]:17 | instance-method/Swift | foo() | s:14swift_ide_test9ASubClassC3fooSiyF | Def,Dyn,RelChild,RelOver | rel: 3
// CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[AClass_foo_USR]]
// CHECK-NEXT: RelOver | instance-method/Swift | foo() | s:14swift_ide_test9AProtocolP3fooSiyF
// CHECK-NEXT: RelChild | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC
return 1
}
}
// RelationExtendedBy
extension AClass {
// CHECK: [[@LINE-1]]:11 | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR:.*]] | Def | rel: 0
// CHECK: [[@LINE-2]]:11 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelExt | rel: 1
// CHECK-NEXT: RelExt | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR]]
func bar() -> Int { return 2 }
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar() | s:14swift_ide_test6AClassC3barSiyF | Def,Dyn,RelChild | rel: 1
// CHECK-NEXT: RelChild | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR]]
}
struct OuterS {
// CHECK: [[@LINE-1]]:8 | struct/Swift | OuterS | [[OUTERS_USR:.*]] | Def | rel: 0
struct InnerS {}
// CHECK: [[@LINE-1]]:10 | struct/Swift | InnerS | [[INNERS_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NEXT: RelChild | struct/Swift | OuterS | [[OUTERS_USR]]
}
extension OuterS.InnerS : AProtocol {
// CHECK: [[@LINE-1]]:18 | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR:.*]] | Def | rel: 0
// CHECK: [[@LINE-2]]:18 | struct/Swift | InnerS | [[INNERS_USR]] | Ref,RelExt | rel: 1
// CHECK-NEXT: RelExt | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR]]
// CHECK: [[@LINE-4]]:27 | protocol/Swift | AProtocol | [[AProtocol_USR]] | Ref,RelBase | rel: 1
// CHECK-NEXT: RelBase | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR]]
// CHECK: [[@LINE-6]]:11 | struct/Swift | OuterS | [[OUTERS_USR]] | Ref | rel: 0
typealias T = ImplementsX
func foo() -> Int { return 1 }
}
protocol ExtendMe {}
protocol Whatever {}
// CHECK: [[@LINE-1]]:10 | protocol/Swift | Whatever | [[Whatever_USR:.*]] | Def | rel: 0
extension ExtendMe where Self: Whatever {}
// CHECK: [[@LINE-1]]:32 | protocol/Swift | Whatever | [[Whatever_USR]] | Ref | rel: 0
var anInstance = AClass(x: 1)
// CHECK: [[@LINE-1]]:18 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref | rel: 0
// CHECK: [[@LINE-2]]:18 | constructor/Swift | init(x:) | s:14swift_ide_test6AClassC1xACSi_tcfc | Ref,Call | rel: 0
anInstance.y.x = anInstance.y.x
// CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Writ | rel: 0
// CHECK: [[@LINE-3]]:14 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Writ | rel: 0
// CHECK: [[@LINE-4]]:18 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-5]]:29 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read | rel: 0
// CHECK: [[@LINE-6]]:31 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Read | rel: 0
anInstance.y.aMethod()
// CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Writ | rel: 0
// CHECK: [[@LINE-3]]:14 | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF | Ref,Call | rel: 0
// FIXME Write role of z occurrence on the RHS?
anInstance.z[1] = anInstance.z[0]
// CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:12 | instance-property/Swift | z | s:14swift_ide_test6AClassC1zSaySiGvp | Ref,Read,Writ | rel: 0
// CHECK: [[@LINE-3]]:19 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-4]]:30 | instance-property/Swift | z | s:14swift_ide_test6AClassC1zSaySiGvp | Ref,Read,Writ | rel: 0
let otherInstance = AStruct(x: 1)
// CHECK: [[@LINE-1]]:29 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref | rel: 0
// CHECK: [[@LINE-2]]:21 | struct/Swift | AStruct | [[AStruct_USR]] | Ref | rel: 0
_ = AStruct.init(x:)
// CHECK: [[@LINE-1]]:18 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref | rel: 0
// CHECK: [[@LINE-2]]:5 | struct/Swift | AStruct | [[AStruct_USR]] | Ref | rel: 0
let _ = otherInstance[0]
// CHECK: [[@LINE-1]]:9 | variable/Swift | otherInstance | s:14swift_ide_test13otherInstanceAA7AStructVvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:22 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Ref,Read | rel: 0
let _ = anInstance[0]
// CHECK: [[@LINE-1]]:9 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:19 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Read | rel: 0
let aSubInstance: AClass = ASubClass(x: 1)
// CHECK: [[@LINE-1]]:5 | variable/Swift | aSubInstance | s:14swift_ide_test12aSubInstanceAA6AClassCvp | Def | rel: 0
// CHECK: [[@LINE-2]]:28 | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC | Ref | rel: 0
// Dynamic, RelationReceivedBy
let _ = aSubInstance.foo()
// CHECK: [[@LINE-1]]:9 | variable/Swift | aSubInstance | s:14swift_ide_test12aSubInstanceAA6AClassCvp | Ref,Read | rel: 0
// CHECK: [[@LINE-2]]:22 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref,Call,Dyn,RelRec | rel: 1
// CHECK-NEXT: RelRec | class/Swift | AClass | s:14swift_ide_test6AClassC
// RelationContainedBy
let contained = 2
// CHECK: [[@LINE-1]]:5 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Def | rel: 0
func containing() {
// CHECK: [[@LINE-1]]:6 | function/Swift | containing() | s:14swift_ide_test10containingyyF | Def | rel: 0
let _ = contained
// CHECK: [[@LINE-1]]:11 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
var x = contained
// CHECK: [[@LINE-1]]:11 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
struct LocalStruct {
var i: AClass = AClass(x: contained)
// CHECK: [[@LINE-1]]:12 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
// CHECK: [[@LINE-3]]:21 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
// CHECK: [[@LINE-5]]:31 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
init(i _: AClass) {}
// CHECK: [[@LINE-1]]:15 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
func inner() -> Int {
let _: AClass = AClass(x: contained)
// CHECK: [[@LINE-1]]:14 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
// CHECK: [[@LINE-3]]:23 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
// CHECK: [[@LINE-5]]:33 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Ref,Read,RelCont | rel: 1
// CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
aCalledFunction(a: 1, b: &z)
// CHECK: [[@LINE-1]]:7 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call,RelCall,RelCont | rel: 1
// CHECK-NEXT: RelCall,RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
return contained
}
}
}
protocol ProtRoot {
func fooCommon()
func foo1()
func foo2()
func foo3(a : Int)
func foo3(a : String)
}
protocol ProtDerived : ProtRoot {
func fooCommon()
func bar1()
func bar2()
func bar3(_ : Int)
func bar3(_ : String)
}
extension ProtDerived {
func fooCommon() {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | fooCommon() | s:14swift_ide_test11ProtDerivedPAAE9fooCommonyyF | Def,Dyn,RelChild,RelOver | rel: 3
// CHECK-NEXT: RelOver | instance-method/Swift | fooCommon() | s:14swift_ide_test11ProtDerivedP9fooCommonyyF
// CHECK-NEXT: RelOver | instance-method/Swift | fooCommon() | s:14swift_ide_test8ProtRootP9fooCommonyyF
func foo1() {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo1() | s:14swift_ide_test11ProtDerivedPAAE4foo1yyF | Def,Dyn,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-method/Swift | foo1() | s:14swift_ide_test8ProtRootP4foo1yyF
func bar1() {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar1() | s:14swift_ide_test11ProtDerivedPAAE4bar1yyF | Def,Dyn,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-method/Swift | bar1() | s:14swift_ide_test11ProtDerivedP4bar1yyF
func foo3(a : Int) {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySi_tF | Def,Dyn,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySi_tF
func foo3(a : String) {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySS_tF | Def,Dyn,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySS_tF
func bar3(_ : Int) {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedPAAE4bar3yySiF | Def,Dyn,RelChild,RelOver | rel: 2
// CHECK-NEXT: RelOver | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedP4bar3yySiF
}
enum MyEnum {
init() {}
func enum_func() {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | enum_func() | [[MyEnum_enum_func_USR:.*]] | Def,RelChild | rel: 1
}
MyEnum().enum_func()
// CHECK: [[@LINE-1]]:10 | instance-method/Swift | enum_func() | [[MyEnum_enum_func_USR]] | Ref,Call,RelRec | rel: 1
class ClassWithFinals {
final var prop : Int { get { return 0} }
// CHECK: [[@LINE-1]]:26 | instance-method/acc-get/Swift | {{.*}} | Def,RelChild,RelAcc | rel: 1
final var prop2 = 0
// CHECK: [[@LINE-1]]:13 | instance-method/acc-get/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-2]]:13 | instance-method/acc-set/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1
final func foo() {}
// CHECK: [[@LINE-1]]:14 | instance-method/Swift | {{.*}} | Def,RelChild | rel: 1
}
final class FinalClass {
var prop : Int { get { return 0} }
// CHECK: [[@LINE-1]]:20 | instance-method/acc-get/Swift | {{.*}} | Def,RelChild,RelAcc | rel: 1
var prop2 = 0
// CHECK: [[@LINE-1]]:7 | instance-method/acc-get/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-set/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1
func foo() {}
// CHECK: [[@LINE-1]]:8 | instance-method/Swift | {{.*}} | Def,RelChild | rel: 1
}
| aa11a4a77a0f886cff6ca204fa4b8b50 | 55.444444 | 164 | 0.644758 | false | true | false | false |
skedgo/tripkit-ios | refs/heads/main | Tests/TripKitUITests/TKUIPolylineRendererStabilityTest.swift | apache-2.0 | 1 | //
// TKUIPolylineRendererStabilityTest.swift
// TripKitTests
//
// Created by Adrian Schönig on 21.06.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import XCTest
import MapKit
@testable import TripKit
@testable import TripKitUI
class TKUIPolylineRendererStabilityTest: XCTestCase {
var threads = 12
var renderers = 10
var polyline: MKPolyline!
func testSimpleMultiThreading() throws {
let group = DispatchGroup()
(1...threads).forEach { round in
group.enter()
DispatchQueue(label: "com.skedgo.tripkit.polyline-test.\(round)", qos: .default).async {
let imageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 100, height: 100))
let _ = imageRenderer.image { context in
(1...self.renderers).forEach { _ in
let renderer = TKUIPolylineRenderer(polyline: self.polyline)
renderer.draw(.world, zoomScale: 1, in: context.cgContext)
}
}
// print("Finished image in \(round)...")
group.leave()
}
}
group.wait()
XCTAssert(true)
}
func testMultipleDrawingsInMultiThreading() throws {
let group = DispatchGroup()
(1...threads).forEach { round in
group.enter()
DispatchQueue(label: "com.skedgo.tripkit.polyline-test.\(round)", qos: .default).async {
let imageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 100, height: 100))
let _ = imageRenderer.image { context in
(1...self.renderers).forEach { _ in
let renderer = TKUIPolylineRenderer(polyline: self.polyline)
renderer.draw(.world, zoomScale: 1, in: context.cgContext)
renderer.draw(.world, zoomScale: 1, in: context.cgContext)
renderer.draw(.world, zoomScale: 1, in: context.cgContext)
}
}
// print("Finished image in \(round)...")
group.leave()
}
}
group.wait()
XCTAssert(true)
}
func testSelectionMultiThreading() throws {
let group = DispatchGroup()
(1...threads).forEach { round in
group.enter()
DispatchQueue(label: "com.skedgo.tripkit.polyline-test.\(round)", qos: .default).async {
let renderers = (1...self.renderers).map { _ -> TKUIPolylineRenderer in
let renderer = TKUIPolylineRenderer(polyline: self.polyline)
renderer.selectionIdentifier = "\(round)"
renderer.selectionHandler = { Int($0) == 2 }
return renderer
}
// draw initial selection...
let imageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 100, height: 100))
let _ = imageRenderer.image { context in
renderers.forEach { $0.draw(.world, zoomScale: 1, in: context.cgContext) }
}
// ... then update
let imageRenderer2 = UIGraphicsImageRenderer(size: CGSize(width: 100, height: 100))
let _ = imageRenderer2.image { context in
renderers.forEach { $0.selectionHandler = { Int($0)?.isMultiple(of: 2) == true } }
renderers.forEach { $0.draw(.world, zoomScale: 1, in: context.cgContext) }
}
group.leave()
}
}
group.wait()
XCTAssert(true)
}
override func setUp() {
super.setUp()
let ferryPath = "~ppmEwd`z[Le@r@c@vEmEn@}@t@o@nAw@??AJ??x@n@n@V|@FfCIf@Mf@Wd@]rBeB^UZOpCiArCcAdBg@N@nAZTJn@l@Zp@R`ABx@Eh@Mn@cAlBmA|A{@z@o@d@Mh@??GK??Sd@Qt@Er@DjA\\~AfArCnBdDxCnEvBvCrGvHtEhGjCrEj@|AP~@VjCn@d]V`D`@nBf@~Ah@r@lA~@bAb@fCj@tCZ`W|A"
let ferryCoordinates = CLLocationCoordinate2D.decodePolyline(ferryPath)
polyline = MKPolyline(coordinates: ferryCoordinates, count: ferryCoordinates.count)
}
}
| d9f14c2f82339907e71be51f5ef306ab | 30.537815 | 246 | 0.61684 | false | true | false | false |
AbooJan/iOS-SDK | refs/heads/master | Examples/nearables/RangingExample-Swift/RangingExample-Swift/ViewController.swift | mit | 9 | //
// ViewController.swift
// RangingExample-Swift
//
// Created by Marcin Klimek on 05/01/15.
// Copyright (c) 2015 Estimote. All rights reserved.
//
import UIKit
class ESTTableViewCell: UITableViewCell
{
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController,
UITableViewDelegate,
UITableViewDataSource,
ESTNearableManagerDelegate
{
var nearables:Array<ESTNearable>!
var nearableManager:ESTNearableManager!
var tableView:UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Ranged Estimote Nearables";
tableView = UITableView(frame: self.view.frame)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.registerClass(ESTTableViewCell.classForCoder(), forCellReuseIdentifier: "CellIdentifier")
/*
* Initialized local nearables array
*/
nearables = []
/*
* Initialize nearables manager and start ranging
* devices around with any possible type. When nearables are ranged
* propper delegate method is invoke. Delegate method updates
* nearables array and reload table view.
*/
nearableManager = ESTNearableManager()
nearableManager.delegate = self
nearableManager.startRangingForType(ESTNearableType.All)
}
// MARK: - ESTNearableManager delegate
func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType)
{
/*
* Update local nearables array and reload table view
*/
self.nearables = nearables as Array<ESTNearable>
self.tableView.reloadData()
}
// MARK: - UITableView delegate and data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return nearables.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as ESTTableViewCell
let nearable = nearables[indexPath.row] as ESTNearable
var details:NSString = NSString(format:"Type: %@ RSSI: %zd", ESTNearableDefinitions.nameForType(nearable.type), nearable.rssi);
cell.textLabel?.text = NSString(format:"Identifier: %@", nearable.identifier);
cell.detailTextLabel?.text = details;
var imageView = UIImageView(frame: CGRectMake(self.view.frame.size.width - 60, 30, 30, 30))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.image = self.imageForNearableType(nearable.type)
cell.contentView.addSubview(imageView)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 80
}
// MARK: - Utility methods
func imageForNearableType(type: ESTNearableType) -> UIImage?
{
switch (type)
{
case ESTNearableType.Bag:
return UIImage(named: "sticker_bag")
case ESTNearableType.Bike:
return UIImage(named: "sticker_bike")
case ESTNearableType.Car:
return UIImage(named: "sticker_car")
case ESTNearableType.Fridge:
return UIImage(named: "sticker_fridge")
case ESTNearableType.Bed:
return UIImage(named: "sticker_bed")
case ESTNearableType.Chair:
return UIImage(named: "sticker_chair")
case ESTNearableType.Shoe:
return UIImage(named: "sticker_shoe")
case ESTNearableType.Door:
return UIImage(named: "sticker_door")
case ESTNearableType.Dog:
return UIImage(named: "sticker_dog")
default:
return UIImage(named: "sticker_grey")
}
}
}
| 3cc301db9c5f84b99a757f8f2e1c057f | 31.214286 | 135 | 0.637029 | false | false | false | false |
JoniVR/VerticalCardSwiper | refs/heads/main | Sources/VerticalCardSwiperFlowLayout.swift | mit | 1 | // MIT License
//
// Copyright (c) 2017 Joni Van Roost
//
// 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
/// Custom `UICollectionViewFlowLayout` that provides the flowlayout information like paging and `CardCell` movements.
internal class VerticalCardSwiperFlowLayout: UICollectionViewFlowLayout {
/// This property sets the amount of scaling for the first item.
internal var firstItemTransform: CGFloat?
/// This property enables paging per card. Default is true.
internal var isPagingEnabled: Bool = true
/// Stores the height of a CardCell.
internal var cellHeight: CGFloat?
/// Allows you to enable/disable the stacking effect. Default is `true`.
internal var isStackingEnabled: Bool = true
/// Allows you to set the view to Stack at the Top or at the Bottom. Default is `true`.
internal var isStackOnBottom: Bool = true
/// Sets how many cards of the stack are visible in the background. Default is 1.
internal var stackedCardsCount: Int = 1
internal override func prepare() {
super.prepare()
assert(collectionView?.numberOfSections == 1, "Number of sections should always be 1.")
assert(collectionView?.isPagingEnabled == false, "Paging on the collectionview itself should never be enabled. To enable cell paging, use the isPagingEnabled property of the VerticalCardSwiperFlowLayout instead.")
}
internal override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView, let cellHeight = cellHeight else { return nil }
let y = collectionView.bounds.minY - cellHeight * CGFloat(stackedCardsCount)
let newRect = CGRect(x: 0, y: y < 0 ? 0 : y, width: collectionView.bounds.maxX, height: collectionView.bounds.maxY)
let items = NSArray(array: super.layoutAttributesForElements(in: newRect)!, copyItems: true)
for object in items {
if let attributes = object as? UICollectionViewLayoutAttributes {
self.updateCellAttributes(attributes)
}
}
return items as? [UICollectionViewLayoutAttributes]
}
internal override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if self.collectionView?.numberOfItems(inSection: 0) == 0 { return nil }
if let attr = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes {
self.updateCellAttributes(attr)
return attr
}
return nil
}
internal override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
// attributes for swiping card away
return self.layoutAttributesForItem(at: itemIndexPath)
}
internal override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
// attributes for adding card
return self.layoutAttributesForItem(at: itemIndexPath)
}
// We invalidate the layout when a "bounds change" happens, for example when we scale the top cell. This forces a layout update on the flowlayout.
internal override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
// Cell paging
internal override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard
let collectionView = self.collectionView,
let cellHeight = cellHeight,
isPagingEnabled
else {
let latestOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
return latestOffset
}
// Page height used for estimating and calculating paging.
let pageHeight = cellHeight + self.minimumLineSpacing
// Make an estimation of the current page position.
let approximatePage = collectionView.contentOffset.y/pageHeight
// Determine the current page based on velocity.
let currentPage = velocity.y == 0.0 ? round(approximatePage) : (velocity.y < 0.0 ? floor(approximatePage) : ceil(approximatePage))
// Create custom flickVelocity.
let flickVelocity = velocity.y * 0.3
// Check how many pages the user flicked, if <= 1 then flickedPages should return 0.
let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity)
// Calculate newVerticalOffset.
let newVerticalOffset = ((currentPage + flickedPages) * pageHeight) - collectionView.contentInset.top
return CGPoint(x: proposedContentOffset.x, y: newVerticalOffset)
}
/**
Updates the attributes.
Here manipulate the zIndex of the cards here, calculate the positions and do the animations.
Below we'll briefly explain how the effect of scrolling a card to the background instead of the top is achieved.
Keep in mind that (x,y) coords in views start from the top left (x: 0,y: 0) and increase as you go down/to the right,
so as you go down, the y-value increases, and as you go right, the x value increases.
The two most important variables we use to achieve this effect are cvMinY and cardMinY.
* cvMinY (A): The top position of the collectionView + inset. On the drawings below it's marked as "A".
This position never changes (the value of the variable does, but the position is always at the top where "A" is marked).
* cardMinY (B): The top position of each card. On the drawings below it's marked as "B". As the user scrolls a card,
this position changes with the card position (as it's the top of the card).
When the card is moving down, this will go up, when the card is moving up, this will go down.
We then take the max(cvMinY, cardMinY) to get the highest value of those two and set that as the origin.y of the card.
By doing this, we ensure that the origin.y of a card never goes below cvMinY, thus preventing cards from scrolling upwards.
```
+---------+ +---------+
| | | |
| +-A=B-+ | | +-A-+ | ---> The top line here is the previous card
| | | | | +--B--+ | that's visible when the user starts scrolling.
| | | | | | | |
| | | | | | | | | As the card moves down,
| | | | | | | | v cardMinY ("B") goes up.
| +-----+ | | | | |
| | | +-----+ |
| +--B--+ | | +--B--+ |
| | | | | | | |
+-+-----+-+ +-+-----+-+
```
- parameter attributes: The attributes we're updating.
*/
fileprivate func updateCellAttributes(_ attributes: UICollectionViewLayoutAttributes) {
guard let collectionView = collectionView else { return }
let cvMinY = collectionView.bounds.minY + collectionView.contentInset.top
let cardMinY = attributes.frame.minY
var origin = attributes.frame.origin
let cardHeight = attributes.frame.height
let finalY = max(cvMinY, cardMinY)
let deltaY = (finalY - cardMinY) / cardHeight
transformAttributes(attributes: attributes, deltaY: deltaY)
attributes.alpha = 1 - (deltaY - CGFloat(stackedCardsCount))
// Set the attributes frame position to the values we calculated
origin.x = collectionView.frame.width/2 - attributes.frame.width/2 - collectionView.contentInset.left
origin.y = finalY
attributes.frame = CGRect(origin: origin, size: attributes.frame.size)
attributes.zIndex = attributes.indexPath.row
}
// Creates and applies a CGAffineTransform to the attributes to recreate the effect of the card going to the background.
fileprivate func transformAttributes(attributes: UICollectionViewLayoutAttributes, deltaY: CGFloat) {
if let itemTransform = firstItemTransform {
let top = isStackOnBottom ? deltaY : deltaY * -1
let scale = 1 - deltaY * itemTransform
let translationScale = CGFloat((attributes.zIndex + 1) * 10)
var t = CGAffineTransform.identity
let calculatedScale = scale > 0 ? scale : 0
t = t.scaledBy(x: calculatedScale, y: 1)
if isStackingEnabled {
t = t.translatedBy(x: 0, y: top * translationScale)
}
attributes.transform = t
}
}
}
| 22940ac8bc7a8dd25fd1fb03d6ae6341 | 47.77665 | 221 | 0.678531 | false | false | false | false |
hooman/swift | refs/heads/main | stdlib/public/Platform/POSIXError.swift | apache-2.0 | 4 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && _runtime(_ObjC)
/// Enumeration describing POSIX error codes.
@objc
public enum POSIXErrorCode : Int32 {
/// Operation not permitted.
case EPERM = 1
/// No such file or directory.
case ENOENT = 2
/// No such process.
case ESRCH = 3
/// Interrupted system call.
case EINTR = 4
/// Input/output error.
case EIO = 5
/// Device not configured.
case ENXIO = 6
/// Argument list too long.
case E2BIG = 7
/// Exec format error.
case ENOEXEC = 8
/// Bad file descriptor.
case EBADF = 9
/// No child processes.
case ECHILD = 10
/// Resource deadlock avoided.
case EDEADLK = 11
/// 11 was EAGAIN.
/// Cannot allocate memory.
case ENOMEM = 12
/// Permission denied.
case EACCES = 13
/// Bad address.
case EFAULT = 14
/// Block device required.
case ENOTBLK = 15
/// Device / Resource busy.
case EBUSY = 16
/// File exists.
case EEXIST = 17
/// Cross-device link.
case EXDEV = 18
/// Operation not supported by device.
case ENODEV = 19
/// Not a directory.
case ENOTDIR = 20
/// Is a directory.
case EISDIR = 21
/// Invalid argument.
case EINVAL = 22
/// Too many open files in system.
case ENFILE = 23
/// Too many open files.
case EMFILE = 24
/// Inappropriate ioctl for device.
case ENOTTY = 25
/// Text file busy.
case ETXTBSY = 26
/// File too large.
case EFBIG = 27
/// No space left on device.
case ENOSPC = 28
/// Illegal seek.
case ESPIPE = 29
/// Read-only file system.
case EROFS = 30
/// Too many links.
case EMLINK = 31
/// Broken pipe.
case EPIPE = 32
/// math software.
/// Numerical argument out of domain.
case EDOM = 33
/// Result too large.
case ERANGE = 34
/// non-blocking and interrupt i/o.
/// Resource temporarily unavailable.
case EAGAIN = 35
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode { return EAGAIN }
/// Operation now in progress.
case EINPROGRESS = 36
/// Operation already in progress.
case EALREADY = 37
/// ipc/network software -- argument errors.
/// Socket operation on non-socket.
case ENOTSOCK = 38
/// Destination address required.
case EDESTADDRREQ = 39
/// Message too long.
case EMSGSIZE = 40
/// Protocol wrong type for socket.
case EPROTOTYPE = 41
/// Protocol not available.
case ENOPROTOOPT = 42
/// Protocol not supported.
case EPROTONOSUPPORT = 43
/// Socket type not supported.
case ESOCKTNOSUPPORT = 44
/// Operation not supported.
case ENOTSUP = 45
/// Protocol family not supported.
case EPFNOSUPPORT = 46
/// Address family not supported by protocol family.
case EAFNOSUPPORT = 47
/// Address already in use.
case EADDRINUSE = 48
/// Can't assign requested address.
case EADDRNOTAVAIL = 49
/// ipc/network software -- operational errors
/// Network is down.
case ENETDOWN = 50
/// Network is unreachable.
case ENETUNREACH = 51
/// Network dropped connection on reset.
case ENETRESET = 52
/// Software caused connection abort.
case ECONNABORTED = 53
/// Connection reset by peer.
case ECONNRESET = 54
/// No buffer space available.
case ENOBUFS = 55
/// Socket is already connected.
case EISCONN = 56
/// Socket is not connected.
case ENOTCONN = 57
/// Can't send after socket shutdown.
case ESHUTDOWN = 58
/// Too many references: can't splice.
case ETOOMANYREFS = 59
/// Operation timed out.
case ETIMEDOUT = 60
/// Connection refused.
case ECONNREFUSED = 61
/// Too many levels of symbolic links.
case ELOOP = 62
/// File name too long.
case ENAMETOOLONG = 63
/// Host is down.
case EHOSTDOWN = 64
/// No route to host.
case EHOSTUNREACH = 65
/// Directory not empty.
case ENOTEMPTY = 66
/// quotas & mush.
/// Too many processes.
case EPROCLIM = 67
/// Too many users.
case EUSERS = 68
/// Disc quota exceeded.
case EDQUOT = 69
/// Network File System.
/// Stale NFS file handle.
case ESTALE = 70
/// Too many levels of remote in path.
case EREMOTE = 71
/// RPC struct is bad.
case EBADRPC = 72
/// RPC version wrong.
case ERPCMISMATCH = 73
/// RPC prog. not avail.
case EPROGUNAVAIL = 74
/// Program version wrong.
case EPROGMISMATCH = 75
/// Bad procedure for program.
case EPROCUNAVAIL = 76
/// No locks available.
case ENOLCK = 77
/// Function not implemented.
case ENOSYS = 78
/// Inappropriate file type or format.
case EFTYPE = 79
/// Authentication error.
case EAUTH = 80
/// Need authenticator.
case ENEEDAUTH = 81
/// Intelligent device errors.
/// Device power is off.
case EPWROFF = 82
/// Device error, e.g. paper out.
case EDEVERR = 83
/// Value too large to be stored in data type.
case EOVERFLOW = 84
// MARK: Program loading errors.
/// Bad executable.
case EBADEXEC = 85
/// Bad CPU type in executable.
case EBADARCH = 86
/// Shared library version mismatch.
case ESHLIBVERS = 87
/// Malformed Macho file.
case EBADMACHO = 88
/// Operation canceled.
case ECANCELED = 89
/// Identifier removed.
case EIDRM = 90
/// No message of desired type.
case ENOMSG = 91
/// Illegal byte sequence.
case EILSEQ = 92
/// Attribute not found.
case ENOATTR = 93
/// Bad message.
case EBADMSG = 94
/// Reserved.
case EMULTIHOP = 95
/// No message available on STREAM.
case ENODATA = 96
/// Reserved.
case ENOLINK = 97
/// No STREAM resources.
case ENOSR = 98
/// Not a STREAM.
case ENOSTR = 99
/// Protocol error.
case EPROTO = 100
/// STREAM ioctl timeout.
case ETIME = 101
/// No such policy registered.
case ENOPOLICY = 103
/// State not recoverable.
case ENOTRECOVERABLE = 104
/// Previous owner died.
case EOWNERDEAD = 105
/// Interface output queue is full.
case EQFULL = 106
/// Must be equal largest errno.
public static var ELAST: POSIXErrorCode { return EQFULL }
// FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and
// KERNEL.
}
#elseif os(Linux) || os(Android)
/// Enumeration describing POSIX error codes.
public enum POSIXErrorCode : Int32 {
/// Operation not permitted.
case EPERM = 1
/// No such file or directory.
case ENOENT = 2
/// No such process.
case ESRCH = 3
/// Interrupted system call.
case EINTR = 4
/// Input/output error.
case EIO = 5
/// Device not configured.
case ENXIO = 6
/// Argument list too long.
case E2BIG = 7
/// Exec format error.
case ENOEXEC = 8
/// Bad file descriptor.
case EBADF = 9
/// No child processes.
case ECHILD = 10
/// Try again.
case EAGAIN = 11
/// Cannot allocate memory.
case ENOMEM = 12
/// Permission denied.
case EACCES = 13
/// Bad address.
case EFAULT = 14
/// Block device required.
case ENOTBLK = 15
/// Device / Resource busy.
case EBUSY = 16
/// File exists.
case EEXIST = 17
/// Cross-device link.
case EXDEV = 18
/// Operation not supported by device.
case ENODEV = 19
/// Not a directory.
case ENOTDIR = 20
/// Is a directory.
case EISDIR = 21
/// Invalid argument.
case EINVAL = 22
/// Too many open files in system.
case ENFILE = 23
/// Too many open files.
case EMFILE = 24
/// Inappropriate ioctl for device.
case ENOTTY = 25
/// Text file busy.
case ETXTBSY = 26
/// File too large.
case EFBIG = 27
/// No space left on device.
case ENOSPC = 28
/// Illegal seek.
case ESPIPE = 29
/// Read-only file system.
case EROFS = 30
/// Too many links.
case EMLINK = 31
/// Broken pipe.
case EPIPE = 32
/// Numerical argument out of domain.
case EDOM = 33
/// Result too large.
case ERANGE = 34
/// Resource deadlock would occur.
case EDEADLK = 35
/// File name too long.
case ENAMETOOLONG = 36
/// No record locks available
case ENOLCK = 37
/// Function not implemented.
case ENOSYS = 38
/// Directory not empty.
case ENOTEMPTY = 39
/// Too many symbolic links encountered
case ELOOP = 40
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode { return .EAGAIN }
/// No message of desired type.
case ENOMSG = 42
/// Identifier removed.
case EIDRM = 43
/// Channel number out of range.
case ECHRNG = 44
/// Level 2 not synchronized.
case EL2NSYNC = 45
/// Level 3 halted
case EL3HLT = 46
/// Level 3 reset.
case EL3RST = 47
/// Link number out of range.
case ELNRNG = 48
/// Protocol driver not attached.
case EUNATCH = 49
/// No CSI structure available.
case ENOCSI = 50
/// Level 2 halted.
case EL2HLT = 51
/// Invalid exchange
case EBADE = 52
/// Invalid request descriptor
case EBADR = 53
/// Exchange full
case EXFULL = 54
/// No anode
case ENOANO = 55
/// Invalid request code
case EBADRQC = 56
/// Invalid slot
case EBADSLT = 57
public static var EDEADLOCK: POSIXErrorCode { return .EDEADLK }
/// Bad font file format
case EBFONT = 59
/// Device not a stream
case ENOSTR = 60
/// No data available
case ENODATA = 61
/// Timer expired
case ETIME = 62
/// Out of streams resources
case ENOSR = 63
/// Machine is not on the network
case ENONET = 64
/// Package not installed
case ENOPKG = 65
/// Object is remote
case EREMOTE = 66
/// Link has been severed
case ENOLINK = 67
/// Advertise error
case EADV = 68
/// Srmount error
case ESRMNT = 69
/// Communication error on send
case ECOMM = 70
/// Protocol error
case EPROTO = 71
/// Multihop attempted
case EMULTIHOP = 72
/// RFS specific error
case EDOTDOT = 73
/// Not a data message
case EBADMSG = 74
/// Value too large for defined data type
case EOVERFLOW = 75
/// Name not unique on network
case ENOTUNIQ = 76
/// File descriptor in bad state
case EBADFD = 77
/// Remote address changed
case EREMCHG = 78
/// Can not access a needed shared library
case ELIBACC = 79
/// Accessing a corrupted shared library
case ELIBBAD = 80
/// .lib section in a.out corrupted
case ELIBSCN = 81
/// Attempting to link in too many shared libraries
case ELIBMAX = 82
/// Cannot exec a shared library directly
case ELIBEXEC = 83
/// Illegal byte sequence
case EILSEQ = 84
/// Interrupted system call should be restarted
case ERESTART = 85
/// Streams pipe error
case ESTRPIPE = 86
/// Too many users
case EUSERS = 87
/// Socket operation on non-socket
case ENOTSOCK = 88
/// Destination address required
case EDESTADDRREQ = 89
/// Message too long
case EMSGSIZE = 90
/// Protocol wrong type for socket
case EPROTOTYPE = 91
/// Protocol not available
case ENOPROTOOPT = 92
/// Protocol not supported
case EPROTONOSUPPORT = 93
/// Socket type not supported
case ESOCKTNOSUPPORT = 94
/// Operation not supported on transport endpoint
case EOPNOTSUPP = 95
/// Protocol family not supported
case EPFNOSUPPORT = 96
/// Address family not supported by protocol
case EAFNOSUPPORT = 97
/// Address already in use
case EADDRINUSE = 98
/// Cannot assign requested address
case EADDRNOTAVAIL = 99
/// Network is down
case ENETDOWN = 100
/// Network is unreachable
case ENETUNREACH = 101
/// Network dropped connection because of reset
case ENETRESET = 102
/// Software caused connection abort
case ECONNABORTED = 103
/// Connection reset by peer
case ECONNRESET = 104
/// No buffer space available
case ENOBUFS = 105
/// Transport endpoint is already connected
case EISCONN = 106
/// Transport endpoint is not connected
case ENOTCONN = 107
/// Cannot send after transport endpoint shutdown
case ESHUTDOWN = 108
/// Too many references: cannot splice
case ETOOMANYREFS = 109
/// Connection timed out
case ETIMEDOUT = 110
/// Connection refused
case ECONNREFUSED = 111
/// Host is down
case EHOSTDOWN = 112
/// No route to host
case EHOSTUNREACH = 113
/// Operation already in progress
case EALREADY = 114
/// Operation now in progress
case EINPROGRESS = 115
/// Stale NFS file handle
case ESTALE = 116
/// Structure needs cleaning
case EUCLEAN = 117
/// Not a XENIX named type file
case ENOTNAM = 118
/// No XENIX semaphores available
case ENAVAIL = 119
/// Is a named type file
case EISNAM = 120
/// Remote I/O error
case EREMOTEIO = 121
/// Quota exceeded
case EDQUOT = 122
/// No medium found
case ENOMEDIUM = 123
/// Wrong medium type
case EMEDIUMTYPE = 124
/// Operation Canceled
case ECANCELED = 125
/// Required key not available
case ENOKEY = 126
/// Key has expired
case EKEYEXPIRED = 127
/// Key has been revoked
case EKEYREVOKED = 128
/// Key was rejected by service
case EKEYREJECTED = 129
/// Owner died
case EOWNERDEAD = 130
/// State not recoverable
case ENOTRECOVERABLE = 131
/// Operation not possible due to RF-kill
case ERFKILL = 132
/// Memory page has hardware error
case EHWPOISON = 133
}
#elseif os(Windows)
/// Enumeration describing POSIX error codes.
public enum POSIXErrorCode : Int32 {
/// Operation not permitted
case EPERM = 1
/// No such file or directory
case ENOENT = 2
/// No such process
case ESRCH = 3
/// Interrupted function
case EINTR = 4
/// I/O error
case EIO = 5
/// No such device or address
case ENXIO = 6
/// Argument list too long
case E2BIG = 7
/// Exec format error
case ENOEXEC = 8
/// Bad file number
case EBADF = 9
/// No spawned processes
case ECHILD = 10
/// No more processes or not enough memory or maximum nesting level reached
case EAGAIN = 11
/// Not enough memory
case ENOMEM = 12
/// Permission denied
case EACCES = 13
/// Bad address
case EFAULT = 14
/// Device or resource busy
case EBUSY = 16
/// File exists
case EEXIST = 17
/// Cross-device link
case EXDEV = 18
/// No such device
case ENODEV = 19
/// Not a directory
case ENOTDIR = 20
/// Is a directory
case EISDIR = 21
/// Invalid argument
case EINVAL = 22
/// Too many files open in system
case ENFILE = 23
/// Too many open files
case EMFILE = 24
/// Inappropriate I/O control operation
case ENOTTY = 25
/// File too large
case EFBIG = 27
/// No space left on device
case ENOSPC = 28
/// Invalid seek
case ESPIPE = 29
/// Read-only file system
case EROFS = 30
/// Too many links
case EMLINK = 31
/// Broken pipe
case EPIPE = 32
/// Math argument
case EDOM = 33
/// Result too large
case ERANGE = 34
/// Resource deadlock would occur
case EDEADLK = 36
/// Same as EDEADLK for compatibility with older Microsoft C versions
public static var EDEADLOCK: POSIXErrorCode { return .EDEADLK }
/// Filename too long
case ENAMETOOLONG = 38
/// No locks available
case ENOLCK = 39
/// Function not supported
case ENOSYS = 40
/// Directory not empty
case ENOTEMPTY = 41
/// Illegal byte sequence
case EILSEQ = 42
/// String was truncated
case STRUNCATE = 80
}
#endif
| bfcec181c30f7fd1518b7ec012a748f1 | 25.443796 | 80 | 0.560285 | false | false | false | false |
ArthurKK/Alamofire | refs/heads/master | Alamofire-master/Example/MasterViewController.swift | apache-2.0 | 69 | // MasterViewController.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
import UIKit
class MasterViewController: UITableViewController {
@IBOutlet weak var titleImageView: UIImageView!
var detailViewController: DetailViewController? = nil
var objects = NSMutableArray()
// MARK: - View Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
navigationItem.titleView = titleImageView
}
override func viewDidLoad() {
super.viewDidLoad()
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = controllers.last?.topViewController as? DetailViewController
}
}
// MARK: - UIStoryboardSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let detailViewController = segue.destinationViewController.topViewController as? DetailViewController {
func requestForSegue(segue: UIStoryboardSegue) -> Request? {
switch segue.identifier! {
case "GET":
detailViewController.segueIdentifier = "GET"
return Alamofire.request(.GET, "http://httpbin.org/get")
case "POST":
detailViewController.segueIdentifier = "POST"
return Alamofire.request(.POST, "http://httpbin.org/post")
case "PUT":
detailViewController.segueIdentifier = "PUT"
return Alamofire.request(.PUT, "http://httpbin.org/put")
case "DELETE":
detailViewController.segueIdentifier = "DELETE"
return Alamofire.request(.DELETE, "http://httpbin.org/delete")
case "DOWNLOAD":
detailViewController.segueIdentifier = "DOWNLOAD"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .CachesDirectory, domain: .UserDomainMask)
return Alamofire.download(.GET, "http://httpbin.org/stream/1", destination: destination)
default:
return nil
}
}
if let request = requestForSegue(segue) {
detailViewController.request = request
}
}
}
}
| d63a7ec19669ef6f1ec4354eb2470a99 | 41.698795 | 142 | 0.644752 | false | false | false | false |
JoeLago/MHGDB-iOS | refs/heads/master | Pods/GRDB.swift/GRDB/Record/RowConvertible+Decodable.swift | mit | 1 | private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let decoder: RowDecoder
init(decoder: RowDecoder) {
self.decoder = decoder
}
var codingPath: [CodingKey] { return decoder.codingPath }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] {
let row = decoder.row
let columnNames = Set(row.columnNames)
let scopeNames = row.scopeNames
return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) }
}
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
func decodeNil(forKey key: Key) throws -> Bool {
let row = decoder.row
return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns nil if the container does not have a value
/// associated with key, or if the value is null. The difference between
/// these states can be distinguished with a contains(_:) call.
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T?
} else if dbValue.isNull {
return nil
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
return nil
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue) {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".")
fatalError("No such column or scope: \(path)")
}
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("not implemented")
}
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
public func superDecoder() throws -> Decoder {
return decoder
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return decoder
}
}
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
let row: Row
var codingPath: [CodingKey]
let column: CodingKey
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return row[column.stringValue] == nil
}
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool { return row[column.stringValue] }
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(row[column.stringValue]) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: [column]))
}
}
}
private struct RowDecoder: Decoder {
let row: Row
init(row: Row, codingPath: [CodingKey]) {
self.row = row
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
// Asked for a value type: column name required
guard let codingKey = codingPath.last else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
}
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
}
}
extension RowConvertible where Self: Decodable {
/// Initializes a record from `row`.
public init(row: Row) {
try! self.init(from: RowDecoder(row: row, codingPath: []))
}
}
| 2f7127b22984af7139949b41a4748f39 | 51.910506 | 262 | 0.660391 | false | false | false | false |
nerdyc/Squeal | refs/heads/master | Sources/Migrations/DropIndex.swift | mit | 1 | import Foundation
extension VersionBuilder {
/// Removes an index from a database table.
///
/// - Parameters:
/// - name: The name of the index to remove.
public func dropIndex(_ name:String, file:StaticString = #file, line:UInt = #line) {
guard let index = indexNamed(name) else {
fatalError("Unable to drop index from schema: \'\(name)\' isn't in the schema", file:file, line:line)
}
guard let tableIndex = indexOfTable(index.tableName) else {
fatalError("Unable to drop index from schema: table \'\(index.tableName)\' isn't in the schema", file:file, line:line)
}
tables[tableIndex] = tables[tableIndex].droppingIndex(name)
let dropIndex = DropIndex(name:name)
transformers.append(dropIndex)
}
}
final class DropIndex : Transformer {
let name:String
init(name:String) {
self.name = name
}
func transform(_ db: Database) throws {
try db.dropIndex(name)
}
}
| 431d4ab2874d057f6ac8e5c6c862a154 | 26.921053 | 130 | 0.593779 | false | false | false | false |
FedeGens/WeePager | refs/heads/master | WeePagerDemo/BasicTextHeader.swift | mit | 1 | //
// BasicHeader.swift
// MyTableView
//
// Created by Federico Gentile on 25/12/16.
// Copyright © 2016 Federico Gentile. All rights reserved.
//
import UIKit
class BasicTextHeader: UIView {
let headerLabel = UILabel()
let backGroundToolbar = UIToolbar()
static func create(withText text: String, backgroundColor color: UIColor?) -> UIView {
let basicTextHeader = BasicTextHeader()
basicTextHeader.headerLabel.text = text
basicTextHeader.backGroundToolbar.barTintColor = (color == nil) ? basicTextHeader.backGroundToolbar.barTintColor : color
return basicTextHeader
}
override init(frame: CGRect) {
super.init(frame: frame)
//set view clearcolor
self.backgroundColor = UIColor.clear
//set backgroundtoolbar constraints
backGroundToolbar.alpha = 1.0
backGroundToolbar.clipsToBounds = true
backGroundToolbar.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(backGroundToolbar)
self.addConstraint(NSLayoutConstraint(item: backGroundToolbar, attribute: .leading, relatedBy:
.equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: backGroundToolbar, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: backGroundToolbar, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: backGroundToolbar, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
//set headerlabel constraints
headerLabel.numberOfLines = 0
headerLabel.baselineAdjustment = .alignBaselines
headerLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(headerLabel)
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func set(color: UIColor, withAlpha alpha: CGFloat) {
self.backgroundColor = color
self.alpha = alpha
}
}
| ccbbe775b417ba457e36c29ff4078816 | 42.565217 | 178 | 0.682302 | false | false | false | false |
gspd-mobi/rage-ios | refs/heads/master | Sources/Rage/Rage.swift | mit | 1 | import Foundation
open class Rage {
fileprivate init() {
// No operations.
}
open class func builder() -> Builder {
return Builder()
}
open class func builderWithBaseUrl(_ baseUrl: String) -> Builder {
return Builder(baseUrl: baseUrl)
}
public final class Builder {
let config: RageClientConfiguration
fileprivate init(baseUrl: String? = nil) {
config = RageClientConfiguration(baseUrl: baseUrl)
}
public func withSessionProvider(_ sessionProvider: SessionProvider) -> Builder {
config.sessionProvider = sessionProvider
return self
}
public func withContentType(_ contentType: ContentType) -> Builder {
config.contentType = contentType
return self
}
public func withHeader(_ key: String, _ value: String) -> Builder {
config.headers[key] = value
return self
}
public func withHeaderDictionary(_ dictionary: [String: String]) -> Builder {
for (key, value) in dictionary {
config.headers[key] = value
}
return self
}
public func withPlugin(_ plugin: RagePlugin) -> Builder {
config.plugins.append(plugin)
return self
}
public func withAuthenticator(_ authenticator: Authenticator?) -> Builder {
config.authenticator = authenticator
return self
}
public func build() -> RageClient {
return RageClient(defaultConfiguration: config)
}
}
}
| 759f69db2f7b8f39f76d77c4cfe2d3ab | 25 | 88 | 0.576923 | false | true | false | false |
khalloufi/SMPageControl-Swift | refs/heads/master | SMPageControl-swift/SMPageControl.swift | mit | 1 | //
// SMPageControl.swift
// SMPageControl-swift
//
// Created by issam on 13/06/2016.
// Copyright © 2016 issam khalloufi. All rights reserved.
//
import UIKit
struct SMPageControlAlignment {
var value: UInt32
init(_ val: UInt32) { value = val }
}
let SMPageControlAlignmentLeft = SMPageControlAlignment(0)
let SMPageControlAlignmentCenter = SMPageControlAlignment(1)
let SMPageControlAlignmentRight = SMPageControlAlignment(2)
struct SMPageControlVerticalAlignment {
var value: UInt32
init(_ val: UInt32) { value = val }
}
let SMPageControlVerticalAlignmentTop = SMPageControlVerticalAlignment(0)
let SMPageControlVerticalAlignmentMiddle = SMPageControlVerticalAlignment(1)
let SMPageControlVerticalAlignmentBottom = SMPageControlVerticalAlignment(2)
struct SMPageControlTapBehavior {
var value: UInt32
init(_ val: UInt32) { value = val }
}
let SMPageControlTapBehaviorStep = SMPageControlTapBehavior(0)
let SMPageControlTapBehaviorJump = SMPageControlTapBehavior(1)
struct SMPageControlImageType {
var value: UInt32
init(_ val: UInt32) { value = val }
}
let SMPageControlImageTypeNormal = SMPageControlImageType(0)
let SMPageControlImageTypeCurrent = SMPageControlImageType(1)
let SMPageControlImageTypeMask = SMPageControlImageType(2)
let DEFAULT_INDICATOR_WIDTH:CGFloat = 6.0
let DEFAULT_INDICATOR_MARGIN:CGFloat = 10.0
let DEFAULT_INDICATOR_WIDTH_LARGE:CGFloat = 7.0
let DEFAULT_INDICATOR_MARGIN_LARGE:CGFloat = 9.0
let DEFAULT_MIN_HEIGHT_LARGE:CGFloat = 36.0
class SMPageControl: UIControl {
var numberOfPages:NSInteger = 0
var currentPage:NSInteger = 0
var indicatorMargin:CGFloat = 0
var indicatorDiameter:CGFloat = 0
var minHeight:CGFloat = 0
var alignment:SMPageControlAlignment = SMPageControlAlignmentCenter
var verticalAlignment:SMPageControlVerticalAlignment = SMPageControlVerticalAlignmentMiddle
var pageIndicatorImage:UIImage!
var pageIndicatorMaskImage:UIImage!
var pageIndicatorTintColor:UIColor!
var currentPageIndicatorImage:UIImage!
var currentPageIndicatorTintColor:UIColor!
var hidesForSinglePage:Bool = false
var defersCurrentPageDisplay:Bool = false
var tapBehavior:SMPageControlTapBehavior = SMPageControlTapBehaviorStep
var displayedPage:NSInteger = 0
var measuredIndicatorWidth:CGFloat = 0
var measuredIndicatorHeight:CGFloat = 0
var pageImageMask:CGImageRef!
var pageNames = [NSInteger: String]()
var pageImages = [NSInteger: UIImage]()
var currentPageImages = [NSInteger: UIImage]()
var pageImageMasks = [NSInteger: UIImage]()
var cgImageMasks = [NSInteger: CGImageRef]()
var pageRects = [CGRect]()
var accessibilityPageControl:UIPageControl = UIPageControl.init()
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
initialize()
}
override var frame: CGRect {
get {
return super.frame
}
set (frame) {
super.frame = frame
setNeedsDisplay()
}
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
if (numberOfPages < 2 && hidesForSinglePage) {
return;
}
let context = UIGraphicsGetCurrentContext()
var _pageRects = [CGRect]()
let left:CGFloat = leftOffset()
var xOffset:CGFloat = left
var yOffset:CGFloat = 0.0
var fillColor:UIColor
var image:UIImage?
var maskingImage:CGImageRef?
var maskSize:CGSize = CGSizeZero
for indexNumber in 0..<numberOfPages {
if (indexNumber == displayedPage) {
fillColor = (currentPageIndicatorTintColor != nil) ? currentPageIndicatorTintColor : UIColor.whiteColor()
image = currentPageImages[indexNumber]
if nil == image {
image = currentPageIndicatorImage
}
} else {
fillColor = (pageIndicatorTintColor != nil) ? pageIndicatorTintColor : UIColor.whiteColor().colorWithAlphaComponent(0.3)
image = pageImages[indexNumber]
if nil == image {
image = pageIndicatorImage
}
}
// If no finished images have been set, try a masking image
if nil == image {
if let originalImage:UIImage = pageImageMasks[indexNumber]{
maskSize = originalImage.size
}
maskingImage = cgImageMasks[indexNumber]
// If no per page mask is set, try for a global page mask!
if (nil == maskingImage) {
maskingImage = pageImageMask
if pageIndicatorMaskImage != nil{
maskSize = pageIndicatorMaskImage.size
}
}
}
fillColor.set()
var indicatorRect:CGRect;
if (image != nil) {
yOffset = topOffsetForHeight(image!.size.height,rect: rect)
let centeredXOffset:CGFloat = xOffset + floor((measuredIndicatorWidth - image!.size.width) / 2.0)
image!.drawAtPoint(CGPointMake(centeredXOffset, yOffset))
indicatorRect = CGRectMake(centeredXOffset, yOffset, image!.size.width, image!.size.height)
} else if (maskingImage != nil) {
yOffset = topOffsetForHeight(maskSize.height,rect: rect)
let centeredXOffset:CGFloat = xOffset + floor((measuredIndicatorWidth - maskSize.width) / 2.0)
indicatorRect = CGRectMake(centeredXOffset, yOffset, maskSize.width, maskSize.height)
CGContextDrawImage(context, indicatorRect, maskingImage)
} else {
yOffset = topOffsetForHeight(indicatorDiameter,rect: rect)
let centeredXOffset:CGFloat = xOffset + floor((measuredIndicatorWidth - indicatorDiameter) / 2.0);
indicatorRect = CGRectMake(centeredXOffset, yOffset, indicatorDiameter, indicatorDiameter);
CGContextFillEllipseInRect(context, indicatorRect)
}
_pageRects.append(indicatorRect)
maskingImage = nil
xOffset += measuredIndicatorWidth + indicatorMargin;
}
pageRects = _pageRects;
}
func initialize() {
self.backgroundColor = UIColor.clearColor()
setStyleWithDefaults()
self.isAccessibilityElement = true
self.accessibilityTraits = UIAccessibilityTraitUpdatesFrequently
self.contentMode = UIViewContentMode.Redraw
}
func updateCurrentPageDisplay(){
displayedPage = currentPage
self.setNeedsLayout()
}
func leftOffset() -> CGFloat {
let rect:CGRect = self.bounds;
let size:CGSize = sizeForNumberOfPages(numberOfPages)
if alignment.value == SMPageControlAlignmentCenter.value {
return ceil(CGRectGetMidX(rect) - CGFloat(size.width / 2.0))
}
if alignment.value == SMPageControlAlignmentRight.value {
return CGRectGetMaxX(rect) - size.width
}
return 0;
}
func topOffsetForHeight(height:CGFloat, rect:CGRect) -> CGFloat {
if verticalAlignment.value == SMPageControlVerticalAlignmentMiddle.value{
return CGRectGetMidY(rect) - (height / 2.0);
}
if verticalAlignment.value == SMPageControlVerticalAlignmentBottom.value{
return CGRectGetMaxY(rect) - height;
}
return 0;
}
func sizeForNumberOfPages(pageCount:NSInteger) -> CGSize {
let marginSpace = CGFloat(max(0,pageCount - 1)) * indicatorMargin
let indicatorSpace = CGFloat(pageCount) * measuredIndicatorWidth
return CGSizeMake(marginSpace + indicatorSpace, measuredIndicatorHeight)
}
func rectForPageIndicator(pageIndex : NSInteger) -> CGRect {
if (pageIndex < 0 || pageIndex >= numberOfPages) {
return CGRectZero;
}
let left:CGFloat = leftOffset()
let size:CGSize = sizeForNumberOfPages(pageIndex + 1)
return CGRectMake(left + size.width - measuredIndicatorWidth, 0, measuredIndicatorWidth, measuredIndicatorWidth)
}
func setImage(image:UIImage!,pageIndex:NSInteger,type:SMPageControlImageType){
if (pageIndex < 0 || pageIndex >= numberOfPages) {
return;
}
switch type.value {
case SMPageControlImageTypeCurrent.value:
if (image != nil){
currentPageImages[pageIndex] = image
}else{
currentPageImages.removeValueForKey(pageIndex)
}
break
case SMPageControlImageTypeNormal.value:
if (image != nil){
pageImages[pageIndex] = image
}else{
pageImages.removeValueForKey(pageIndex)
}
break
case SMPageControlImageTypeMask.value:
if (image != nil){
pageImageMasks[pageIndex] = image
}else{
pageImageMasks.removeValueForKey(pageIndex)
}
break
default:
break
}
}
func setImage(image:UIImage, pageIndex:NSInteger){
setImage(image, pageIndex: pageIndex, type: SMPageControlImageTypeNormal)
updateMeasuredIndicatorSizes()
}
func setCurrentImage(image:UIImage,pageIndex:NSInteger){
setImage(image, pageIndex: pageIndex, type: SMPageControlImageTypeCurrent)
updateMeasuredIndicatorSizes()
}
func setImageMask(image:UIImage?, pageIndex:NSInteger) {
setImage(image, pageIndex: pageIndex, type: SMPageControlImageTypeMask)
if nil == image{
cgImageMasks.removeValueForKey(pageIndex)
return
}
cgImageMasks[pageIndex] = createMaskForImage(image!)
updateMeasuredIndicatorSizeWithSize(image!.size)
setNeedsDisplay()
}
override func sizeThatFits(size:CGSize) -> CGSize {
var sizeThatFits:CGSize = sizeForNumberOfPages(numberOfPages)
sizeThatFits.height = max(sizeThatFits.height,minHeight)
return sizeThatFits
}
override func intrinsicContentSize() -> CGSize {
if (numberOfPages < 1 || (numberOfPages < 2 && hidesForSinglePage)) {
return CGSizeMake(UIViewNoIntrinsicMetric, 0.0)
}
return CGSizeMake(UIViewNoIntrinsicMetric, max(measuredIndicatorHeight, minHeight))
}
func updatePageNumberForScrollView(scrollView:UIScrollView) {
currentPage = NSInteger(floor(scrollView.contentOffset.x / scrollView.bounds.size.width));
}
func setScrollViewContentOffsetForCurrentPage(scrollView:UIScrollView,animated:Bool){
var offset:CGPoint = scrollView.contentOffset
offset.x = scrollView.bounds.size.width * CGFloat(currentPage)
scrollView.setContentOffset(offset, animated: animated)
}
func setStyleWithDefaults() {
setIndicatorDiameter(DEFAULT_INDICATOR_WIDTH_LARGE)
setIndicatorMargin(DEFAULT_INDICATOR_MARGIN_LARGE)
pageIndicatorTintColor = UIColor.whiteColor().colorWithAlphaComponent(0.2)
setMinHeight(DEFAULT_MIN_HEIGHT_LARGE)
}
//MARK :
func createMaskForImage(image:UIImage) -> CGImageRef {
let pixelsWide = image.size.width * image.scale
let pixelsHigh = image.size.height * image.scale
let context:CGContextRef = CGBitmapContextCreate(nil,
Int(pixelsWide),
Int(pixelsHigh),
CGImageGetBitsPerComponent(image.CGImage),
Int(pixelsWide),
nil,
CGImageAlphaInfo.Only.rawValue)!
CGContextTranslateCTM(context, 0.0, pixelsHigh)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, pixelsWide, pixelsHigh), image.CGImage)
let maskImage:CGImageRef = CGBitmapContextCreateImage(context)!
return maskImage
}
func updateMeasuredIndicatorSizeWithSize(size:CGSize){
measuredIndicatorWidth = max(measuredIndicatorWidth, size.width);
measuredIndicatorHeight = max(measuredIndicatorHeight, size.height);
}
func updateMeasuredIndicatorSizes(){
measuredIndicatorWidth = indicatorDiameter;
measuredIndicatorHeight = indicatorDiameter;
// If we're only using images, ignore the indicatorDiameter
if ((pageIndicatorImage != nil || pageIndicatorMaskImage != nil) && currentPageIndicatorImage != nil)
{
measuredIndicatorWidth = 0;
measuredIndicatorHeight = 0;
}
if (pageIndicatorImage != nil) {
updateMeasuredIndicatorSizeWithSize(pageIndicatorImage.size)
}
if (currentPageIndicatorImage != nil) {
updateMeasuredIndicatorSizeWithSize(currentPageIndicatorImage.size)
}
if (pageIndicatorMaskImage != nil) {
updateMeasuredIndicatorSizeWithSize(pageIndicatorMaskImage.size)
}
invalidateIntrinsicContentSize()
}
@nonobjc
func setIndicatorDiameter(_indicatorDiameter:CGFloat) {
if (_indicatorDiameter == indicatorDiameter) {
return
}
indicatorDiameter = _indicatorDiameter
// Absolute minimum height of the control is the indicator diameter
if (minHeight < indicatorDiameter) {
setMinHeight(indicatorDiameter)
}
updateMeasuredIndicatorSizes()
setNeedsDisplay()
}
@nonobjc
func setIndicatorMargin(_indicatorMargin:CGFloat) {
if (_indicatorMargin == indicatorMargin) {
return
}
indicatorMargin = _indicatorMargin;
setNeedsDisplay()
}
@nonobjc
func setMinHeight(_minHeight:CGFloat) {
if (_minHeight == minHeight) {
return
}
minHeight = _minHeight
if (minHeight < indicatorDiameter) {
minHeight = indicatorDiameter
}
invalidateIntrinsicContentSize()
setNeedsLayout()
}
@nonobjc
func setNumberOfPages(_numberOfPages:NSInteger) {
if _numberOfPages == numberOfPages {
return;
}
accessibilityPageControl.numberOfPages = _numberOfPages
numberOfPages = _numberOfPages
self.invalidateIntrinsicContentSize()
updateAccessibilityValue()
setNeedsDisplay()
}
@nonobjc
func setCurrentPage(_currentPage:NSInteger) {
setCurrentPage(_currentPage, sendEvent: false, canDefer: false)
}
func setCurrentPage(_currentPage:NSInteger,sendEvent:Bool,canDefer:Bool) {
currentPage = min(max(0,_currentPage),numberOfPages - 1)
accessibilityPageControl.currentPage = currentPage
updateAccessibilityValue()
if self.defersCurrentPageDisplay == false || canDefer == false{
displayedPage = currentPage
setNeedsDisplay()
}
if sendEvent{
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
}
}
@nonobjc
func setCurrentPageIndicatorImage(_currentPageIndicatorImage:UIImage) {
if _currentPageIndicatorImage.isEqual(currentPageIndicatorImage) {
return;
}
currentPageIndicatorImage = _currentPageIndicatorImage
updateMeasuredIndicatorSizes()
setNeedsDisplay()
}
@nonobjc
func setPageIndicatorImage(_pageIndicatorImage:UIImage) {
if _pageIndicatorImage.isEqual(pageIndicatorMaskImage){
return
}
pageIndicatorImage = _pageIndicatorImage
updateMeasuredIndicatorSizes()
setNeedsDisplay()
}
@nonobjc
func setPageIndicatorMaskImage(_pageIndicatorMaskImage:UIImage) {
if _pageIndicatorMaskImage.isEqual(pageIndicatorMaskImage){
return
}
pageIndicatorMaskImage = _pageIndicatorMaskImage
pageImageMask = createMaskForImage(pageIndicatorMaskImage)
updateMeasuredIndicatorSizes()
setNeedsDisplay()
}
// MARK : UIAccessibility
func setName(name:String,pageIndex:NSInteger) {
if (pageIndex < 0 || pageIndex >= numberOfPages) {
return;
}
pageNames[pageIndex] = name;
}
func nameForPage(pageIndex:NSInteger) -> String? {
if (pageIndex < 0 || pageIndex >= numberOfPages) {
return nil;
}
return pageNames[pageIndex];
}
func updateAccessibilityValue() {
let pageName = nameForPage(currentPage)
if pageName != nil{
self.accessibilityValue = "\(pageName) - \(accessibilityPageControl.accessibilityValue)"
}else{
self.accessibilityValue = accessibilityPageControl.accessibilityValue
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let point = touch!.locationInView(self)
if(SMPageControlTapBehaviorJump.value == tapBehavior.value){
var tappedIndicatorIndex:NSInteger = NSNotFound
for (index, value) in pageRects.enumerate() {
let indicatorRect:CGRect = value
if CGRectContainsPoint(indicatorRect, point){
tappedIndicatorIndex = index
break
}
}
if NSNotFound != tappedIndicatorIndex{
setCurrentPage(tappedIndicatorIndex, sendEvent: true, canDefer: true)
return
}
}
let size = sizeForNumberOfPages(numberOfPages)
let left = leftOffset()
let middle = left + (size.width / 2)
if point.x < middle{
setCurrentPage(currentPage - 1, sendEvent: true, canDefer: true)
}else{
setCurrentPage(currentPage + 1, sendEvent: true, canDefer: true)
}
}
}
| b81546aff67e1eabd70084664b544d5f | 37.590437 | 136 | 0.635115 | false | false | false | false |
Miguel-Herrero/Swift | refs/heads/master | Landmarks/Landmarks/Profile/ProfileHost.swift | gpl-3.0 | 1 | //
// ProfileHost.swift
// Landmarks
//
// Created by Miguel Herrero Baena on 20/06/2019.
// Copyright © 2019 Miguel Herrero Baena. All rights reserved.
//
import SwiftUI
struct ProfileHost : View {
@Environment(\.editMode) var mode
@State private var profile = Profile.default
@State private var draftProfile = Profile.default
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack {
if self.mode?.value == .active {
Button(action: {
self.profile = self.draftProfile
self.mode?.animation().value = .inactive
}) {
Text("Done")
}
}
Spacer()
EditButton()
}
if self.mode?.value == .inactive {
ProfileSummary(profile: profile)
} else {
ProfileEditor(profile: $draftProfile)
.onDisappear {
self.draftProfile = self.profile
}
}
}
.padding()
}
}
#if DEBUG
struct ProfileHost_Previews : PreviewProvider {
static var previews: some View {
ProfileHost()
}
}
#endif
| d0422866a90ece13f9675bd27d960967 | 23.903846 | 64 | 0.488803 | false | false | false | false |
IvanVorobei/RateApp | refs/heads/master | SPRateApp - project/SPRateApp/sparrow/ui/views/views/SPBlurView.swift | mit | 3 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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
@available(iOS 9, *)
public class SPBlurView: UIVisualEffectView {
private let blurEffect: UIBlurEffect
open var blurRadius: CGFloat {
return blurEffect.value(forKeyPath: "blurRadius") as! CGFloat
}
public convenience init() {
self.init(withRadius: 0)
}
public init(withRadius radius: CGFloat) {
let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")!
let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type
self.blurEffect = customBlurObject.init() as! UIBlurEffect
self.blurEffect.setValue(1.0, forKeyPath: "scale")
self.blurEffect.setValue(radius, forKeyPath: "blurRadius")
super.init(effect: radius == 0 ? nil : self.blurEffect)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func setBlurRadius(_ radius: CGFloat) {
guard radius != blurRadius else {
return
}
blurEffect.setValue(radius, forKeyPath: "blurRadius")
self.effect = blurEffect
}
}
| dd660d881684aec1efc569e277ba4e93 | 39.45614 | 87 | 0.708153 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | refs/heads/master | JKWayfairPriceGameTests/FinalScoreIndicatorViewModelSpec.swift | mit | 1 | //
// FinalScoreIndicatorViewModelSpec.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli on 10/11/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import JKWayfairPriceGame
class FinalScoreIndicatorViewModelSpec: QuickSpec {
override func spec() {
describe("Verifying the final score indicator view model") {
var finalScoreIndicatorViewModel: FinalScoreIndicatorViewModel? = nil
var gameViewModel: GameViewModel? = nil
beforeEach({
let product1 = try? Product(dictionary: ["availability": "Available", "imageURL": "", "listPrice": 100, "manufacturerIdentifier": 200, "manufacturerName": "Random Manufacturer", "name": "A very good product", "salePrice": 50, "sku": "SK243"])
let product2 = try? Product(dictionary: ["availability": "Unavailable", "imageURL": "", "listPrice": 200, "manufacturerIdentifier": 9393, "manufacturerName": "Random Manufacturer 1", "name": "A very great product", "salePrice": 100, "sku": "SK343"])
let product3 = try? Product(dictionary: ["availability": "Available", "imageURL": "", "listPrice": 10000, "manufacturerIdentifier": 200, "manufacturerName": "Random Manufacturer 2", "name": "A very amazing product", "salePrice": 5000, "sku": "SK24453"])
gameViewModel = GameViewModel(products: [product1!, product2!, product3!])
// Mocking these values since we are not really testing the GameViewModel.
gameViewModel?.totalScore = 20
gameViewModel?.questionIndex = 3
gameViewModel?.skipCount = 0
finalScoreIndicatorViewModel = FinalScoreIndicatorViewModel(gameViewModel: gameViewModel!)
})
describe("Verifying the initial parameter values for FinalScoreIndicatorViewModel", {
it("Initial values of model should match the expected value", closure: {
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.GoBack))
expect(finalScoreIndicatorViewModel?.gameViewModel).toNot(beNil())
expect(gameViewModel).to(beIdenticalTo(finalScoreIndicatorViewModel?.gameViewModel))
})
})
describe("Verifying the game statistics", {
it("Game statistics should match the expected string corresponding to the game parameters based on the user performance", closure: {
expect(finalScoreIndicatorViewModel?.totalStats).to(equal("Total Questions: 3 Skipped: 0\n\nCorrect: 2 / 66%\n\nTotal Score: 20"))
})
})
describe("Verifying the back button press action", {
it("Pressing back button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.goBackButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.GoBack))
})
})
describe("Verifying the new game button press action", {
it("Pressing new game button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.newGameButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.NewGame))
})
})
describe("Verifying the view statistics button press action", {
it("Pressing view statistics button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.viewStatisticsButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.ViewStatistics))
})
})
}
}
}
| 10672468ae2567b8d92155a79bca59c9 | 58.111111 | 269 | 0.642622 | false | false | false | false |
laszlokorte/reform-swift | refs/heads/master | ReformExpression/ReformExpression/ShuntingYardParser.swift | mit | 1 | //
// Parser.swift
// ExpressionEngine
//
// Created by Laszlo Korte on 07.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public enum ShuntingYardTokenType : TokenType {
case EOF
case literalValue
case argumentSeparator
case identifier
case parenthesisLeft
case parenthesisRight
case `operator`
case Ignore
case Unknown
public static let unknown = ShuntingYardTokenType.Unknown
public static let ignore = ShuntingYardTokenType.Ignore
public static let eof = ShuntingYardTokenType.EOF
}
public final class ShuntingYardParser<Delegate : ShuntingYardDelegate> : Parser {
public typealias NodeType = Delegate.NodeType
public typealias TokenType = Token<ShuntingYardTokenType>
let delegate : Delegate
public init(delegate: Delegate) {
self.delegate = delegate
}
public func parse<T : Sequence>(_ tokens: T) -> Result<NodeType, ShuntingYardError> where T.Iterator.Element==TokenType {
do {
let context = ShuntingYardContext<NodeType>()
var needOpen = false
outer:
for token in tokens
{
if (needOpen && token.type != .parenthesisLeft)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "Expected Opening Parenthesis.")
}
needOpen = false
switch (token.type)
{
case .EOF:
break outer
case .Unknown:
throw ShuntingYardError.unexpectedToken(token: token, message: "")
case .identifier:
if (context.lastTokenAtom)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
if (delegate.hasFunctionOfName(token))
{
context.stack.push(token)
context.argCount.push(0)
if let _ = context.wereValues.pop()
{
context.wereValues.push(true)
}
context.wereValues.push(false)
needOpen = true
}
else if(delegate.hasConstantOfName(token))
{
context.lastTokenAtom = true
context.output.push(try delegate.constantTokenToNode(token))
if let _ = context.wereValues.pop()
{
context.wereValues.push(true)
}
}
else
{
context.lastTokenAtom = true
context.output.push(try delegate.variableTokenToNode(token))
if let _ = context.wereValues.pop()
{
context.wereValues.push(true)
}
}
case .literalValue:
if (context.lastTokenAtom)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
context.lastTokenAtom = true
context.output.push(try delegate.literalTokenToNode(token))
if let _ = context.wereValues.pop()
{
context.wereValues.push(true)
}
case .argumentSeparator:
while let peek = context.stack.peek(), peek.type != .parenthesisLeft,
let _ = context.stack.pop()
{
context.output.push(try _pipe(peek, context: context))
}
if (context.stack.isEmpty || context.wereValues.isEmpty)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
if let wereValue = context.wereValues.pop(), wereValue,
let argCount = context.argCount.pop()
{
context.argCount.push(argCount + 1)
}
context.wereValues.push(true)
context.lastTokenAtom = false
case .operator:
if (isOperator(context.prevToken) && delegate.hasUnaryOperator(
token))
{
if (context.lastTokenAtom)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
context.unaries.insert(token)
context.stack.push(token)
}
else
{
if let peek = context.stack.peek(), peek.type ==
ShuntingYardTokenType.identifier,
let _ = context.stack.pop()
{
context.output.push(try _pipe(peek, context: context))
}
while let peek = context.stack.peek(), peek.type == ShuntingYardTokenType.operator,
let tokenPrec = delegate.precedenceOfOperator(token, unary: context.actsAsUnary(token)),
let peekPrec = delegate.precedenceOfOperator(peek, unary: context.actsAsUnary(peek)), (tokenPrec < peekPrec || (delegate.assocOfOperator(token) == Associativity.left && tokenPrec == peekPrec)),
let _ = context.stack.pop()
{
context.output.push(try _pipe(peek, context: context))
}
context.stack.push(token)
context.lastTokenAtom = false
}
case .parenthesisLeft:
if (context.lastTokenAtom)
{
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
context.stack.push(token)
case .parenthesisRight:
while let peek = context.stack.peek(), !delegate.isMatchingPair(
peek, right: token),
let _ = context.stack.pop()
{
context.output.push(try _pipe(peek, context: context))
}
guard let _ = context.stack.pop() else
{
throw ShuntingYardError.mismatchedToken(token: token, open: false)
}
if let peek = context.stack.peek(), peek.type ==
ShuntingYardTokenType.identifier,
let _ = context.stack.pop()
{
context.output.push(try _pipe(peek, context: context))
}
case .Ignore:
continue
}
context.prevToken = token
}
return .success(try finalize(context))
} catch let e as ShuntingYardError {
return Result.fail(e)
} catch {
return Result.fail(ShuntingYardError.invalidState)
}
}
func finalize(_ context : ShuntingYardContext<NodeType>) throws -> NodeType
{
while let peek = context.stack.peek()
{
if (peek.type == ShuntingYardTokenType.parenthesisLeft)
{
throw ShuntingYardError.mismatchedToken(token: peek, open: true)
}
if (peek.type == ShuntingYardTokenType.parenthesisRight)
{
throw ShuntingYardError.mismatchedToken(token: peek, open: false)
}
_ = context.stack.pop()
context.output.push(try _pipe(peek, context: context))
}
if let result = context.output.pop()
{
if (!context.output.isEmpty)
{
throw ShuntingYardError.invalidState
}
return result
}
else
{
return try delegate.emptyNode()
}
}
func _pipe(_ op : Token<ShuntingYardTokenType>, context : ShuntingYardContext<NodeType>) throws -> NodeType
{
switch (op.type)
{
case .identifier:
// @TODO: CLEAN UP
guard var argCount = context.argCount.pop() else {
throw ShuntingYardError.unexpectedToken(token: op, message: "")
}
var temp = [NodeType]()
while argCount > 0, let peek = context.output.pop()
{
argCount -= 1
temp.append(peek)
}
if let w = context.wereValues.pop(), w {
if let peek = context.output.pop()
{
temp.append(peek)
}
else
{
throw ShuntingYardError.unexpectedEndOfArgumentList(token: op)
}
}
return try delegate.functionTokenToNode(op, args: temp.reversed())
case .operator:
if (context.unaries.contains(op))
{
guard delegate.hasUnaryOperator(op) else
{
throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.unary)
}
guard let operand = context.output.pop()
else
{
throw ShuntingYardError.missingOperand(token: op, arity: OperatorArity.unary, missing: 1)
}
return try delegate.unaryOperatorToNode(op, operand: operand)
}
else
{
guard delegate.hasBinaryOperator(op) else
{
throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.binary)
}
guard let rightHand = context.output.pop()
else
{
throw ShuntingYardError.missingOperand(token: op, arity: OperatorArity.binary,missing: 2)
}
guard let leftHand = context.output.pop()
else
{
throw ShuntingYardError.missingOperand(token: op, arity: OperatorArity.binary,missing: 1)
}
return try delegate.binaryOperatorToNode(op, leftHand: leftHand, rightHand: rightHand)
}
default:
throw ShuntingYardError.unexpectedToken(token: op, message: "")
}
}
func isOperator(_ token : Token<ShuntingYardTokenType>?) -> Bool
{
if let t = token {
return t.type == ShuntingYardTokenType.operator || t.type == ShuntingYardTokenType
.argumentSeparator || t.type == ShuntingYardTokenType.parenthesisLeft } else {
return true
}
}
}
public enum ShuntingYardError : Error {
case invalidState
case unexpectedEndOfArgumentList(token: Token<ShuntingYardTokenType>)
case missingOperand(token: Token<ShuntingYardTokenType>, arity: OperatorArity, missing: Int)
case unknownOperator(token: Token<ShuntingYardTokenType>, arity: OperatorArity)
case unknownFunction(token: Token<ShuntingYardTokenType>, parameters: Int)
case unexpectedToken(token: Token<ShuntingYardTokenType>, message: String)
case mismatchedToken(token: Token<ShuntingYardTokenType>, open: Bool)
}
final class ShuntingYardContext<NodeType>
{
var stack : Stack<Token<ShuntingYardTokenType>> = Stack()
var output : Stack<NodeType> = Stack<NodeType>()
var wereValues : Stack<Bool> = Stack<Bool>()
var argCount : Stack<Int> = Stack<Int>()
var unaries: Set<Token<ShuntingYardTokenType>> = Set()
var prevToken : Token<ShuntingYardTokenType>? = nil
var lastTokenAtom : Bool = false
func actsAsUnary(_ token : Token<ShuntingYardTokenType>) -> Bool
{
return unaries.contains(token)
}
}
public protocol ShuntingYardDelegate {
associatedtype NodeType
func isMatchingPair(_ left : Token<ShuntingYardTokenType>, right : Token<ShuntingYardTokenType>) -> Bool
func hasFunctionOfName(_ name : Token<ShuntingYardTokenType>) -> Bool
func hasConstantOfName(_ name : Token<ShuntingYardTokenType>) -> Bool
func variableTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> NodeType
func constantTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> NodeType
func emptyNode() throws -> NodeType
func unaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, operand : NodeType) throws -> NodeType
func binaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, leftHand : NodeType, rightHand : NodeType) throws -> NodeType
func functionTokenToNode(_ function : Token<ShuntingYardTokenType>, args : [NodeType]) throws -> NodeType
func hasBinaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool
func hasUnaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool
func assocOfOperator(_ token : Token<ShuntingYardTokenType>) -> Associativity?
func precedenceOfOperator(_ token : Token<ShuntingYardTokenType>, unary : Bool) -> Precedence?
func literalTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> NodeType
}
| b1ecf0a7addf455b566cb00b47c8e07a | 35.989583 | 221 | 0.505703 | false | false | false | false |
SwiftBond/Bond | refs/heads/master | Sources/Bond/Bond.swift | mit | 2 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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 ReactiveKit
/// An abstraction of a binding target. Given a target object and a setter closure,
/// one can create a Bond instance onto which signals can be bound. When a next event
/// is sent on the bound signal, Bond will call the setter closure to update the target.
public struct Bond<Element>: BindableProtocol {
private weak var target: Deallocatable?
private let setter: (AnyObject, Element) -> Void
private let context: ExecutionContext
public init<Target: Deallocatable>(target: Target, context: ExecutionContext, setter: @escaping (Target, Element) -> Void) {
self.target = target
self.context = context
self.setter = { setter($0 as! Target, $1) }
}
public init<Target: Deallocatable>(target: Target, setter: @escaping (Target, Element) -> Void) where Target: BindingExecutionContextProvider {
self.target = target
self.context = target.bindingExecutionContext
self.setter = { setter($0 as! Target, $1) }
}
public func bind(signal: Signal<Element, NoError>) -> Disposable {
if let target = target {
return signal.take(until: target.deallocated).observeNext { element in
self.context.execute {
if let target = self.target {
self.setter(target, element)
}
}
}
} else {
return NonDisposable.instance
}
}
}
extension ReactiveExtensions where Base: Deallocatable {
/// Creates a bond on the receiver.
public func bond<Element>(context: ExecutionContext, setter: @escaping (Base, Element) -> Void) -> Bond<Element> {
return Bond(target: base, context: context, setter: setter)
}
}
extension ReactiveExtensions where Base: Deallocatable, Base: BindingExecutionContextProvider {
/// Creates a bond on the receiver.
public func bond<Element>(setter: @escaping (Base, Element) -> Void) -> Bond<Element> {
return Bond(target: base, setter: setter)
}
}
| a8e00a7befca8ff77bd91bb84b6649c2 | 40.883117 | 147 | 0.683721 | false | false | false | false |
byu-oit/ios-byuSuite | refs/heads/dev | byuSuite/Classes/Reusable/UI/ByuViewController2.swift | apache-2.0 | 1 | //
// ByuViewController2.swift
// byuSuite
//
// Created by Nathan Johnson on 4/10/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
class ByuViewController2: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.byuBackground
extendedLayoutIncludesOpaqueBars = true
}
//MARK: - Methods
func displayActionSheet(from item: Any, title: String? = nil, actions: [UIAlertAction], cancelActionHandler: ((UIAlertAction?) -> Void)? = nil) {
let actionSheet = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
for action in actions {
actionSheet.addAction(action)
}
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancelActionHandler))
if let barButton = item as? UIBarButtonItem {
actionSheet.popoverPresentationController?.barButtonItem = barButton
} else if let view = item as? UIView {
actionSheet.popoverPresentationController?.sourceView = view
actionSheet.popoverPresentationController?.sourceRect = view.bounds
}
present(actionSheet, animated: true, completion: nil)
}
func displayPhoneAction(from item: Any, title: String? = "Call", phoneNumber: String) {
displayActionSheet(from: item, title: nil, actions: [
UIAlertAction(title: title, style: .default, handler: { (_) in
if let phoneUrl = URL(string: "tel://\(phoneNumber)") {
UIApplication.shared.openURL(phoneUrl)
}
})
])
}
}
extension ByuViewController2: UITableViewDelegate {
//This method will not get called unless tableView(_:titleForHeaderInSection:) is implemented and does not return nil
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let dataSource = self as? UITableViewDataSource else { return nil }
if tableView.style == .plain {
let frame = CGRect(x: 8, y: 0, width: tableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section))
let headerView = UIView(frame: frame)
headerView.backgroundColor = UIColor.byuTableSectionHeaderBackground
let label = UILabel(frame: headerView.frame)
label.backgroundColor = UIColor.clear
label.textColor = UIColor.byuTableSectionHeader
label.text = dataSource.tableView!(tableView, titleForHeaderInSection: section)
label.font = UIFont.byuTableViewHeader
headerView.addSubview(label)
return headerView
}
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let dataSource = self as? UITableViewDataSource else { return UITableViewAutomaticDimension }
if dataSource.tableView?(tableView, titleForHeaderInSection: section) != nil && tableView.style == .plain { return 20 }
return UITableViewAutomaticDimension
}
}
| 5dfb8c43e7d72a2c1d6ee153f2a5a85d | 37.809524 | 149 | 0.665644 | false | false | false | false |
trifl/Chirp | refs/heads/master | Pod/Classes/Chirp.swift | mit | 1 | import AVFoundation
open class Chirp {
open class Sound {
open var id: SystemSoundID
open fileprivate(set) var count: Int = 1
init(id: SystemSoundID) {
self.id = id
}
}
// MARK: - Constants
fileprivate let kDefaultExtension = "wav"
// MARK: - Singleton
public static let sharedManager = Chirp()
// MARK: - Private Variables
open fileprivate(set) var sounds = [String:Sound]()
// MARK: - Public
@discardableResult
open func prepareSound(fileName: String) -> String? {
let fixedSoundFileName = self.fixedSoundFileName(fileName: fileName)
if let sound = soundForKey(fixedSoundFileName) {
sound.count += 1
return fixedSoundFileName
}
if let pathURL = pathURLForSound(fileName: fixedSoundFileName) {
var soundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(pathURL as CFURL, &soundID)
let sound = Sound(id: soundID)
sounds[fixedSoundFileName] = sound
return fixedSoundFileName
}
return nil
}
open func playSound(fileName: String) {
let fixedSoundFileName = self.fixedSoundFileName(fileName: fileName)
if let sound = soundForKey(fixedSoundFileName) {
AudioServicesPlaySystemSound(sound.id)
}
}
open func removeSound(fileName: String) {
let fixedSoundFileName = self.fixedSoundFileName(fileName: fileName)
if let sound = soundForKey(fixedSoundFileName) {
sound.count -= 1
if sound.count <= 0 {
AudioServicesDisposeSystemSoundID(sound.id)
sounds.removeValue(forKey: fixedSoundFileName)
}
}
}
// MARK: - Private
fileprivate func soundForKey(_ key: String) -> Sound? {
return sounds[key]
}
fileprivate func fixedSoundFileName(fileName: String) -> String {
var fixedSoundFileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
var soundFileComponents = fixedSoundFileName.components(separatedBy: ".")
if soundFileComponents.count == 1 {
fixedSoundFileName = "\(soundFileComponents[0]).\(kDefaultExtension)"
}
return fixedSoundFileName
}
fileprivate func pathForSound(fileName: String) -> String? {
let fixedSoundFileName = self.fixedSoundFileName(fileName: fileName)
let components = fixedSoundFileName.components(separatedBy: ".")
return Bundle.main.path(forResource: components[0], ofType: components[1])
}
fileprivate func pathURLForSound(fileName: String) -> URL? {
if let path = pathForSound(fileName: fileName) {
return URL(fileURLWithPath: path)
}
return nil
}
}
| 8370c8ff179d5896b2cee67a0cf10369 | 29.364706 | 85 | 0.691592 | false | false | false | false |
amujic5/AFEA | refs/heads/master | AFEA-StarterProject/AFEA-StarterProject/Extensions/CAShapeLayer+Circle.swift | mit | 1 | import UIKit
extension CAShapeLayer {
static func circle(frame: CGRect, strokeColor: UIColor, lineWidth: CGFloat, fillColor: UIColor = .clear) -> CAShapeLayer {
let path = UIBezierPath.circle(frame: frame)
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = fillColor.cgColor
layer.strokeColor = strokeColor.cgColor
layer.lineWidth = lineWidth
return layer
}
}
| cc96ce0f0f2da3799116c8edc14d9279 | 26.9375 | 126 | 0.666667 | false | false | false | false |
Lightstreamer/Lightstreamer-example-StockList-client-ios | refs/heads/master | Shared/StockListViewController.swift | apache-2.0 | 2 | // Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/
//
// StockListViewController.swift
// StockList Demo for iOS
//
// Copyright (c) Lightstreamer Srl
//
// 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 LightstreamerClient
class StockListViewController: UITableViewController, SubscriptionDelegate, UIPopoverControllerDelegate, UINavigationControllerDelegate {
let lockQueue = DispatchQueue(label: "lightstreamer.StockListViewController")
var stockListView: StockListView?
var subscribed = false
var subscription: Subscription?
var selectedRow: IndexPath?
// Multiple-item data structures: each item has a second-level dictionary.
// They store fields data and which fields have been updated
var itemUpdated = [UInt : [String: Bool]]()
var itemData = [UInt : [String : String?]]()
// List of rows marked to be reloaded by the table
var rowsToBeReloaded = Set<IndexPath>()
var infoButton: UIBarButtonItem?
var popoverInfoController: UIPopoverController?
var statusButton: UIBarButtonItem?
var popoverStatusController: UIPopoverController?
var detailController: DetailViewController?
// MARK: -
// MARK: User actions
// MARK: -
// MARK: Lightstreamer connection status management
// MARK: -
// MARK: Internals
// MARK: -
// MARK: Initialization
override init(style: UITableView.Style) {
super.init(style: style)
title = "Lightstreamer Stock List"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
title = "Lightstreamer Stock List"
}
required init?(coder: NSCoder) {
super.init(coder: coder)
title = "Lightstreamer Stock List"
}
// MARK: -
// MARK: User actions
@objc func infoTapped() {
if DEVICE_IPAD {
// If the Info popover is open close it
if popoverInfoController != nil {
popoverInfoController?.dismiss(animated: true)
popoverInfoController = nil
return
}
// If the Status popover is open close it
if popoverStatusController != nil {
popoverStatusController?.dismiss(animated: true)
popoverStatusController = nil
}
// Open the Info popover
let infoController = InfoViewController()
popoverInfoController = UIPopoverController(contentViewController: infoController)
popoverInfoController?.contentSize = CGSize(width: INFO_IPAD_WIDTH, height: INFO_IPAD_HEIGHT)
popoverInfoController?.delegate = self
if let rightBarButtonItem = navigationItem.rightBarButtonItem {
popoverInfoController?.present(from: rightBarButtonItem, permittedArrowDirections: .any, animated: true)
}
} else {
let infoController = InfoViewController()
navigationController?.pushViewController(infoController, animated: true)
}
}
@objc func statusTapped() {
if DEVICE_IPAD {
// If the Status popover is open close it
if popoverStatusController != nil {
popoverStatusController?.dismiss(animated: true)
popoverStatusController = nil
return
}
// If the Info popover is open close it
if popoverInfoController != nil {
popoverInfoController?.dismiss(animated: true)
popoverInfoController = nil
}
// Open the Status popover
let statusController = StatusViewController()
popoverStatusController = UIPopoverController(contentViewController: statusController)
popoverStatusController?.contentSize = CGSize(width: STATUS_IPAD_WIDTH, height: STATUS_IPAD_HEIGHT)
popoverStatusController?.delegate = self
if let leftBarButtonItem = navigationItem.leftBarButtonItem {
popoverStatusController?.present(from: leftBarButtonItem, permittedArrowDirections: .any, animated: true)
}
} else {
let statusController = StatusViewController()
navigationController?.pushViewController(statusController, animated: true)
}
}
// MARK: -
// MARK: Methods of UIViewController
override func loadView() {
let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListView"), owner: self, options: nil)
stockListView = niblets?.last as? StockListView
tableView = stockListView?.table
view = stockListView
infoButton = UIBarButtonItem(image: UIImage(named: "Info"), style: .plain, target: self, action: #selector(infoTapped))
infoButton?.tintColor = UIColor.white
navigationItem.rightBarButtonItem = infoButton
statusButton = UIBarButtonItem(image: UIImage(named: "Icon-disconnected"), style: .plain, target: self, action: #selector(statusTapped))
statusButton?.tintColor = UIColor.white
navigationItem.leftBarButtonItem = statusButton
navigationController?.delegate = self
if DEVICE_IPAD {
// On the iPad we preselect the first row,
// since the detail view is always visible
selectedRow = IndexPath(row: 0, section: 0)
detailController = (UIApplication.shared.delegate as? AppDelegate_iPad)?.detailController
}
// We use the notification center to know when the
// connection changes status
NotificationCenter.default.addObserver(self, selector: #selector(connectionStatusChanged), name: NOTIFICATION_CONN_STATUS, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(connectionEnded), name: NOTIFICATION_CONN_ENDED, object: nil)
// Start connection (executes in background)
Connector.shared().connect()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if DEVICE_IPAD {
return .landscape
} else {
return .portrait
}
}
// MARK: -
// MARK: Methods of UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NUMBER_OF_ITEMS
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Prepare the table cell
var cell = tableView.dequeueReusableCell(withIdentifier: "StockListCell") as? StockListCell
if cell == nil {
let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListCell"), owner: self, options: nil)
cell = niblets?.last as? StockListCell
}
// Retrieve the item's data structures
var item: [String : String?]! = nil
var updated: [String : Bool]! = nil
lockQueue.sync {
item = itemData[UInt(indexPath.row)]
updated = itemUpdated[UInt(indexPath.row)]
}
if let item = item {
// Update the cell appropriately
let colorName = item["color"] as? String
var color: UIColor? = nil
if colorName == "green" {
color = GREEN_COLOR
} else if colorName == "orange" {
color = ORANGE_COLOR
} else {
color = UIColor.white
}
cell?.nameLabel?.text = item["stock_name"] as? String
if updated?["stock_name"] ?? false {
if !stockListView!.table!.isDragging {
SpecialEffects.flash(cell?.nameLabel, with: color)
}
updated?["stock_name"] = false
}
cell?.lastLabel?.text = item["last_price"] as? String
if updated?["last_price"] ?? false {
if !stockListView!.table!.isDragging {
SpecialEffects.flash(cell?.lastLabel, with: color)
}
updated?["last_price"] = false
}
cell?.timeLabel?.text = item["time"] as? String
if updated?["time"] ?? false {
if !stockListView!.table!.isDragging {
SpecialEffects.flash(cell?.timeLabel, with: color)
}
updated?["time"] = false
}
let pctChange = Double((item["pct_change"] ?? "0") ?? "0") ?? 0.0
if pctChange > 0.0 {
cell?.dirImage?.image = UIImage(named: "Arrow-up")
} else if pctChange < 0.0 {
cell?.dirImage?.image = UIImage(named: "Arrow-down")
} else {
cell?.dirImage?.image = nil
}
if let object = item["pct_change"] {
cell?.changeLabel?.text = String(format: "%@%%", object!)
}
cell?.changeLabel?.textColor = (Double((item["pct_change"] ?? "0") ?? "0") ?? 0.0 >= 0.0) ? DARK_GREEN_COLOR : RED_COLOR
if updated?["pct_change"] ?? false {
if !stockListView!.table!.isDragging {
SpecialEffects.flashImage(cell?.dirImage, with: color)
SpecialEffects.flash(cell?.changeLabel, with: color)
}
updated?["pct_change"] = false
}
}
// Update the cell text colors appropriately
if indexPath == selectedRow {
cell?.nameLabel?.textColor = SELECTED_TEXT_COLOR
cell?.lastLabel?.textColor = SELECTED_TEXT_COLOR
cell?.timeLabel?.textColor = SELECTED_TEXT_COLOR
} else {
cell?.nameLabel?.textColor = DEFAULT_TEXT_COLOR
cell?.lastLabel?.textColor = DEFAULT_TEXT_COLOR
cell?.timeLabel?.textColor = DEFAULT_TEXT_COLOR
}
return cell!
}
// MARK: -
// MARK: Methods of UITableViewDelegate
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
// Mark the row to be reloaded
lockQueue.sync {
if selectedRow != nil {
rowsToBeReloaded.insert(selectedRow!)
}
rowsToBeReloaded.insert(indexPath)
}
selectedRow = indexPath
// Update the table view
reloadTableRows()
// On the iPhone the Detail View Controller is created on demand and pushed with
// the navigation controller
if detailController == nil {
detailController = DetailViewController()
// Ensure the view is loaded
detailController?.view
}
// Update the item on the detail controller
detailController?.changeItem(TABLE_ITEMS[indexPath.row])
if !DEVICE_IPAD {
// On the iPhone the detail view controller may be already visible,
// if it is not just push it
if (navigationController?.viewControllers.count ?? 0) == 1 {
if let detailController = detailController {
navigationController?.pushViewController(detailController, animated: true)
}
}
}
return nil
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListSection"), owner: self, options: nil)
return niblets?.last as? UIView
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath == selectedRow {
cell.backgroundColor = SELECTED_ROW_COLOR
} else if indexPath.row % 2 == 0 {
cell.backgroundColor = LIGHT_ROW_COLOR
} else {
cell.backgroundColor = DARK_ROW_COLOR
}
}
// MARK: -
// MARK: Methods of UIPopoverControllerDelegate
func popoverControllerDidDismissPopover(_ popoverController: UIPopoverController) {
if popoverController == popoverInfoController {
popoverInfoController = nil
} else if popoverController == popoverStatusController {
popoverStatusController = nil
}
}
// MARK: -
// MARK: Methods of UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if !DEVICE_IPAD {
// Remove selection when coming back from detail view
if viewController == self {
// Mark the row to be reloaded
lockQueue.sync {
if selectedRow != nil {
rowsToBeReloaded.insert(selectedRow!)
}
}
selectedRow = nil
// Update the table view
reloadTableRows()
}
}
}
// MARK: -
// MARK: Lighstreamer connection status management
@objc func connectionStatusChanged() {
// This method is always called from a background thread
// Check if we need to subscribe
let needsSubscription = !subscribed && Connector.shared().connected
DispatchQueue.main.async(execute: { [self] in
// Update connection status icon
if Connector.shared().connectionStatus.hasPrefix("DISCONNECTED") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-disconnected")
} else if Connector.shared().connectionStatus.hasPrefix("CONNECTING") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-connecting")
} else if Connector.shared().connectionStatus.hasPrefix("STALLED") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-stalled")
} else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("POLLING") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-polling")
} else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("WS-STREAMING") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-WS-streaming")
} else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("HTTP-STREAMING") {
navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-HTTP-streaming")
}
// If the detail controller is visible, set the item on the detail view controller,
// so that it can do its own subscription
if needsSubscription && (DEVICE_IPAD || ((navigationController?.viewControllers.count ?? 0) > 1)) {
detailController?.changeItem(TABLE_ITEMS[selectedRow?.row ?? 0])
}
})
// Check if we need to subscribe
if needsSubscription {
subscribed = true
print("StockListViewController: subscribing table...")
// The LSLightstreamerClient will reconnect and resubscribe automatically
subscription = Subscription(subscriptionMode: .MERGE, items: TABLE_ITEMS, fields: LIST_FIELDS)
subscription?.dataAdapter = DATA_ADAPTER
subscription?.requestedSnapshot = .yes
subscription?.addDelegate(self)
Connector.shared().subscribe(subscription!)
}
}
@objc func connectionEnded() {
// This method is always called from a background thread
// Connection was forcibly closed by the server,
// prepare for a new subscription
subscribed = false
subscription = nil
// Start a new connection (executes in background)
Connector.shared().connect()
}
// MARK: -
// MARK: Internals
func reloadTableRows() {
// This method is always called from the main thread
var rows: [IndexPath]? = nil
lockQueue.sync {
rows = [IndexPath]()
for indexPath in self.rowsToBeReloaded {
rows?.append(indexPath)
}
self.rowsToBeReloaded.removeAll()
}
// Ask the table to reload the marked rows
if let rows = rows {
stockListView?.table?.reloadRows(at: rows, with: .none)
}
}
// MARK: -
// MARK: Methods of SubscriptionDelegate
func subscription(_ subscription: Subscription, didClearSnapshotForItemName itemName: String?, itemPos: UInt) {}
func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forCommandSecondLevelItemWithKey key: String) {}
func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?, forCommandSecondLevelItemWithKey key: String) {}
func subscription(_ subscription: Subscription, didEndSnapshotForItemName itemName: String?, itemPos: UInt) {}
func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forItemName itemName: String?, itemPos: UInt) {}
func subscriptionDidRemoveDelegate(_ subscription: Subscription) {}
func subscriptionDidAddDelegate(_ subscription: Subscription) {}
func subscriptionDidSubscribe(_ subscription: Subscription) {}
func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?) {}
func subscriptionDidUnsubscribe(_ subscription: Subscription) {}
func subscription(_ subscription: Subscription, didReceiveRealFrequency frequency: RealMaxFrequency?) {}
func subscription(_ subscription: Subscription, didUpdateItem itemUpdate: ItemUpdate) {
// This method is always called from a background thread
let itemPosition = UInt(itemUpdate.itemPos)
// Check and prepare the item's data structures
var item: [String : String?]! = nil
var updated: [String : Bool]! = nil
lockQueue.sync {
item = itemData[itemPosition - 1]
if item == nil {
item = [String : String?](minimumCapacity: NUMBER_OF_LIST_FIELDS)
itemData[itemPosition - 1] = item
}
updated = self.itemUpdated[itemPosition - 1]
if updated == nil {
updated = [String : Bool](minimumCapacity: NUMBER_OF_LIST_FIELDS)
itemUpdated[itemPosition - 1] = updated
}
}
var previousLastPrice = 0.0
for fieldName in LIST_FIELDS {
// Save previous last price to choose blink color later
if fieldName == "last_price" {
previousLastPrice = Double((item[fieldName] ?? "0") ?? "0") ?? 0.0
}
// Store the updated field in the item's data structures
let value = itemUpdate.value(withFieldName: fieldName)
if value != "" {
item?[fieldName] = value
} else {
item?[fieldName] = nil
}
if itemUpdate.isValueChanged(withFieldName: fieldName) {
updated?[fieldName] = true
}
}
// Evaluate the update color and store it in the item's data structures
let currentLastPrice = Double(itemUpdate.value(withFieldName: "last_price") ?? "0") ?? 0
if currentLastPrice >= previousLastPrice {
item?["color"] = "green"
} else {
item?["color"] = "orange"
}
lockQueue.sync {
itemData[itemPosition - 1] = item
itemUpdated[itemPosition - 1] = updated
}
// Mark rows to be reload
lockQueue.sync {
rowsToBeReloaded.insert(IndexPath(row: Int(itemPosition) - 1, section: 0))
}
DispatchQueue.main.async(execute: { [self] in
// Update the table view
reloadTableRows()
})
}
}
// MARK: -
// MARK: StockListViewController extension
// MARK: -
// MARK: StockListViewController implementation
| 9073f0220d0d51fb7bdd1cc9a44c69c4 | 36.433929 | 150 | 0.613176 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainUI/SearchCryptoDomain/SearchCryptoDomainView.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainComponentLibrary
import ComposableArchitecture
import ComposableNavigation
import DIKit
import FeatureCryptoDomainDomain
import Localization
import SwiftUI
import ToolKit
struct SearchCryptoDomainView: View {
private typealias LocalizedString = LocalizationConstants.FeatureCryptoDomain.SearchDomain
private typealias Accessibility = AccessibilityIdentifiers.SearchDomain
private let store: Store<SearchCryptoDomainState, SearchCryptoDomainAction>
init(store: Store<SearchCryptoDomainState, SearchCryptoDomainAction>) {
self.store = store
}
var body: some View {
WithViewStore(store) { viewStore in
VStack(spacing: Spacing.padding2) {
searchBar
.padding([.top, .leading, .trailing], Spacing.padding3)
alertCardDescription
.padding([.leading, .trailing], Spacing.padding3)
domainList
}
.onAppear {
viewStore.send(.onAppear)
}
.primaryNavigation(title: LocalizedString.title)
.bottomSheet(isPresented: viewStore.binding(\.$isPremiumDomainBottomSheetShown)) {
createPremiumDomainBottomSheet()
}
.navigationRoute(in: store)
}
}
private var searchBar: some View {
WithViewStore(store) { viewStore in
SearchBar(
text: viewStore.binding(\.$searchText),
isFirstResponder: viewStore.binding(\.$isSearchFieldSelected),
cancelButtonText: LocalizationConstants.cancel,
subText: viewStore.isSearchTextValid ? nil : LocalizedString.SearchBar.error,
subTextStyle: viewStore.isSearchTextValid ? .default : .error,
placeholder: LocalizedString.title,
onReturnTapped: {
viewStore.send(.set(\.$isSearchFieldSelected, false))
}
)
.accessibilityIdentifier(Accessibility.searchBar)
}
}
private var alertCardDescription: some View {
WithViewStore(store) { viewStore in
if viewStore.isAlertCardShown {
AlertCard(
title: LocalizedString.Description.title,
message: LocalizedString.Description.body,
onCloseTapped: {
viewStore.send(.set(\.$isAlertCardShown, false), animation: .linear)
}
)
.accessibilityIdentifier(Accessibility.alertCard)
}
}
}
private var domainList: some View {
WithViewStore(store) { viewStore in
ScrollView {
if viewStore.isSearchResultsLoading {
ProgressView()
} else {
LazyVStack(spacing: 0) {
ForEach(viewStore.searchResults, id: \.domainName) { result in
PrimaryDivider()
createDomainRow(result: result)
}
PrimaryDivider()
}
}
}
.simultaneousGesture(
DragGesture().onChanged { _ in
viewStore.send(.set(\.$isSearchFieldSelected, false))
}
)
.accessibilityIdentifier(Accessibility.domainList)
}
}
private func createDomainRow(result: SearchDomainResult) -> some View {
WithViewStore(store) { viewStore in
PrimaryRow(
title: result.domainName,
subtitle: result.domainType.statusLabel,
trailing: {
TagView(
text: result.domainAvailability.availabilityLabel,
variant: result.domainAvailability == .availableForFree ?
.success : result.domainAvailability == .unavailable ? .default : .infoAlt
)
},
action: {
viewStore.send(.set(\.$isSearchFieldSelected, false))
switch result.domainType {
case .free:
viewStore.send(.selectFreeDomain(result))
case .premium:
viewStore.send(.selectPremiumDomain(result))
}
}
)
.disabled(result.domainAvailability == .unavailable)
.accessibilityIdentifier(Accessibility.domainListRow)
}
}
private func createPremiumDomainBottomSheet() -> some View {
WithViewStore(store) { viewStore in
BuyDomainActionView(
domainName: viewStore.selectedPremiumDomain?.domainName ?? "",
redirectUrl: viewStore.selectedPremiumDomainRedirectUrl ?? "",
isShown: viewStore.binding(\.$isPremiumDomainBottomSheetShown)
)
}
}
}
#if DEBUG
@testable import FeatureCryptoDomainData
@testable import FeatureCryptoDomainMock
struct SearchCryptoDomainView_Previews: PreviewProvider {
static var previews: some View {
SearchCryptoDomainView(
store: .init(
initialState: .init(),
reducer: searchCryptoDomainReducer,
environment: .init(
mainQueue: .main,
analyticsRecorder: NoOpAnalyticsRecorder(),
externalAppOpener: ToLogAppOpener(),
searchDomainRepository: SearchDomainRepository(
apiClient: SearchDomainClient.mock
),
orderDomainRepository: OrderDomainRepository(
apiClient: OrderDomainClient.mock
),
userInfoProvider: { .empty() }
)
)
)
}
}
#endif
| a47d9a7165a891a72035745a32cac8b2 | 35.914634 | 102 | 0.555005 | false | false | false | false |
luowei/PaintCodeSamples | refs/heads/master | GraphicDraw/GraphicDraw/ViewControllerAB.swift | apache-2.0 | 1 | //
// ViewControllerAB.swift
// GraphicDraw
//
// Created by Luo Wei on 2020/12/17.
// Copyright © 2020 wodedata. All rights reserved.
//
import UIKit
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("=====Controller A\n")
}
}
class ViewControllerB: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("=====Controller B\n")
}
}
| b87b6a954c9cd271cc9afe96f5029ada | 13.967742 | 51 | 0.625 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Mail/ComposeMail.swift | lgpl-2.1 | 2 | //
// ComposeMail.swift
// Neocom
//
// Created by Artem Shimanski on 2/17/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import CoreData
import Combine
import Alamofire
import Expressible
struct ComposeMail: View {
var draft: MailDraft? = nil
var onComplete: () -> Void
@EnvironmentObject private var sharedState: SharedState
@Environment(\.managedObjectContext) private var managedObjectContext
var body: some View {
NavigationView {
if sharedState.account != nil {
ComposeMailContent(esi: sharedState.esi, account: sharedState.account!, managedObjectContext: managedObjectContext, draft: draft, onComplete: onComplete)
}
}
}
}
fileprivate struct ContactsSearchAlignmentID: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.top]
}
}
fileprivate struct ComposeMailContent: View {
var onComplete: () -> Void
private var account: Account
private var managedObjectContext: NSManagedObjectContext
private var esi: ESI
@State private var text = NSAttributedString()
@State private var subject: String
@State private var firstResponder: UITextView?
@State private var recipientsFieldFrame: CGRect?
@State private var sendSubscription: AnyCancellable?
@State private var error: IdentifiableWrapper<Error>?
@State private var needsSaveDraft = true
@State private var isSaveDraftAlertPresented = false
@State private var isLoadoutPickerPresented = false
@State private var selectedRange: NSRange = NSRange(location: 0, length: 0)
private var draft: MailDraft?
@Environment(\.self) private var environment
@EnvironmentObject private var sharedState: SharedState
@ObservedObject var contactsSearchController: SearchResultsController<[Contact]?, NSAttributedString>
@State private var contactsInitialLoading: AnyPublisher<[Int64:Contact], Never>
init(esi: ESI, account: Account, managedObjectContext: NSManagedObjectContext, draft: MailDraft?, onComplete: @escaping () -> Void) {
self.esi = esi
self.account = account
self.managedObjectContext = managedObjectContext
self.onComplete = onComplete
self.draft = draft
func search(_ string: NSAttributedString) -> AnyPublisher<[Contact]?, Never> {
let s = string.string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(.symbols))
guard !s.isEmpty else {return Just(nil).eraseToAnyPublisher()}
return Contact.searchContacts(containing: s, esi: esi, options: [.universe], managedObjectContext: managedObjectContext)
.map{$0 as Optional}
.eraseToAnyPublisher()
}
_subject = State(initialValue: draft?.subject ?? "")
_text = State(initialValue: draft?.body ?? NSAttributedString())
contactsSearchController = SearchResultsController(initialValue: nil, predicate: NSAttributedString(), search)
let contactsInitialLoading: AnyPublisher<[Int64:Contact], Never>
if let ids = draft?.to, !ids.isEmpty {
contactsInitialLoading = Contact.contacts(with: Set(ids), esi: esi, characterID: account.characterID, options: [.all], managedObjectContext: managedObjectContext).receive(on: RunLoop.main).eraseToAnyPublisher()
}
else {
contactsInitialLoading = Empty().eraseToAnyPublisher()
}
_contactsInitialLoading = State(initialValue: contactsInitialLoading)
}
private func loadContacts(_ contacts: [Int64: Contact]) {
let s = contacts.values.filter{$0.name != nil}.sorted{$0.name! < $1.name!}.map {
TextAttachmentContact($0, esi: esi)
}.reduce(into: NSMutableAttributedString()) {s, contact in s.append(NSAttributedString(attachment: contact))}
self.contactsSearchController.predicate = s
self.contactsInitialLoading = Empty().eraseToAnyPublisher()
}
private var currentMail: ESI.Mail {
let recipients = contactsSearchController.predicate.attachments.values
.compactMap{$0 as? TextAttachmentContact}
.map{ESI.Recipient(recipientID: Int($0.contact.contactID), recipientType: $0.contact.recipientType ?? .character)}
let data = try? text.data(from: NSRange(location: 0, length: text.length),
documentAttributes: [.documentType : NSAttributedString.DocumentType.html])
let html = data.flatMap{String(data: $0, encoding: .utf8)} ?? text.string
return ESI.Mail(approvedCost: 0, body: html, recipients: recipients, subject: self.subject)
}
private func sendMail() {
let mail = currentMail
self.sendSubscription = esi.characters.characterID(Int(account.characterID)).mail().post(mail: mail).sink(receiveCompletion: { (result) in
self.sendSubscription = nil
switch result {
case .finished:
self.onComplete()
case let .failure(error):
self.error = IdentifiableWrapper(error)
}
}, receiveValue: {_ in})
}
private var sendButton: some View {
let recipients = contactsSearchController.predicate.attachments.values.compactMap{$0 as? TextAttachmentContact}
return Button(action: {
self.sendMail()
}) {
Image(systemName: "paperplane").frame(minWidth: 24).contentShape(Rectangle())
}.disabled(recipients.isEmpty || text.length == 0 || sendSubscription != nil)
}
private var cancelButton: some View {
BarButtonItems.close {
if self.draft?.managedObjectContext == nil && (self.text.length > 0 || !self.subject.isEmpty) {
self.isSaveDraftAlertPresented = true
}
else {
self.onComplete()
}
}
}
private var saveDraftAlert: Alert {
Alert(title: Text("Save Draft"), primaryButton: Alert.Button.default(Text("Save"), action: {
self.needsSaveDraft = true
self.onComplete()
}), secondaryButton: Alert.Button.destructive(Text("Discard Changes"), action: {
self.needsSaveDraft = false
self.onComplete()
}))
}
private func saveDraft() {
let recipients = contactsSearchController.predicate.attachments.values
.compactMap{$0 as? TextAttachmentContact}
.map{$0.contact.contactID}
let draft = self.draft ?? MailDraft(context: managedObjectContext)
if draft.managedObjectContext == nil {
managedObjectContext.insert(draft)
}
draft.body = text
draft.subject = subject
draft.to = recipients
draft.date = Date()
}
private func attach(_ loadout: Loadout) {
guard let ship = loadout.ship, let dna = try? DNALoadoutEncoder().encode(ship), let url = URL(dna: dna) else {return}
guard let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == loadout.typeID).first() else {return}
guard let mutableString = text.mutableCopy() as? NSMutableAttributedString else {return}
let name = ship.name?.isEmpty == false ? ship.name : type.typeName
let s = NSAttributedString(string: name ?? "", attributes: [.link: url, .font: UIFont.preferredFont(forTextStyle: .body)])
mutableString.replaceCharacters(in: selectedRange, with: s)
text = mutableString
}
private var attachmentButton: some View {
Button(action: {self.isLoadoutPickerPresented = true}) {
Image(systemName: "paperclip").frame(minWidth: 24).contentShape(Rectangle())
}
.sheet(isPresented: $isLoadoutPickerPresented) {
NavigationView {
ComposeMailLoadoutsPicker { loadout in
self.attach(loadout)
self.isLoadoutPickerPresented = false
}.navigationBarItems(leading: BarButtonItems.close {
self.isLoadoutPickerPresented = false
})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
private func recipients(_ rootGeometry: GeometryProxy) -> some View {
TextView(text: self.$contactsSearchController.predicate,
typingAttributes: [.font: UIFont.preferredFont(forTextStyle: .body)],
placeholder: NSAttributedString(string: NSLocalizedString("To:", comment: ""),
attributes: [.font: UIFont.preferredFont(forTextStyle: .headline),
.foregroundColor: UIColor.secondaryLabel]),
style: .fixedLayoutWidth(rootGeometry.size.width - 32),
onBeginEditing: { self.firstResponder = $0 },
onEndEditing: {
if self.firstResponder == $0 {
self.firstResponder = nil
}
}).alignmentGuide(VerticalAlignment(ContactsSearchAlignmentID.self)) {$0[.bottom]}
}
private var contactsSearchView: some View {
Group {
if firstResponder != nil && contactsSearchController.results != nil {
ZStack(alignment: Alignment(horizontal: .center, vertical: VerticalAlignment(ContactsSearchAlignmentID.self))) {
ContactsSearchResults(contacts: contactsSearchController.results ?? []) { contact in
var attachments = self.contactsSearchController.predicate.attachments.map{($0.key.location, $0.value)}.sorted{$0.0 < $1.0}.map{$0.1}
attachments.append(TextAttachmentContact(contact, esi: self.esi))
self.firstResponder?.resignFirstResponder()
self.contactsSearchController.predicate = attachments.reduce(into: NSMutableAttributedString()) { s, attachment in
s.append(NSAttributedString(attachment: attachment))
}
}
}
}
}
}
var body: some View {
GeometryReader { geometry in
VStack(alignment: .leading) {
VStack(alignment: .leading) {
HStack {
self.recipients(geometry)
}
HStack {
Text("From:").font(.headline).foregroundColor(.secondary)
ContactView(account: self.account, esi: self.esi)
}
HStack {
TextField("Subject", text: self.$subject)
}
}.padding(.horizontal, 16)
Divider()
TextView(text: self.$text, selectedRange: self.$selectedRange, typingAttributes: [.font: UIFont.preferredFont(forTextStyle: .body)]).padding(.horizontal, 16)
}.overlay(self.contactsSearchView, alignment: Alignment(horizontal: .center, vertical: VerticalAlignment(ContactsSearchAlignmentID.self)))
.overlay(self.sendSubscription != nil ? ActivityIndicator() : nil)
}
.onPreferenceChange(FramePreferenceKey.self) {
if self.recipientsFieldFrame?.size != $0.first?.integral.size {
self.recipientsFieldFrame = $0.first?.integral
}
}
.padding(.top)
.navigationBarTitle(Text("Compose Mail"))
.navigationBarItems(leading: cancelButton,
trailing: HStack{
attachmentButton
sendButton})
.alert(item: self.$error) { error in
Alert(title: Text("Error"), message: Text(error.wrappedValue.localizedDescription), dismissButton: .cancel(Text("Close")))
}
.alert(isPresented: $isSaveDraftAlertPresented) {
self.saveDraftAlert
}
.onDisappear {
if self.needsSaveDraft {
self.saveDraft()
}
}
.onReceive(contactsInitialLoading) { contacts in
self.loadContacts(contacts)
}
}
}
#if DEBUG
struct ComposeMail_Previews: PreviewProvider {
static var previews: some View {
ComposeMail {}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| e1b233218d85ec0d03039ee2d774bcf4 | 43.873239 | 222 | 0.615035 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | refs/heads/master | RedBus/RedBus/Common/Constants.swift | apache-2.0 | 1 | //
// Constants.swift
// RedBus
//
// Created by Anirudh Das on 8/22/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
//Success and Error Messages
public static let useDifferentFilter = "Use a different filter!"
public static let bookingSuccessful = "Bus booking successful."
public static let fetchBusesSuccess = "Showing all buses."
public static let cancelSuccessful = "Booking cancelled successfully."
public static let invalidRatingInput = "Please enter a valid rating between 0 to 5"
public static let ratingUpdateSuccess = "Rating updated successfully."
public static let filterSuccess = "Filter applied successfully."
//Images
public static let placeholderImage: UIImage = #imageLiteral(resourceName: "placeholder")
public static let filter: UIImage = #imageLiteral(resourceName: "filter")
public static let clearFilter: UIImage = #imageLiteral(resourceName: "clearFilter")
public static let ratingDeselected: UIImage = #imageLiteral(resourceName: "ratingDeselected")
public static let ratingSelected: UIImage = #imageLiteral(resourceName: "ratingSelected")
public static let depatureDeselected: UIImage = #imageLiteral(resourceName: "departureDeselected")
public static let depatureSelected: UIImage = #imageLiteral(resourceName: "departureSelected")
public static let fareDeselected: UIImage = #imageLiteral(resourceName: "fareDeselected")
public static let fareSelected: UIImage = #imageLiteral(resourceName: "fareSelected")
public static let arrowUp: UIImage = #imageLiteral(resourceName: "arrowUp")
public static let arrowDown: UIImage = #imageLiteral(resourceName: "arrowDown")
public static let acDeselected: UIImage = #imageLiteral(resourceName: "acDeselected")
public static let acSelected: UIImage = #imageLiteral(resourceName: "acSelected")
public static let nonACDeselected: UIImage = #imageLiteral(resourceName: "nonACDeselected")
public static let nonACSelected: UIImage = #imageLiteral(resourceName: "nonACSelected")
public static let seaterDeselected: UIImage = #imageLiteral(resourceName: "seaterDeselected")
public static let seaterSelected: UIImage = #imageLiteral(resourceName: "seaterSelected")
public static let sleeperDeselected: UIImage = #imageLiteral(resourceName: "sleeperDeselected")
public static let sleeperSelected: UIImage = #imageLiteral(resourceName: "sleeperSelected")
//Storyboard Identifiers
public static let filterVCStoryboardId = "filterVC"
public static let busCell = "busCell"
public static let bookingCell = "bookingCell"
public static let busesListVC = "busesListVC"
//Alerts
public static let bookingAlertTitle = "Confirm Booking"
public static let bookingAlertMessage = "Are you sure you want to book your bus"
public static let bookingAlertOK = "Book"
public static let bookingAlertCancel = "Dismiss"
public static let cancelAlertTitle = "Confirm Cancel"
public static let cancelAlertMessage = "Are you sure you want to cancel your booking?"
public static let cancelAlertOK = "Proceed"
public static let cancelAlertCancel = "Dismiss"
public static let updateAlertPlaceholder = "Enter rating"
public static let updateAlertTitle = "Confirm Update"
public static let updateAlertMessage = "Are you sure you want to update rating?"
public static let updateAlertOK = "Update"
public static let updateAlertCancel = "Dismiss"
}
| 590bb68e2c1ddec00fc9905eaee06574 | 47.689189 | 102 | 0.747433 | false | false | false | false |
mentalfaculty/impeller | refs/heads/master | Examples/Listless/Listless/TasksViewController.swift | mit | 1 | //
// TasksViewController.swift
// Listless
//
// Created by Drew McCormack on 07/01/2017.
// Copyright © 2017 The Mental Faculty B.V. All rights reserved.
//
import UIKit
class TasksViewController: UITableViewController {
var taskList: TaskList? {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 75
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navController = self.presentedViewController as? UINavigationController,
let taskController = navController.topViewController as? TaskViewController,
var task = taskController.task {
// Save and sync
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.localRepository.commit(&task)
appDelegate.sync()
// In case the edited task hss moved due to a sync, use the identifier to find the right index
let identifiers = taskList!.tasks.map({ $0.metadata.uniqueIdentifier })
if let editedRow = identifiers.index(of: task.metadata.uniqueIdentifier) {
taskList!.tasks[editedRow] = task
}
}
}
@IBAction func add(_ sender: Any?) {
guard taskList != nil else { return }
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let newTask = Task()
taskList!.tasks.insert(newTask, at: 0)
appDelegate.localRepository.commit(&taskList!)
let path = IndexPath(row: 0, section: 0)
tableView.selectRow(at: path, animated: true, scrollPosition: .none)
performSegue(withIdentifier: "toTask", sender: self)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return taskList?.tasks.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let task = taskList!.tasks[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath) as! TaskCell
cell.contentLabel.text = task.text
cell.tagsLabel.text = task.tagList.asString
cell.accessoryType = task.isComplete ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let task = taskList!.tasks[indexPath.row]
let title = task.isComplete ? "Mark Incomplete" : "Mark Complete"
let action = UITableViewRowAction(style: .normal, title: title) { action, indexPath in
var newTask = task
newTask.isComplete = !task.isComplete
self.taskList!.tasks[indexPath.row] = newTask
// Save and sync
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.localRepository.commit(&newTask)
appDelegate.sync()
}
return [action]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toTask" {
let navController = segue.destination as! UINavigationController
let c = navController.topViewController as! TaskViewController
c.task = taskList!.tasks[tableView.indexPathForSelectedRow!.row]
}
}
}
| 187e1cb4044a117c2ad588d92b9b9d87 | 37.37234 | 124 | 0.639867 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/QuickPickPhotos/QuickPickPhotosCell.swift | mit | 1 | //
// QuickPickPhotosCell.swift
// Yep
//
// Created by nixzhu on 15/10/16.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import Photos
import YepKit
import Proposer
final class QuickPickPhotosCell: UITableViewCell {
@IBOutlet weak var photosCollectionView: UICollectionView!
var alertCanNotAccessCameraRollAction: (() -> Void)?
var takePhotoAction: (() -> Void)?
var pickedPhotosAction: (Set<PHAsset> -> Void)?
var images: PHFetchResult?
lazy var imageManager = PHCachingImageManager()
var imageCacheController: ImageCacheController!
var pickedImageSet = Set<PHAsset>() {
didSet {
pickedPhotosAction?(pickedImageSet)
}
}
var completion: ((images: [UIImage], imageAssetSet: Set<PHAsset>) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .None
photosCollectionView.backgroundColor = UIColor.clearColor()
photosCollectionView.registerNibOf(CameraCell)
photosCollectionView.registerNibOf(PhotoCell)
photosCollectionView.showsHorizontalScrollIndicator = false
if let layout = photosCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = CGSize(width: 70, height: 70)
layout.minimumInteritemSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
photosCollectionView.contentInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
}
proposeToAccess(.Photos, agreed: {
SafeDispatch.async { [weak self] in
if let strongSelf = self {
let options = PHFetchOptions()
options.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: false)
]
let images = PHAsset.fetchAssetsWithMediaType(.Image, options: options)
strongSelf.images = images
strongSelf.imageCacheController = ImageCacheController(imageManager: strongSelf.imageManager, images: images, preheatSize: 1)
strongSelf.photosCollectionView.dataSource = self
strongSelf.photosCollectionView.delegate = self
strongSelf.photosCollectionView.reloadData()
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(strongSelf)
}
}
}, rejected: { [weak self] in
self?.alertCanNotAccessCameraRollAction?()
})
}
}
// MARK: - PHPhotoLibraryChangeObserver
extension QuickPickPhotosCell: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(changeInstance: PHChange) {
if let
_images = images,
changeDetails = changeInstance.changeDetailsForFetchResult(_images) {
SafeDispatch.async { [weak self] in
self?.images = changeDetails.fetchResultAfterChanges
self?.photosCollectionView.reloadData()
}
}
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension QuickPickPhotosCell: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return images?.count ?? 0
default:
return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
switch indexPath.section {
case 0:
let cell: CameraCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
return cell
case 1:
let cell: PhotoCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
return cell
default:
return UICollectionViewCell()
}
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? PhotoCell {
cell.imageManager = imageManager
if let imageAsset = images?[indexPath.item] as? PHAsset {
cell.imageAsset = imageAsset
cell.photoPickedImageView.hidden = !pickedImageSet.contains(imageAsset)
}
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 0:
takePhotoAction?()
case 1:
if let imageAsset = images?[indexPath.item] as? PHAsset {
if pickedImageSet.contains(imageAsset) {
pickedImageSet.remove(imageAsset)
} else {
pickedImageSet.insert(imageAsset)
}
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoCell
cell.photoPickedImageView.hidden = !pickedImageSet.contains(imageAsset)
}
default:
break
}
}
}
| 292fcbb618a207c71e1cfb6a70f8c55f | 30.497076 | 146 | 0.630709 | false | false | false | false |
laurentVeliscek/AudioKit | refs/heads/master | AudioKit/iOS/AudioKit/User Interface/AKPlaygroundLoop.swift | mit | 2 | //
// AKPlaygroundLoop.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import Foundation
import QuartzCore
public typealias Closure = () -> ()
/// Class to handle updating via CADisplayLink
public class AKPlaygroundLoop {
private var internalHandler: Closure = {}
private var trigger = 60
private var counter = 0
/// Repeat this loop at a given period with a code block
///
/// - parameter every: Period, or interval between block executions
/// - parameter handler: Code block to execute
///
public init(every duration: Double, handler: Closure) {
trigger = Int(60 * duration)
internalHandler = handler
let displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink.frameInterval = 1
displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
/// Repeat this loop at a given frequency with a code block
///
/// - parameter frequency: Frequency of block executions in Hz
/// - parameter handler: Code block to execute
///
public init(frequency: Double, handler: Closure) {
trigger = Int(60 / frequency)
internalHandler = handler
let displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink.frameInterval = 1
displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
/// Callback function for CADisplayLink
@objc func update() {
if counter < trigger {
counter += 1
return
}
counter = 0
self.internalHandler()
}
}
| b60d24041d4581ef873e698a37c35c21 | 31.314815 | 91 | 0.660172 | false | false | false | false |
MakeSchool/TripPlanner | refs/heads/master | TripPlanner/Networking/Synchronization/TripPlannerBackendSynchronizer.swift | mit | 1 | //
// TripPlannerBackendSynchronization.swift
// TripPlanner
//
// Created by Benjamin Encz on 9/9/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
import CoreData
// global synchronous queue for dispatching sync requests
// ensures that we don't send multiple updates to server at the same time
// server sync will be treated as atomic operation
let syncQueue = dispatch_queue_create("syncQueue", nil)
let syncGroup = dispatch_group_create()
struct TripPlannerBackendSynchronizer {
var tripPlannerClient: TripPlannerClient
var coreDataClient: CoreDataClient
init(tripPlannerClient: TripPlannerClient = defaultTripPlannerClient(), coreDataClient: CoreDataClient) {
self.tripPlannerClient = tripPlannerClient
self.coreDataClient = coreDataClient
}
func sync(completion: () -> Void) {
// ensure that only one sync can happen at a time by dispatching to a serial queue
dispatch_async(syncQueue) {
dispatch_group_enter(syncGroup)
self.uploadSync {
self.downloadSync {
self.coreDataClient.syncInformation().lastSyncTimestamp = NSDate.currentTimestamp()
self.coreDataClient.saveStack()
completion()
dispatch_group_leave(syncGroup)
}
}
// block syncQueue until latest sync request finished
dispatch_group_wait(syncGroup, DISPATCH_TIME_FOREVER)
}
}
func downloadSync(completionBlock: () -> Void) -> Void {
tripPlannerClient.fetchTrips {
if case .Success(let trips) = $0 {
let allLocalTripIds = self.coreDataClient.allTrips().filter { $0.serverID != nil }.map { $0.serverID }
// trips that exist locally, but not in the server set
let tripsToDelete = allLocalTripIds.filter { localTripId in !trips.contains{ $0.serverID == localTripId } }
tripsToDelete.forEach { tripServerID in
let tripToDelete = self.coreDataClient.tripWithServerID(tripServerID!)
self.coreDataClient.context.deleteObject(tripToDelete!)
}
trips.forEach { jsonTrip in
let existingTrip = self.coreDataClient.tripWithServerID(jsonTrip.serverID!)
if let existingTrip = existingTrip {
existingTrip.parsing = true
// check if server data is actually newer then local; if not return
if (existingTrip.lastUpdate!.doubleValue > jsonTrip.lastUpdate) {
existingTrip.parsing = false
return
}
// update existing trip
existingTrip.configureWithJSONTrip(jsonTrip)
// TODO: For now we're re-generating all waypoints from server locally
// could be more efficient in future by using a server identifier
// that maps local waypoints to ones from server
existingTrip.waypoints?.forEach { waypoint in
self.coreDataClient.context.deleteObject(waypoint as! NSManagedObject)
}
jsonTrip.waypoints.forEach {
let waypoint = Waypoint(context: existingTrip.managedObjectContext!)
try! waypoint.managedObjectContext!.save()
waypoint.parsing = false
waypoint.configureWithJSONWaypoint($0)
waypoint.trip = existingTrip
}
self.coreDataClient.saveStack()
existingTrip.parsing = false
self.coreDataClient.saveStack()
return
}
let (newTrip, temporaryContext) = self.coreDataClient.createObjectInTemporaryContext(Trip.self)
newTrip.configureWithJSONTrip(jsonTrip)
jsonTrip.waypoints.forEach {
let wayPoint = Waypoint(context: temporaryContext)
wayPoint.configureWithJSONWaypoint($0)
wayPoint.trip = newTrip
}
try! temporaryContext.save()
self.coreDataClient.saveStack()
}
}
completionBlock()
}
}
func uploadSync(completionBlock: () -> ()) {
let (createTripRequests, updateTripRequests, deleteTripRequests) = generateUploadRequests()
/* NOTE:
Instead of using a dispatch group most developers would use Promises or a framework like ReactiveCocoa that allows
to create a sequence of different asynchronous tasks. However, this example solution tries not to use too many outside frameworks.
Another possible solution would be using NSOperations and NSOperationQueue but that would require to restructure the TripPlannerClient significantly.
*/
let uploadGroup = dispatch_group_create()
for createTripRequest in createTripRequests {
dispatch_group_enter(uploadGroup)
createTripRequest.perform(tripPlannerClient.urlSession) {
if case .Success(let trip) = $0 {
// select uploaded trip
let createdTrip = self.coreDataClient.context.objectWithID(createTripRequest.trip.objectID) as? Trip
// assign server generated serverID
createdTrip?.serverID = trip.serverID
self.coreDataClient.saveStack()
}
dispatch_group_leave(uploadGroup)
}
}
for updateTripRequest in updateTripRequests {
dispatch_group_enter(uploadGroup)
updateTripRequest.perform(tripPlannerClient.urlSession) {
// in success case nothing needs to be done
if case .Failure = $0 {
// if failure ocurred we will need to try to sync this trip again
// set lastUpdate in near future so that trip will be selected as updated trip again
// TODO: use cleaner solution here
// select updated trip
let updatedTrip = self.coreDataClient.context.objectWithID(updateTripRequest.trip.objectID) as? Trip
// update lastUpdate
updatedTrip?.lastUpdate = NSDate.timeIntervalSinceReferenceDate() + 1000
self.coreDataClient.saveStack()
}
dispatch_group_leave(uploadGroup)
}
}
for deleteTripRequest in deleteTripRequests {
dispatch_group_enter(uploadGroup)
deleteTripRequest.perform(tripPlannerClient.urlSession) {
// in success case we can finally delete the trip
if case .Success(let deletionResponse) = $0 {
// remove trip from list of unsynced deletes
var deletedTripsArray = self.coreDataClient.syncInformation().unsyncedDeletedTripsArray
deletedTripsArray = deletedTripsArray.filter { $0 != deletionResponse.deletedTripIdentifier }
self.coreDataClient.syncInformation().unsyncedDeletedTripsArray = deletedTripsArray
self.coreDataClient.saveStack()
}
dispatch_group_leave(uploadGroup)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dispatch_group_wait(uploadGroup, DISPATCH_TIME_FOREVER)
dispatch_async(dispatch_get_main_queue()) {
completionBlock()
}
}
}
func generateUploadRequests() -> (createTripRequests: [TripPlannerClientCreateTripRequest], updateTripRequest: [TripPlannerClientUpdateTripRequest], deleteTripRequests: [TripPlannerClientDeleteTripRequest]) {
let tripsToDelete = coreDataClient.unsyncedTripDeletions()
let deleteRequests = tripsToDelete.map { tripPlannerClient.createDeleteTripRequest($0) }
let tripsToPost = coreDataClient.unsyncedTrips()
let postRequests = tripsToPost.map { tripPlannerClient.createCreateTripRequest($0) }
let lastSyncTimestamp = coreDataClient.syncInformation().lastSyncTimestamp?.doubleValue ?? 0
let tripsToUpdate = coreDataClient.syncedUpdateTripsChangedSince(lastSyncTimestamp)
let putRequests = tripsToUpdate.map { tripPlannerClient.createUpdateTripRequest($0) }
return (createTripRequests: postRequests, updateTripRequest: putRequests, deleteTripRequests: deleteRequests)
}
}
private func defaultTripPlannerClient() -> TripPlannerClient {
return TripPlannerClient(urlSession: NSURLSession.sharedSession())
} | 65c26fc8f87309ccb4231cb0b4e94794 | 40.60396 | 210 | 0.656432 | false | false | false | false |
Pyroh/Fluor | refs/heads/main | Fluor/Controllers/StatusMenuController.swift | mit | 1 | //
// StatusMenuController.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
import DefaultsWrapper
class StatusMenuController: NSObject, NSMenuDelegate, NSWindowDelegate, MenuControlObserver {
//MARK: - Menu Delegate
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet var menuItemsController: MenuItemsController!
@IBOutlet var behaviorController: BehaviorController!
private var rulesController: RulesEditorWindowController?
private var aboutController: AboutWindowController?
private var preferencesController: PreferencesWindowController?
private var runningAppsController: RunningAppWindowController?
var statusItem: NSStatusItem!
override func awakeFromNib() {
setupStatusMenu()
self.menuItemsController.setupController()
self.behaviorController.setupController()
startObservingUsesLightIcon()
startObservingMenuControlNotification()
}
deinit {
stopObservingUsesLightIcon()
stopObservingSwitchMenuControlNotification()
}
func windowWillClose(_ notification: Notification) {
guard let object = notification.object as? NSWindow else { return }
NotificationCenter.default.removeObserver(self, name: NSWindow.willCloseNotification, object: object)
if object.isEqual(rulesController?.window) {
rulesController = nil
} else if object.isEqual(aboutController?.window) {
aboutController = nil
} else if object.isEqual(preferencesController?.window) {
preferencesController = nil
} else if object.isEqual(runningAppsController?.window) {
runningAppsController = nil
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
switch keyPath {
case UserDefaultsKeyName.useLightIcon.rawValue?:
adaptStatusMenuIcon()
default:
return
}
}
// MARK: - Private functions
/// Setup the status bar's item
private func setupStatusMenu() {
self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
self.statusItem.menu = statusMenu
adaptStatusMenuIcon()
}
/// Adapt status bar icon from user's settings.
private func adaptStatusMenuIcon() {
let disabledApp = AppManager.default.isDisabled
let usesLightIcon = AppManager.default.useLightIcon
switch (disabledApp, usesLightIcon) {
case (false, false): statusItem.image = #imageLiteral(resourceName: "IconAppleMode")
case (false, true): statusItem.image = #imageLiteral(resourceName: "AppleMode")
case (true, false): statusItem.image = #imageLiteral(resourceName: "IconDisabled")
case (true, true): statusItem.image = #imageLiteral(resourceName: "LighIconDisabled")
}
}
/// Register self as an observer for some notifications.
private func startObservingUsesLightIcon() {
UserDefaults.standard.addObserver(self, forKeyPath: UserDefaultsKeyName.useLightIcon.rawValue, options: [], context: nil)
}
/// Unregister self as an observer for some notifications.
private func stopObservingUsesLightIcon() {
UserDefaults.standard.removeObserver(self, forKeyPath: UserDefaultsKeyName.useLightIcon.rawValue, context: nil)
}
// MARK: - NSWindowDelegate
func menuWillOpen(_ menu: NSMenu) {
self.behaviorController.adaptToAccessibilityTrust()
}
// MARK: - MenuControlObserver
func menuNeedsToOpen(notification: Notification) { }
func menuNeedsToClose(notification: Notification) {
if let userInfo = notification.userInfo, let animated = userInfo["animated"] as? Bool, !animated {
self.statusMenu.cancelTrackingWithoutAnimation()
} else {
self.statusMenu.cancelTracking()
}
}
// MARK: IBActions
/// Show the *Edit Rules* window.
///
/// - parameter sender: The object that sent the action.
@IBAction func editRules(_ sender: AnyObject) {
guard rulesController == nil else {
rulesController?.window?.orderFrontRegardless()
return
}
rulesController = RulesEditorWindowController.instantiate()
rulesController?.window?.delegate = self
rulesController?.window?.orderFrontRegardless()
}
/// Show the *About* window.
///
/// - parameter sender: The object that sent the action.
@IBAction func showAbout(_ sender: AnyObject) {
guard aboutController == nil else {
aboutController?.window?.makeKeyAndOrderFront(self)
aboutController?.window?.makeMain()
NSApp.activate(ignoringOtherApps: true)
return
}
aboutController = AboutWindowController.instantiate()
aboutController?.window?.delegate = self
aboutController?.window?.makeKeyAndOrderFront(self)
aboutController?.window?.makeMain()
NSApp.activate(ignoringOtherApps: true)
}
/// Show the *Preferences* window.
///
/// - parameter sender: The object that sent the action.
@IBAction func showPreferences(_ sender: AnyObject) {
guard preferencesController == nil else {
preferencesController?.window?.makeKeyAndOrderFront(self)
preferencesController?.window?.makeMain()
NSApp.activate(ignoringOtherApps: true)
return
}
self.preferencesController = PreferencesWindowController.instantiate()
preferencesController?.window?.delegate = self
preferencesController?.window?.makeKeyAndOrderFront(self)
preferencesController?.window?.makeMain()
NSApp.activate(ignoringOtherApps: true)
}
/// Show the *Running Applications* window.
///
/// - parameter sender: The object that sent the action.
@IBAction func showRunningApps(_ sender: AnyObject) {
guard runningAppsController == nil else {
runningAppsController?.window?.orderFrontRegardless()
return
}
runningAppsController = RunningAppWindowController.instantiate()
runningAppsController?.window?.delegate = self
runningAppsController?.window?.orderFrontRegardless()
}
/// Enable or disable Fluor fn keys management.
/// If disabled the keyboard behaviour is set as its behaviour before app launch.
///
/// - Parameter sender: The object that sent the action.
@IBAction func toggleApplicationState(_ sender: NSMenuItem) {
let disabled = sender.state == .off
if disabled {
self.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "LighIconDisabled") : #imageLiteral(resourceName: "IconDisabled")
} else {
self.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "AppleMode") : #imageLiteral(resourceName: "IconAppleMode")
}
self.behaviorController.setApplicationIsEnabled(disabled)
}
/// Terminate the application.
///
/// - parameter sender: The object that sent the action.
@IBAction func quitApplication(_ sender: AnyObject) {
self.stopObservingUsesLightIcon()
NSWorkspace.shared.notificationCenter.removeObserver(self)
self.behaviorController.performTerminationCleaning()
NSApp.terminate(self)
}
}
| 1568d5ff602a7f8226535ee44dc49b7a | 38.872146 | 163 | 0.684265 | false | false | false | false |
torub/SwiftLisp | refs/heads/master | SwiftLisp/types.swift | mit | 1 | //
// types.swift
// HelloSwift
//
// Created by toru on 8/10/14.
// Copyright (c) 2014 toru. All rights reserved.
//
import Foundation
protocol LispObj {
func toStr() -> String
// list ならば キャストして値を返す
func listp() -> ConsCell?
}
/*
Singleton の例
参考: http://qiita.com/1024jp/items/3a7bc437af3e79f74505
*/
class Nil: LispObj {
init() {
}
class var sharedInstance: Nil {
struct Singleton {
private static let instance = Nil()
}
return Singleton.instance
}
func toStr() -> String {
return "nil";
}
func listp() -> ConsCell? {
return nil;
}
}
/*
Stringクラスの拡張
str.substring(from, to) を str[from...to] で実現する
参考: http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift
*/
extension String {
subscript (r: Range<Int>) -> String {
get {
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(startIndex, r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
}
// instanceof -> is
// cast -> as or as? asは強制、as?は失敗するとnilが入る
// AnyObject という何でも表す型がある?
// Any という型もある
class ConsCell: LispObj {
var car: LispObj;
var cdr: LispObj;
init(car: LispObj, cdr: LispObj) {
self.car = car;
self.cdr = cdr;
}
func toStr() -> String {
var returnValue: String = "";
returnValue += "(";
var tmpcell = self;
while (true) {
returnValue += tmpcell.car.toStr();
if let cdrcell = tmpcell.cdr.listp() {
tmpcell = cdrcell;
} else if tmpcell.cdr is Nil {
break;
} else {
returnValue += ".";
returnValue += tmpcell.cdr.toStr();
break;
}
returnValue += " ";
}
returnValue += ")"
return returnValue;
}
func listp() -> ConsCell? {
return self;
}
}
class Symbol: LispObj {
var name: String;
init(name: String) {
self.name = name;
}
func toStr() -> String {
return name;
}
func listp() -> ConsCell? {
return nil;
}
}
class LispNum: LispObj {
var value: Int;
init(value: Int) {
self.value = value;
}
func toStr() -> String {
return String(value);
}
func listp() -> ConsCell? {
return nil;
}
}
class LispStr: LispObj {
var value: String;
init(value: String) {
self.value = value;
}
func toStr() -> String {
return "\"" + value + "\"";
}
func listp() -> ConsCell? {
return nil;
}
}
class Error: LispObj {
var message: String;
init(message: String) {
self.message = message;
}
func toStr() -> String {
return "Error: " + message;
}
func listp() -> ConsCell? {
return nil;
}
}
class Environment: LispObj {
var env: [Dictionary<String, LispObj>] = [];
init() {
env.insert(Dictionary<String, LispObj>(), atIndex: 0);
}
func toStr() -> String {
return "[env]";
}
func add(variable: String, val: LispObj) {
env[0].updateValue(val, forKey: variable)
}
func addPrimitive(name: String) {
self.add(name, val: ConsCell(car: LispStr(value: PRIMITIVE), cdr: Symbol(name: name)));
}
func get(name: String) -> LispObj {
for dic in env {
if let value = dic[name] {
return value;
}
}
return NIL;
}
func copy() -> Environment {
// Swiftは値渡しのようなので、以下でコピーになる
var newenv = Environment()
newenv.env = self.env;
return newenv;
}
func extend(lambda_params: LispObj, operand: LispObj) -> Environment? {
env.insert(Dictionary<String, LispObj>(), atIndex: 0)
if (addlist(lambda_params, operand: operand)) {
return self;
} else {
return nil;
}
}
func addlist(params: LispObj, operand: LispObj) -> Bool {
if let params_cell = params.listp() { // && で繋げて書くと上手くいかない(なぜ??)
if let operand_cell = operand.listp() {
// これだと param_cell.car がLispStrのとき不具合になりそう
self.add(params_cell.car.toStr(), val: operand_cell.car);
return addlist(params_cell.cdr, operand: operand_cell.cdr);
} else {
// TODO: サイズが合わない場合のエラー処理
return false;
}
} else {
if let operand_cell = operand.listp() {
// TODO: サイズが合わない場合のエラー処理
return false;
} else {
return true;
}
}
}
func listp() -> ConsCell? {
return nil
}
} | 72ee9d0337e010607104e91f4e338ec2 | 20.779221 | 119 | 0.506759 | false | false | false | false |
LuckyResistor/FontToBytes | refs/heads/master | FontToBytes/ModeItem.swift | gpl-2.0 | 1 | //
// Lucky Resistor's Font to Byte
// ---------------------------------------------------------------------------
// (c)2015 by Lucky Resistor. See LICENSE for details.
//
// 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 2 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
import Cocoa
/// A single mode item in the navigation list.
///
class ModeItem {
let title: String
let isSection: Bool
let converter: ModeConverter?
/// Creates a new section item.
///
init(title: String) {
self.title = title
self.converter = nil
self.isSection = true
}
/// Creates a new mode item.
///
init(title: String, converter: ModeConverter) {
self.title = title
self.converter = converter
self.isSection = false
}
}
| 862ec3aeee62187cdcd6545410d3ba54 | 27.54 | 78 | 0.640505 | false | false | false | false |
ymkil/LKImagePicker | refs/heads/master | LKImagePickerExample/LKImagePickerExample/LKTestCell.swift | mit | 1 | //
// LKTestCell.swift
// LKImagePicker
//
// Created by Mkil on 11/01/2017.
// Copyright © 2017 黎宁康. All rights reserved.
//
import UIKit
class LKTestCell: UICollectionViewCell {
lazy var imageView: UIImageView = { [unowned self] in
let imageView = UIImageView()
imageView.frame = self.bounds
imageView.backgroundColor = UIColor.init(white: 1.000, alpha: 0.500)
imageView.contentMode = .scaleAspectFit
return imageView
}()
lazy var deleteBtn: UIButton = { [unowned self] in
let deleteBtn = UIButton(type: .custom)
deleteBtn.frame = CGRect(x: self.frame.size.width - 36, y: 0, width: 36, height: 36)
deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, -10)
deleteBtn.setImage(UIImage(named: "photo_delete"), for: .normal)
deleteBtn.alpha = 0.6
return deleteBtn
}()
override init(frame: CGRect) {
super.init(frame: frame)
[imageView,deleteBtn].forEach {
addSubview($0)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 0cf7ffeb59353b33e4f4fa4cca888390 | 26 | 92 | 0.606061 | false | false | false | false |
VladiMihaylenko/omim | refs/heads/master | iphone/Maps/Classes/CustomAlert/Toast/Toast.swift | apache-2.0 | 5 | @objc(MWMToast)
@objcMembers
final class Toast: NSObject {
private var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
static func toast(withText text: String) -> Toast {
return Toast(text)
}
private init(_ text: String) {
blurView.layer.cornerRadius = 8
blurView.clipsToBounds = true
blurView.alpha = 0
let label = UILabel()
label.text = text
label.textAlignment = .center
label.numberOfLines = 0
label.font = .regular14()
label.textColor = .white
label.frame = blurView.contentView.bounds
label.translatesAutoresizingMaskIntoConstraints = false
blurView.contentView.addSubview(label)
blurView.isUserInteractionEnabled = false
let views = ["label" : label]
blurView.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[label]-8-|",
options: [],
metrics: [:],
views: views))
blurView.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[label]-8-|",
options: [],
metrics: [:],
views: views))
}
func show() {
show(in: UIApplication.shared.keyWindow)
}
func show(in view: UIView?) {
guard let v = view else { return }
blurView.translatesAutoresizingMaskIntoConstraints = false
v.addSubview(blurView)
let views = ["bv" : blurView]
v.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|->=16-[bv]->=16-|",
options: [],
metrics: [:],
views: views))
v.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[bv]-50-|",
options: [],
metrics: [:],
views: views))
v.addConstraint(NSLayoutConstraint(item: blurView,
attribute: .centerX,
relatedBy: .equal,
toItem: v,
attribute: .centerX,
multiplier: 1,
constant: 0))
UIView.animate(withDuration: kDefaultAnimationDuration) {
self.blurView.alpha = 1
}
Timer.scheduledTimer(timeInterval: 3,
target: self,
selector: #selector(onTimer),
userInfo: nil,
repeats: false)
}
@objc private func onTimer() {
UIView.animate(withDuration: kDefaultAnimationDuration,
animations: { self.blurView.alpha = 0 }) { [self] _ in self.blurView.removeFromSuperview() }
}
}
| 9021e6d9fc24331f2073bea96d3da7b5 | 41.103896 | 111 | 0.467921 | false | false | false | false |
JoeLago/MHGDB-iOS | refs/heads/master | Pods/GRDB.swift/GRDB/Core/DatabaseError.swift | mit | 1 | import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// A result code limited to the least significant 8 bits of the receiver.
/// See https://www.sqlite.org/rescode.html for more information.
///
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
public var primaryResultCode: ResultCode {
return ResultCode(rawValue: rawValue & 0xFF)
}
var isPrimary: Bool {
return self == primaryResultCode
}
/// Returns true if the code on the left matches the code on the right.
///
/// Primary result codes match themselves and their extended result codes,
/// while extended result codes match only themselves:
///
/// switch error.extendedResultCode {
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
/// case .SQLITE_CONSTRAINT: // any other constraint error
/// default: // any other database error
/// }
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
if pattern.isPrimary {
return pattern == code.primaryResultCode
} else {
return pattern == code
}
}
// Primary Result codes
// https://www.sqlite.org/rescode.html#primary_result_code_list
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
public static let SQLITE_PERM = ResultCode(rawValue: 3) // Access permission denied
public static let SQLITE_ABORT = ResultCode(rawValue: 4) // Callback routine requested an abort
public static let SQLITE_BUSY = ResultCode(rawValue: 5) // The database file is locked
public static let SQLITE_LOCKED = ResultCode(rawValue: 6) // A table in the database is locked
public static let SQLITE_NOMEM = ResultCode(rawValue: 7) // A malloc() failed
public static let SQLITE_READONLY = ResultCode(rawValue: 8) // Attempt to write a readonly database
public static let SQLITE_INTERRUPT = ResultCode(rawValue: 9) // Operation terminated by sqlite3_interrupt()
public static let SQLITE_IOERR = ResultCode(rawValue: 10) // Some kind of disk I/O error occurred
public static let SQLITE_CORRUPT = ResultCode(rawValue: 11) // The database disk image is malformed
public static let SQLITE_NOTFOUND = ResultCode(rawValue: 12) // Unknown opcode in sqlite3_file_control()
public static let SQLITE_FULL = ResultCode(rawValue: 13) // Insertion failed because database is full
public static let SQLITE_CANTOPEN = ResultCode(rawValue: 14) // Unable to open the database file
public static let SQLITE_PROTOCOL = ResultCode(rawValue: 15) // Database lock protocol error
public static let SQLITE_EMPTY = ResultCode(rawValue: 16) // Database is empty
public static let SQLITE_SCHEMA = ResultCode(rawValue: 17) // The database schema changed
public static let SQLITE_TOOBIG = ResultCode(rawValue: 18) // String or BLOB exceeds size limit
public static let SQLITE_CONSTRAINT = ResultCode(rawValue: 19) // Abort due to constraint violation
public static let SQLITE_MISMATCH = ResultCode(rawValue: 20) // Data type mismatch
public static let SQLITE_MISUSE = ResultCode(rawValue: 21) // Library used incorrectly
public static let SQLITE_NOLFS = ResultCode(rawValue: 22) // Uses OS features not supported on host
public static let SQLITE_AUTH = ResultCode(rawValue: 23) // Authorization denied
public static let SQLITE_FORMAT = ResultCode(rawValue: 24) // Auxiliary database format error
public static let SQLITE_RANGE = ResultCode(rawValue: 25) // 2nd parameter to sqlite3_bind out of range
public static let SQLITE_NOTADB = ResultCode(rawValue: 26) // File opened that is not a database file
public static let SQLITE_NOTICE = ResultCode(rawValue: 27) // Notifications from sqlite3_log()
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
// Extended Result Code
// https://www.sqlite.org/rescode.html#extended_result_code_list
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
public static let SQLITE_IOERR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (4<<8)))
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (5<<8)))
public static let SQLITE_IOERR_TRUNCATE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (6<<8)))
public static let SQLITE_IOERR_FSTAT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (7<<8)))
public static let SQLITE_IOERR_UNLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (8<<8)))
public static let SQLITE_IOERR_RDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (9<<8)))
public static let SQLITE_IOERR_DELETE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (10<<8)))
public static let SQLITE_IOERR_BLOCKED = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (11<<8)))
public static let SQLITE_IOERR_NOMEM = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (12<<8)))
public static let SQLITE_IOERR_ACCESS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (13<<8)))
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (14<<8)))
public static let SQLITE_IOERR_LOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (15<<8)))
public static let SQLITE_IOERR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (16<<8)))
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (17<<8)))
public static let SQLITE_IOERR_SHMOPEN = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (18<<8)))
public static let SQLITE_IOERR_SHMSIZE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (19<<8)))
public static let SQLITE_IOERR_SHMLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (20<<8)))
public static let SQLITE_IOERR_SHMMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (21<<8)))
public static let SQLITE_IOERR_SEEK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (22<<8)))
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (23<<8)))
public static let SQLITE_IOERR_MMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (24<<8)))
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (25<<8)))
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (3<<8)))
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (4<<8)))
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (5<<8)))
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (6<<8)))
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (7<<8)))
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8)))
public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8)))
public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8)))
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8)))
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8)))
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
#if !swift(>=4.1)
// Equatable
extension ResultCode {
/// :nodoc:
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
#endif
// CustomStringConvertible
extension ResultCode {
/// :nodoc:
public var description: String {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
} else {
return "\(rawValue)"
}
#endif
}
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
/// // A constraint error
/// }
///
/// This property returns a "primary result code", that is to say the least
/// significant 8 bits of any SQLite result code. See
/// https://www.sqlite.org/rescode.html for more information.
///
/// See also `extendedResultCode`.
public var resultCode: ResultCode {
return extendedResultCode.primaryResultCode
}
/// The SQLite extended error code (see
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
/// // A foreign key constraint error
/// }
///
/// See also `resultCode`.
public let extendedResultCode: ResultCode
/// The SQLite error message.
public let message: String?
/// The SQL query that yielded the error (if relevant).
public let sql: String?
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.extendedResultCode = resultCode
self.message = message
self.sql = sql
self.arguments = arguments
}
/// Creates a Database Error with a raw Int32 result code.
///
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
// MARK: Not public
/// The query arguments that yielded the error (if relevant).
/// Not public because the StatementArguments class has no public method.
let arguments: StatementArguments?
}
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
description += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
description += " arguments \(arguments)"
}
if let message = message {
description += ": \(message)"
}
return description
}
}
// CustomNSError
extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
}
| 448807f99c065d3d9fed2b4c402cee1c | 56.940741 | 139 | 0.657057 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Extensions/UIKit/UIViewController.swift | apache-2.0 | 1 | // Copyright 2018 Esri.
//
// 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
extension UIViewController {
/// Shows an alert with the given title, message, and an OK button.
func presentAlert(title: String? = nil, message: String? = nil) {
let okAction = UIAlertAction(title: "OK", style: .default)
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert, actions: [okAction])
present(alertController, animated: true)
}
/// Show an alert with the title "Error", the error's `localizedDescription`
/// as the message, and an OK button.
func presentAlert(error: Error) {
presentAlert(title: "Error", message: error.localizedDescription)
}
}
private extension UIAlertController {
/// Initializes the alert controller with the given parameters, adding the
/// actions successively and setting the first action as preferred.
convenience init(title: String? = nil, message: String? = nil, preferredStyle: UIAlertController.Style = .alert, actions: [UIAlertAction] = []) {
self.init(title: title, message: message, preferredStyle: preferredStyle)
for action in actions {
addAction(action)
}
preferredAction = actions.first
}
}
| 7dd5a5410916f9973eeaae6f80f70f32 | 41.928571 | 149 | 0.703827 | false | false | false | false |
lemonkey/iOS | refs/heads/master | ListerforAppleWatchiOSandOSX/Swift/ListerKit Tests/ListPresenterTestHelper.swift | mit | 2 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A class that makes it easier to test `ListPresenterType` implementations.
*/
import ListerKit
import XCTest
class ListPresenterTestHelper: ListPresenterDelegate {
// MARK: Properties
var remainingExpectedWillChanges: Int? = nil
var willChangeCallbackCount = 0
/// An array of tuples representing the inserted list items.
var didInsertListItemCallbacks: [(listItem: ListItem, index: Int)] = []
/// An array of tuples representing the removed list items.
var didRemoveListItemCallbacks: [(listItem: ListItem, index: Int)] = []
/// An array of tuples representing the updated list items.
var didUpdateListItemCallbacks: [(listItem: ListItem, index: Int)] = []
/// An array of tuples representing the moved list items.
var didMoveListItemCallbacks: [(listItem: ListItem, fromIndex: Int, toIndex: Int)] = []
/// An array of tuples representing the updates to the list presenter's color.
var didUpdateListColorCallbacks: [List.Color] = []
var remainingExpectedDidChanges: Int? = nil
var didChangeCallbackCount = 0
// Expectation specific variables.
var assertions: (Void -> Void)! = nil
var isTesting = false
// MARK: ListPresenterDelegate
func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) {
/*
Lister's tests currently do not support testing and `listPresenterDidRefreshCompleteLayout(_:)`
calls.
*/
}
func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
if !isTesting { return }
remainingExpectedWillChanges?--
willChangeCallbackCount++
}
func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) {
if !isTesting { return }
didInsertListItemCallbacks += [(listItem: listItem, index: index)]
}
func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) {
if !isTesting { return }
didRemoveListItemCallbacks += [(listItem: listItem, index: index)]
}
func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) {
if !isTesting { return }
didUpdateListItemCallbacks += [(listItem: listItem, index: index)]
}
func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) {
if !isTesting { return }
didMoveListItemCallbacks += [(listItem: listItem, fromIndex: fromIndex, toIndex: toIndex)]
}
func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) {
if !isTesting { return }
didUpdateListColorCallbacks += [color]
}
func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
if !isTesting { return }
remainingExpectedDidChanges?--
didChangeCallbackCount++
if remainingExpectedDidChanges == 0 {
assertions()
isTesting = false
}
}
/// A helper method run `assertions` once a batch of changes has occured to the list presenter.
func whenNextChangesOccur(assert assertions: Void -> Void) {
isTesting = true
self.assertions = assertions
willChangeCallbackCount = 0
remainingExpectedWillChanges = nil
didInsertListItemCallbacks = []
didRemoveListItemCallbacks = []
didUpdateListItemCallbacks = []
didMoveListItemCallbacks = []
didUpdateListColorCallbacks = []
didChangeCallbackCount = 0
remainingExpectedDidChanges = nil
remainingExpectedWillChanges = 1
remainingExpectedDidChanges = 1
}
}
| 9e23b1f0b867c0475dcd4ea6146ba111 | 31.612903 | 112 | 0.656034 | false | true | false | false |
CesarValiente/CursoSwiftUniMonterrey | refs/heads/master | week5/hamburguesas/hamburguesas/Datos.swift | mit | 1 | //
// DatosSwift.swift
// hamburguesas
//
// Created by Cesar Valiente on 28/12/15.
// Copyright © 2015 Cesar Valiente. All rights reserved.
//
// Is required to be in Spanish for evaluation, so yeah.. coding in Spanish :-(
import Foundation
import UIKit
class ColeccionDePaises {
let paises = ["España", "Francia", "Portugal", "Alemania", "Italia", "Inglaterra", "Escocia", "Irlanda", "Gales", "Irlanda del Norte", "Suecia", "Noruega", "Finlandia", "Dinamarca", "Republica Checa", "Eslovaquia", "Belgica", "Holanda", "Hungria", "Ucrania", "Rusia"]
func obtenPais () -> String {
let posicion = Int (arc4random()) % paises.count
return paises[posicion]
}
}
class ColeccionDeHamburguesas {
let hamburguesas : [String] = ["pollo", "ternera", "cerdo", "mexicana", "tropical", "wopper", "big king", "queso", "picante", "dulce", "china", "iberica", "chorizo", "extra de queso", "doble", "salmon", "trucha", ]
func obtenHamburguesa () -> String {
let posicion = Int (arc4random()) % hamburguesas.count
return hamburguesas[posicion]
}
}
class ColeccionDeColores {
let colores = [
UIColor(red: 30/255, green: 180/255, blue: 20/255, alpha: 1),
UIColor(red: 50/255, green: 100/255, blue: 50/255, alpha: 1),
UIColor(red: 70/255, green: 120/255, blue: 70/255, alpha: 1),
UIColor(red: 80/255, green: 140/255, blue: 90/255, alpha: 1),
UIColor(red: 90/255, green: 160/255, blue: 100/255, alpha: 1),
UIColor(red: 100/255, green: 180/255, blue: 120/255, alpha: 1),
UIColor(red: 120/255, green: 200/255, blue: 130/255, alpha: 1),
UIColor(red: 150/255, green: 230/255, blue: 150/255, alpha: 1),
UIColor(red: 170/255, green: 50/255, blue: 200/255, alpha: 1)]
func cambiarColor () -> UIColor {
let posicion = Int (arc4random()) % colores.count
return colores[posicion]
}
} | a64755fd299b3fba4e9cfeb052b0c5d7 | 40.170213 | 272 | 0.619959 | false | false | false | false |
appintheair/WatchAnimationHelper | refs/heads/master | Example/LayerAnimations/Views.swift | mit | 1 | //
// Views.swift
// LayerAnimations
//
// Created by Sergey Pronin on 1/21/15.
// Copyright (c) 2015 AITA LTD. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
class RoundLayer: CALayer {
dynamic var radius: CGFloat = 0
override init(layer: AnyObject) {
super.init(layer: layer)
if layer is RoundLayer {
self.radius = (layer as RoundLayer).radius
}
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
override init() {
super.init()
}
override class func needsDisplayForKey(key: String) -> Bool {
if key == "radius" {
return true
}
return super.needsDisplayForKey(key)
}
}
let kRoundMaxRadius: CGFloat = 100
class RoundView: UIView {
var pointColor: UIColor = UIColor.redColor()
convenience init(location: CGPoint) {
self.init(frame: CGRectMake(location.x, location.y, kRoundMaxRadius, kRoundMaxRadius))
}
override init(var frame: CGRect) {
super.init(frame: frame)
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
override class func layerClass() -> AnyClass {
return RoundLayer.self
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
override func drawLayer(layer: CALayer, inContext context: CGContextRef) {
var radius = (layer as RoundLayer).radius
// println(radius)
var circleRect = CGContextGetClipBoundingBox(context)
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
CGContextFillEllipseInRect(context, CGRectMake((circleRect.size.width-radius)/2, (circleRect.size.height-radius)/2, radius, radius))
}
func animate() -> UIImage {
var animation = CABasicAnimation(keyPath: "radius")
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fromValue = 0
animation.toValue = kRoundMaxRadius
(self.layer as RoundLayer).radius = kRoundMaxRadius
// self.layer.addAnimation(animation, forKey:"radius")
return self.watch_resolveAnimation(animation)
}
}
class PlaneView: UIView {
required init(coder: NSCoder) {
super.init(coder: coder)
}
override init(var frame: CGRect) {
super.init(frame: frame)
}
convenience override init() {
var img = UIImage(named: "hud_plane")!
var imageView = UIImageView(image: img)
self.init(frame: CGRectMake(0, 0, img.size.width, img.size.height))
self.addSubview(imageView)
self.backgroundColor = UIColor.blackColor()
}
func animate() -> UIImage {
var rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = M_PI * 2.0
rotation.duration = 2
self.layer.addAnimation(rotation, forKey: "rotationAnimation")
return self.watch_resolveAnimation(rotation)
}
} | 4fc6ab5b1a894588e93f933d520e90d5 | 27.285714 | 140 | 0.624566 | false | false | false | false |
Subsets and Splits