repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Shivam0911/IOS-Training-Projects
|
HitList/HitList/AppDelegate.swift
|
1
|
2650
|
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
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: "HitList")
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)")
}
}
}
}
|
mit
|
8d536175b1742e6d6860d7d6a19ced04
| 40.40625 | 191 | 0.710943 | 5.532359 | false | false | false | false |
maazsq/Algorithms_Example
|
InsertionSort/Swift/insertionSort.swift
|
3
|
591
|
func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
guard array.count > 1 else { return array }
var sampleArray = array
for index in 1..<sampleArray.count {
var y = index
let temp = sampleArray[y]
while y > 0 && isOrderedBefore(temp, sampleArray[y - 1]) {
sampleArray[y] = sampleArray[y - 1]
y -= 1
}
sampleArray[y] = temp
}
return sampleArray
}
//Usage:
let array = insertionSort([5,4,6,3,7]) { (firstItem, secondItem) -> Bool in
// Sort items of an arrayin ascending order.
return firstItem < secondItem
}
|
apache-2.0
|
bc56ecc4f8d535723a54e6cbc059df3b
| 25.863636 | 79 | 0.617597 | 3.436047 | false | false | false | false |
ZamzamInc/SwiftyLocations
|
SwiftyLocations/LocationManager.swift
|
1
|
8772
|
//
// LocationManager.swift
// DelegateClosureConversion
//
// Created by Basem Emara on 3/2/17.
// Copyright © 2017 Basem Emara. All rights reserved.
//
import CoreLocation
public class LocationManager: NSObject, CLLocationManagerDelegate {
/// Internal Core Location manager
fileprivate lazy var manager: CLLocationManager = {
$0.delegate = self
if let value = self.desiredAccuracy { $0.desiredAccuracy = value }
if let value = self.distanceFilter { $0.distanceFilter = value }
if let value = self.activityType { $0.activityType = value }
return $0
}(CLLocationManager())
/// Default location manager options
fileprivate let desiredAccuracy: CLLocationAccuracy?
fileprivate let distanceFilter: Double?
fileprivate let activityType: CLActivityType?
public init(
desiredAccuracy: CLLocationAccuracy? = nil,
distanceFilter: Double? = nil,
activityType: CLActivityType? = nil) {
// Assign values to location manager options
self.desiredAccuracy = desiredAccuracy
self.distanceFilter = distanceFilter
self.activityType = activityType
super.init()
}
/// Subscribes to receive new location data when available.
public var didUpdateLocations = SynchronizedArray<LocationObserver>()
fileprivate var didUpdateLocationsSingle = SynchronizedArray<LocationHandler>()
/// Subscribes to receive new authorization data when available.
public var didChangeAuthorization = SynchronizedArray<AuthorizationObserver>()
fileprivate var didChangeAuthorizationSingle = SynchronizedArray<AuthorizationHandler>()
deinit {
// Empty task queues of references
didUpdateLocations.removeAll()
didUpdateLocationsSingle.removeAll()
didChangeAuthorization.removeAll()
didChangeAuthorizationSingle.removeAll()
}
}
// MARK: - Nested types
public extension LocationManager {
/// Location handler queue type.
typealias LocationObserver = Observer<LocationHandler>
typealias LocationHandler = (CLLocation) -> Void
// Authorization handler queue type.
typealias AuthorizationObserver = Observer<AuthorizationHandler>
typealias AuthorizationHandler = (Bool) -> Void
/// Permission types to use location services.
///
/// - whenInUse: While the app is in the foreground.
/// - always: Whenever the app is running.
enum AuthorizationType {
case whenInUse, always
}
}
// CLLocationManagerDelegate functions
public extension LocationManager {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
// Trigger and empty queues
didUpdateLocations.forEach { $0.handler(location) }
didUpdateLocationsSingle.removeAll { $0.forEach { $0(location) } }
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status != .notDetermined else { return }
// Trigger and empty queues
didChangeAuthorization.forEach { $0.handler(isAuthorized) }
didChangeAuthorizationSingle.removeAll { $0.forEach { $0(self.isAuthorized) } }
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// TODO: Injectable logger
debugPrint(error)
}
}
// MARK: - CLLocationManager wrappers
public extension LocationManager {
/// A Boolean value indicating whether the app wants to receive location updates when suspended.
var allowsBackgroundLocationUpdates: Bool {
get { return manager.allowsBackgroundLocationUpdates }
set { manager.allowsBackgroundLocationUpdates = newValue }
}
/// Determines if location services is enabled and authorized for always or when in use.
var isAuthorized: Bool {
return CLLocationManager.locationServicesEnabled()
&& [.authorizedAlways, .authorizedWhenInUse].contains(
CLLocationManager.authorizationStatus())
}
/// Determines if location services is enabled and authorized for the specified authorization type.
func isAuthorized(for type: AuthorizationType) -> Bool {
guard CLLocationManager.locationServicesEnabled() else { return false }
return (type == .whenInUse && CLLocationManager.authorizationStatus() == .authorizedWhenInUse)
|| (type == .always && CLLocationManager.authorizationStatus() == .authorizedAlways)
}
/// Starts the generation of updates that report the user’s current location.
func startUpdating(enableBackground: Bool = false) {
manager.allowsBackgroundLocationUpdates = enableBackground
manager.startUpdatingLocation()
}
/// Stops the generation of location updates.
func stopUpdating() {
manager.allowsBackgroundLocationUpdates = false
manager.stopUpdatingLocation()
}
}
// MARK: - Single requests
public extension LocationManager {
/// Requests permission to use location services.
///
/// - Parameters:
/// - type: Type of permission required, whether in the foreground (.whenInUse) or while running (.always).
/// - startUpdating: Starts the generation of updates that report the user’s current location.
/// - completion: True if the authorization succeeded for the authorization type, false otherwise.
func requestAuthorization(for type: AuthorizationType = .whenInUse, startUpdating: Bool = false, completion: AuthorizationHandler? = nil) {
// Handle authorized and exit
guard !isAuthorized(for: type) else {
if startUpdating { self.startUpdating() }
completion?(true)
return
}
// Request appropiate authorization before exit
defer {
switch type {
case .whenInUse: manager.requestWhenInUseAuthorization()
case .always: manager.requestAlwaysAuthorization()
}
}
// Handle mismatched allowed and exit
guard !isAuthorized else {
if startUpdating { self.startUpdating() }
// Process callback in case authorization dialog not launched by OS
// since user will be notified first time only and inored subsequently
completion?(false)
return
}
if startUpdating {
didChangeAuthorizationSingle += { _ in self.startUpdating() }
}
// Handle denied and exit
guard CLLocationManager.authorizationStatus() == .notDetermined
else { completion?(false); return }
if let completion = completion {
didChangeAuthorizationSingle += completion
}
}
/// Request the one-time delivery of the user’s current location.
///
/// - Parameter completion: The completion with the location object.
func requestLocation(completion: @escaping LocationHandler) {
didUpdateLocationsSingle += completion
manager.requestLocation()
}
}
#if os(iOS)
import UIKit
public extension LocationManager {
/// Presents alert for notifying use to update location settings.
///
/// - Parameters:
/// - controller: Controller to present from.
/// - title: Title of the alert.
/// - message: Message of the alert.
/// - buttonText: Settings button label text.
/// - cancelText: Cancel button label text.
static func authorizationAlert(for controller: UIViewController?,
title: String = "Allow access to your location while you use the app?",
message: String = "Enable authorization from settings.",
buttonText: String = "Settings",
cancelText: String = "Cancel") {
guard let controller = controller else { return }
// Contruct alert and associated actions
let alertController: UIAlertController = {
$0.addAction(UIAlertAction(title: cancelText, style: .cancel, handler: nil))
$0.addAction(UIAlertAction(title: buttonText, style: .default) { _ in
guard let settings = URL(string: UIApplicationOpenSettingsURLString) else { return }
UIApplication.shared.open(settings)
})
return $0
}(UIAlertController(title: title, message: message, preferredStyle: .alert))
// Display alert to user
controller.present(alertController, animated: true, completion: nil)
}
}
#endif
|
mit
|
667880f34f2b1390a51dfc51c7be33c1
| 37.442982 | 143 | 0.662407 | 5.71382 | false | false | false | false |
ioscodigo/ICTabFragment
|
Example/ICTagFragmentExample/Pods/ICTabFragment/ICTabFragment/ICTabPageViewController.swift
|
1
|
3117
|
//
// ICTabPageViewController.swift
// ICTabFragment
//
// Created by Digital Khrisna on 6/1/17.
// Copyright © 2017 codigo. All rights reserved.
//
import UIKit
class ICTabPageViewController: UIPageViewController {
lazy var listViewController = [UIViewController]()
internal var context: ICTabFragmentViewController?
var childDelegate: ICTabChildProtocol?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.dataSource = self
if let first = listViewController.first {
setViewControllers([first], direction: .forward, animated: false, completion: nil)
}
guard let parent = context else { return }
parent.parentDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//Mark: Extension class
extension ICTabPageViewController: UIPageViewControllerDataSource{
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = listViewController.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
return listViewController[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = listViewController.index(of: viewController) else{
return nil
}
let nextIndex = viewControllerIndex + 1
guard listViewController.count > nextIndex else {
return nil
}
return listViewController[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if !completed {
return
}
let currentIndex = listViewController.index(where: {$0 == pageViewController.viewControllers?.first})
childDelegate?.didChildChangeFrame(currentIndex!)
}
}
extension ICTabPageViewController: UIPageViewControllerDelegate{
}
extension ICTabPageViewController: ICTabParentProtocol {
func didParentButtonTapped(_ row: Int, row previous: Int, parent view: UICollectionView) {
if row > previous {
setViewControllers([listViewController[row]], direction: .forward, animated: true, completion: nil)
} else {
setViewControllers([listViewController[row]], direction: .reverse, animated: true, completion: nil)
}
let indexPath = IndexPath(row: row, section: 0)
view.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
|
mit
|
f2ab9152c1993d20e438072e4511c6ee
| 32.148936 | 190 | 0.667843 | 5.77037 | false | false | false | false |
allbto/WayThere
|
ios/WayThere/Pods/Nimble/Nimble/Matchers/EndWith.swift
|
75
|
2705
|
import Foundation
/// A Nimble matcher that succeeds when the actual sequence's last element
/// is equal to the expected value.
public func endWith<S: SequenceType, T: Equatable where S.Generator.Element == T>(endingElement: T) -> NonNilMatcherFunc<S> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
if let actualValue = actualExpression.evaluate() {
var actualGenerator = actualValue.generate()
var lastItem: T?
var item: T?
do {
lastItem = item
item = actualGenerator.next()
} while(item != nil)
return lastItem == endingElement
}
return false
}
}
/// A Nimble matcher that succeeds when the actual collection's last element
/// is equal to the expected object.
public func endWith(endingElement: AnyObject) -> NonNilMatcherFunc<NMBOrderedCollection> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
let collection = actualExpression.evaluate()
return collection != nil && collection!.indexOfObject(endingElement) == collection!.count - 1
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring
/// where the expected substring's location is the actual string's length minus the
/// expected substring's length.
public func endWith(endingSubstring: String) -> NonNilMatcherFunc<String> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingSubstring)>"
if let collection = actualExpression.evaluate() {
let range = collection.rangeOfString(endingSubstring)
return range != nil && range!.endIndex == collection.endIndex
}
return false
}
}
extension NMBObjCMatcher {
public class func endWithMatcher(expected: AnyObject) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let actual = actualExpression.evaluate()
if let actualString = actual as? String {
let expr = Expression(expression: ({ actualString }), location: location)
return endWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = Expression(expression: ({ actual as? NMBOrderedCollection }), location: location)
return endWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
|
mit
|
a5a4fe8cf2b241129a3fba7f285024eb
| 41.936508 | 125 | 0.668022 | 5.475709 | false | false | false | false |
burningmantech/ranger-ims-mac
|
Incidents/IncidentController_edit.swift
|
1
|
13719
|
//
// IncidentController_edit.swift
// Incidents
//
// © 2015 Burning Man and its contributors. All rights reserved.
// See the file COPYRIGHT.md for terms.
//
import Cocoa
extension IncidentController {
func enableEditing() {
statePopUp?.enabled = true
priorityPopUp?.enabled = true
summaryField?.enabled = true
rangersTable?.enabled = true
rangerToAddField?.enabled = true
typesTable?.enabled = true
typeToAddField?.enabled = true
locationNameField?.enabled = true
locationRadialAddressField?.enabled = true
locationConcentricAddressField?.enabled = true
locationDescriptionField?.enabled = true
reportEntryToAddView?.editable = true
// This updates the save button correctly
updateEdited()
}
func disableEditing() {
statePopUp?.enabled = false
priorityPopUp?.enabled = false
summaryField?.enabled = false
rangersTable?.enabled = false
rangerToAddField?.enabled = false
typesTable?.enabled = false
typeToAddField?.enabled = false
locationNameField?.enabled = false
locationRadialAddressField?.enabled = false
locationConcentricAddressField?.enabled = false
locationDescriptionField?.enabled = false
reportEntryToAddView?.editable = false
saveButton?.enabled = false
}
@IBAction func editSummary(sender: AnyObject?) {
defer { updateView() }
let oldSummary: String
if let summary = incident!.summary { oldSummary = summary } else { oldSummary = "" }
let newSummary = summaryField!.stringValue
if newSummary == oldSummary { return }
logDebug("Summary changed to: \(newSummary)")
incident!.summary = newSummary
}
@IBAction func editState(sender: AnyObject?) {
defer { updateView() }
guard let selectedTag = statePopUp!.selectedItem?.tag else {
logError("Unable to get selected state tag")
return
}
guard let selectedState = IncidentStateTag(rawValue: selectedTag) else {
logError("Unknown state tag: \(selectedTag)")
return
}
let newState: IncidentState
switch selectedState {
case .New : newState = .New
case .OnHold : newState = .OnHold
case .Dispatched: newState = .Dispatched
case .OnScene : newState = .OnScene
case .Closed : newState = .Closed
}
if newState == incident!.state { return }
logDebug("State changed to: \(newState)")
incident!.state = newState
}
@IBAction func editPriority(sender: AnyObject?) {
defer { updateView() }
guard let selectedTag = priorityPopUp!.selectedItem?.tag else {
logError("Unable to get selected priority tag")
return
}
guard let selectedPriority = IncidentPriorityTag(rawValue: selectedTag) else {
logError("Unknown state tag: \(selectedTag)")
return
}
let newPriority: IncidentPriority
switch selectedPriority {
case .High : newPriority = .High
case .Normal: newPriority = .Normal
case .Low : newPriority = .Low
}
if newPriority == incident!.priority { return }
logDebug("Priority changed to: \(newPriority)")
incident!.priority = newPriority
}
@IBAction func editLocationName(sender: AnyObject?) {
defer { updateView() }
let oldName: String
if let name = incident!.location?.name { oldName = name } else { oldName = "" }
let newName = locationNameField!.stringValue
func knownLocation() -> Location? {
if (
locationConcentricAddressField?.stringValue == "" &&
locationRadialAddressField?.stringValue == "" &&
locationDescriptionField?.stringValue == ""
) {
if let knownLocation = dispatchQueueController?.locationsByLowercaseName[newName.lowercaseString] {
return knownLocation
}
}
return nil
}
let newLocation: Location?
if let location = knownLocation() {
newLocation = location
}
else if newName != oldName {
if incident!.location == nil {
newLocation = Location(name: newName)
} else {
newLocation = Location(
name: newName,
address: incident!.location!.address
)
}
} else {
newLocation = incident!.location
}
if newLocation != incident!.location {
logDebug("Location changed to: \(newLocation)")
incident!.location = newLocation
}
}
@IBAction func editAddressDescription(sender: AnyObject?) {
defer { updateView() }
let oldDescription: String
if let description = incident!.location?.address?.textDescription { oldDescription = description } else { oldDescription = "" }
let newDescription = locationDescriptionField!.stringValue
if newDescription == oldDescription { return }
let newLocation: Location
if incident!.location == nil || incident!.location!.address == nil {
newLocation = Location(
address: TextOnlyAddress(textDescription: newDescription)
)
}
else {
let newAddress: Address
let oldAddress = incident!.location!.address
if let oldAddress = oldAddress as? RodGarettAddress {
newAddress = RodGarettAddress(
concentric: oldAddress.concentric,
radialHour: oldAddress.radialHour,
radialMinute: oldAddress.radialMinute,
textDescription: newDescription
)
}
else if let _ = oldAddress as? TextOnlyAddress {
newAddress = TextOnlyAddress(textDescription: newDescription)
}
else {
logError("Unable to edit unknown address type: \(oldAddress)")
return
}
newLocation = Location(
name: incident!.location!.name,
address: newAddress
)
}
logDebug("Location changed to: \(newLocation)")
incident!.location = newLocation
}
private func _incidentRodGarrettAddress() -> RodGarettAddress? {
let oldAddress: RodGarettAddress
if let address = incident!.location?.address {
if let address = address as? RodGarettAddress {
oldAddress = address
}
else if let address = address as? TextOnlyAddress {
oldAddress = RodGarettAddress(textDescription: address.textDescription)
}
else {
logError("Unable to edit unknown address type: \(address)")
return nil
}
} else {
oldAddress = RodGarettAddress()
}
return oldAddress
}
@IBAction func editAddressRadial(sender: AnyObject?) {
defer { updateView() }
guard let oldAddress = _incidentRodGarrettAddress() else { return }
let oldRadialHour: Int, oldRadialMinute: Int
if let hour = oldAddress.radialHour, minute = oldAddress.radialMinute {
oldRadialHour = hour
oldRadialMinute = minute
} else {
oldRadialHour = -1
oldRadialMinute = -1
}
let newRadialName = locationRadialAddressField!.stringValue
let newRadialHour: Int?, newRadialMinute: Int?
if newRadialName == "" {
newRadialHour = nil
newRadialMinute = nil
} else {
let newRadialComponents = newRadialName.characters.split(isSeparator: {$0 == ":"})
guard newRadialComponents.count == 2 else {
logError("Unable to parse radial address components: \(newRadialName)")
return
}
guard let hour = Int(String(newRadialComponents[0])) else {
logError("Unable to parse radial hour: \(newRadialName)")
return
}
guard let minute = Int(String(newRadialComponents[1])) else {
logError("Unable to parse radial minute: \(newRadialName)")
return
}
newRadialHour = hour
newRadialMinute = minute
}
if newRadialHour == oldRadialHour && newRadialMinute == oldRadialMinute { return }
let newAddress = RodGarettAddress(
concentric: oldAddress.concentric,
radialHour: newRadialHour,
radialMinute: newRadialMinute,
textDescription: oldAddress.textDescription
)
let newLocation = Location(
name: incident!.location?.name,
address: newAddress
)
logDebug("Location changed to: \(newLocation)")
incident!.location = newLocation
}
@IBAction func editAddressConcentric(sender: AnyObject?) {
defer { updateView() }
guard let oldAddress = _incidentRodGarrettAddress() else { return }
let oldConcentricName: String
if let name = oldAddress.concentric?.description { oldConcentricName = name } else { oldConcentricName = "" }
let newConcentricName = locationConcentricAddressField!.stringValue
if newConcentricName == oldConcentricName { return }
func matchesEsplanade() -> Bool {
let esplanade = ConcentricStreet.Esplanade.description
let e = ConcentricStreet.E.description
for prefixLength in 1...esplanade.characters.count {
let prefix = newConcentricName.substringToIndex(esplanade.startIndex.advancedBy(prefixLength))
if e.hasPrefix(prefix) { continue } // Could be either E or Esplanade
return esplanade.hasPrefix(prefix)
}
return false
}
let newConcentric: ConcentricStreet?
if matchesEsplanade() { newConcentric = ConcentricStreet.Esplanade }
else if newConcentricName.hasPrefix("A") { newConcentric = ConcentricStreet.A }
else if newConcentricName.hasPrefix("B") { newConcentric = ConcentricStreet.B }
else if newConcentricName.hasPrefix("C") { newConcentric = ConcentricStreet.C }
else if newConcentricName.hasPrefix("D") { newConcentric = ConcentricStreet.D }
else if newConcentricName.hasPrefix("E") { newConcentric = ConcentricStreet.E }
else if newConcentricName.hasPrefix("F") { newConcentric = ConcentricStreet.F }
else if newConcentricName.hasPrefix("G") { newConcentric = ConcentricStreet.G }
else if newConcentricName.hasPrefix("H") { newConcentric = ConcentricStreet.H }
else if newConcentricName.hasPrefix("I") { newConcentric = ConcentricStreet.I }
else if newConcentricName.hasPrefix("J") { newConcentric = ConcentricStreet.J }
else if newConcentricName.hasPrefix("K") { newConcentric = ConcentricStreet.K }
else if newConcentricName.hasPrefix("L") { newConcentric = ConcentricStreet.L }
else if newConcentricName.hasPrefix("M") { newConcentric = ConcentricStreet.M }
else if newConcentricName.hasPrefix("N") { newConcentric = ConcentricStreet.N }
else if newConcentricName == "" { newConcentric = nil }
else {
logDebug("Unknown concentric street name: \(newConcentricName)")
return
}
let newAddress = RodGarettAddress(
concentric: newConcentric,
radialHour: oldAddress.radialHour,
radialMinute: oldAddress.radialMinute,
textDescription: oldAddress.textDescription
)
let newLocation = Location(
name: incident!.location!.name,
address: newAddress
)
logDebug("Location changed to: \(newLocation)")
incident!.location = newLocation
}
func addReportEntry() {
defer { updateView() }
guard let textStorage = reportEntryToAddView?.textStorage else {
logError("No text storage for report entry to add view?")
return
}
let reportTextTrimmed = textStorage.string.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
guard reportTextTrimmed.characters.count > 0 else { return }
if let username = NSUserDefaults.standardUserDefaults().stringForKey("IMSUserName") {
let author = Ranger(handle: username)
let entry = ReportEntry(author: author, text: reportTextTrimmed)
if incident!.reportEntries == nil {
incident!.reportEntries = []
}
incident!.reportEntries!.append(entry)
textStorage.setAttributedString(NSAttributedString())
}
}
}
|
apache-2.0
|
ec35a6e1f02feee168cec2784c1fcd8d
| 34.086957 | 135 | 0.578729 | 5.084507 | false | false | false | false |
quran/quran-ios
|
Sources/TranslationService/TranslationsRepository.swift
|
1
|
2714
|
//
// TranslationsRepository.swift
// Quran
//
// Created by Mohamed Afifi on 2/26/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import BatchDownloader
import Foundation
import PromiseKit
public struct TranslationsRepository {
let networkManager: TranslationNetworkManager
let persistence: ActiveTranslationsPersistence
public init(databasesPath: String, baseURL: URL) {
let urlSession = BatchDownloader.NetworkManager(session: .shared, baseURL: baseURL)
networkManager = DefaultTranslationNetworkManager(networkManager: urlSession, parser: JSONTranslationsParser())
persistence = SQLiteActiveTranslationsPersistence(directory: databasesPath)
}
public func downloadAndSyncTranslations() -> Promise<Void> {
let local = DispatchQueue.global().async(.promise, execute: persistence.retrieveAll)
let remote = networkManager.getTranslations()
return when(fulfilled: local, remote) // get local and remote
.map(combine) // combine local and remote
.map(saveCombined) // save combined list
}
private func combine(local: [Translation], remote: [Translation]) -> ([Translation], [String: Translation]) {
let localMapConstant = local.flatGroup { $0.fileName }
var localMap = localMapConstant
var combinedList: [Translation] = []
remote.forEach { remote in
var combined = remote
if let local = localMap[remote.fileName] {
combined.installedVersion = local.installedVersion
localMap[remote.fileName] = nil
}
combinedList.append(combined)
}
combinedList.append(contentsOf: localMap.map { $1 })
return (combinedList, localMapConstant)
}
private func saveCombined(translations: [Translation], localMap: [String: Translation]) throws {
try translations.forEach { translation in
if localMap[translation.fileName] != nil {
try self.persistence.update(translation)
} else {
try self.persistence.insert(translation)
}
}
}
}
|
apache-2.0
|
1afb813fb28c733828d06fbad1f8c83f
| 37.771429 | 119 | 0.681282 | 4.778169 | false | false | false | false |
Novkirishki/JustNinja
|
Just Ninja/Just Ninja/Wall.swift
|
1
|
1047
|
//
// Wall.swift
// Just Ninja
//
// Created by Nikolai Novkirishki on 2/1/16.
// Copyright © 2016 Nikolai Novkirishki. All rights reserved.
//
import Foundation
import SpriteKit
class Wall: SKSpriteNode {
let WALL_COLOR = UIColor.blackColor()
init() {
let wallSize = CGSizeMake(WALL_WIDTH, WALL_HEIGHT)
super.init(texture: nil, color: WALL_COLOR, size: wallSize)
loadPhysicsBodyWithSize(wallSize)
startMoving()
}
func loadPhysicsBodyWithSize(size: CGSize) {
physicsBody = SKPhysicsBody(rectangleOfSize: size)
physicsBody?.categoryBitMask = WALL_CATEGORY
physicsBody?.affectedByGravity = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startMoving() {
let moveLeft = SKAction.moveByX(-MOVING_SPEED, y: 0, duration: 1)
runAction(SKAction.repeatActionForever(moveLeft))
}
func stopMoving() {
removeAllActions()
}
}
|
mit
|
7af62b0771d306de2dcd2197feaf616f
| 23.928571 | 73 | 0.641491 | 4.394958 | false | false | false | false |
djwbrown/swift
|
stdlib/public/core/ValidUTF8Buffer.swift
|
2
|
5931
|
//===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Stores valid UTF8 inside an unsigned integer.
//
// Actually this basic type could be used to store any UInt8s that cannot be
// 0xFF
//
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct _ValidUTF8Buffer<
Storage: UnsignedInteger & FixedWidthInteger
> {
public typealias Element = Unicode.UTF8.CodeUnit
internal typealias _Storage = Storage
@_versioned
internal var _biasedBits: Storage
@_versioned
internal init(_biasedBits: Storage) {
self._biasedBits = _biasedBits
}
@_versioned
internal init(_containing e: Element) {
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits = Storage(extendingOrTruncating: e &+ 1)
}
}
extension _ValidUTF8Buffer : Sequence {
public typealias SubSequence = RangeReplaceableRandomAccessSlice<_ValidUTF8Buffer>
public struct Iterator : IteratorProtocol, Sequence {
public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits }
public mutating func next() -> Element? {
if _biasedBits == 0 { return nil }
defer { _biasedBits >>= 8 }
return Element(extendingOrTruncating: _biasedBits) &- 1
}
internal var _biasedBits: Storage
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _ValidUTF8Buffer : Collection {
public typealias IndexDistance = Int
public struct Index : Comparable {
@_versioned
internal var _biasedBits: Storage
@_versioned
internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits }
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits == rhs._biasedBits
}
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits > rhs._biasedBits
}
}
public var startIndex : Index {
return Index(_biasedBits: _biasedBits)
}
public var endIndex : Index {
return Index(_biasedBits: 0)
}
public var count : IndexDistance {
return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3
}
public func index(after i: Index) -> Index {
_debugPrecondition(i._biasedBits != 0)
return Index(_biasedBits: i._biasedBits >> 8)
}
public subscript(i: Index) -> Element {
return Element(extendingOrTruncating: i._biasedBits) &- 1
}
}
extension _ValidUTF8Buffer : BidirectionalCollection {
public func index(before i: Index) -> Index {
let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count
_debugPrecondition(offset != 0)
return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8))
}
}
extension _ValidUTF8Buffer : RandomAccessCollection {
public typealias Indices = DefaultRandomAccessIndices<_ValidUTF8Buffer>
@inline(__always)
public func distance(from i: Index, to j: Index) -> IndexDistance {
_debugPrecondition(_isValid(i))
_debugPrecondition(_isValid(j))
return (
i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount
) &>> 3
}
@inline(__always)
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
let startOffset = distance(from: startIndex, to: i)
let newOffset = startOffset + n
_debugPrecondition(newOffset >= 0)
_debugPrecondition(newOffset <= count)
return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3))
}
}
extension _ValidUTF8Buffer : RangeReplaceableCollection {
public init() {
_biasedBits = 0
}
public var capacity: IndexDistance {
return _ValidUTF8Buffer.capacity
}
public static var capacity: IndexDistance {
return Storage.bitWidth / Element.bitWidth
}
@inline(__always)
public mutating func append(_ e: Element) {
_debugPrecondition(count + 1 <= capacity)
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits |= Storage(e &+ 1) &<< (count &<< 3)
}
@inline(__always)
public mutating func removeFirst() {
_debugPrecondition(!isEmpty)
_biasedBits = _biasedBits._fullShiftRight(8)
}
@_versioned
internal func _isValid(_ i: Index) -> Bool {
return i == endIndex || indices.contains(i)
}
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(_isValid(target.lowerBound))
_debugPrecondition(_isValid(target.upperBound))
var r = _ValidUTF8Buffer()
for x in self[..<target.lowerBound] { r.append(x) }
for x in replacement { r.append(x) }
for x in self[target.upperBound...] { r.append(x) }
self = r
}
@inline(__always)
public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) {
_debugPrecondition(count + other.count <= capacity)
_biasedBits |= Storage(
extendingOrTruncating: other._biasedBits) &<< (count &<< 3)
}
}
extension _ValidUTF8Buffer {
public static var encodedReplacementCharacter : _ValidUTF8Buffer {
return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01)
}
}
/*
let test = _ValidUTF8Buffer<UInt64>(0..<8)
print(Array(test))
print(test.startIndex)
for (ni, i) in test.indices.enumerated() {
for (nj, j) in test.indices.enumerated() {
assert(test.distance(from: i, to: j) == nj - ni)
assert(test.index(i, offsetBy: nj - ni) == j)
}
}
*/
|
apache-2.0
|
a4adf8e8d0755f52311297b36f53a078
| 28.655 | 84 | 0.651492 | 4.248567 | false | false | false | false |
tikipatel/SwiftColors
|
SwiftColors/SwiftColors.swift
|
1
|
4590
|
// SwiftColors.swift
//
// Copyright (c) 2014 Doan Truong Thi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS)
import UIKit
typealias SWColor = UIColor
#else
import Cocoa
typealias SWColor = NSColor
#endif
public extension SWColor {
/**
Create non-autoreleased color with in the given hex string
Alpha will be set as 1 by default
- parameter hexString:
- returns: color with the given hex string
*/
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex string and alpha
- parameter hexString:
- parameter alpha:
- returns: color with the given hex string and alpha
*/
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}
if let _ = hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) {
// Deal with 3 character Hex strings
if hex.characters.count == 3 {
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1))
let greenHex = hex.substringWithRange(hex.startIndex.advancedBy(1) ..< hex.startIndex.advancedBy(2))
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2))
let greenHex = hex.substringWithRange(hex.startIndex.advancedBy(2) ..< hex.startIndex.advancedBy(4))
let blueHex = hex.substringWithRange(hex.startIndex.advancedBy(4) ..< hex.startIndex.advancedBy(6))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else {
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases, not a feature. -- Apple Forum
self.init()
return nil
}
}
/**
Create non-autoreleased color with in the given hex value
Alpha will be set as 1 by default
- parameter hex:
- returns: color with the given hex value
*/
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex value and alpha
- parameter hex:
- parameter alpha:
- returns: color with the given hex value and alpha
*/
public convenience init?(hex: Int, alpha: Float) {
let hexString = NSString(format: "%2X", hex) as String
self.init(hexString: hexString as String , alpha: alpha)
}
}
|
mit
|
f18da2241cace343df1186656b331304
| 38.913043 | 140 | 0.635076 | 4.636364 | false | false | false | false |
rinov/RxSmartBag
|
RxSmartBag/Classes/RxSmartBag.swift
|
1
|
1901
|
//
// RxSmartBag.swift
// Pods
//
// Created by Ryo Ishikawa on 2017/05/11.
//
//
import Foundation
import RxSwift
// `AllocatedObject` is used for associated object.
extension DisposeBag {
struct AllocatedObject {
static var instance = DisposeBag()
}
}
//`SmartBagManagerable` represents that having a stored property of dispose bag by automatically.
public protocol SmartBagManagerable {
var smartBag: DisposeBag { get set }
}
// Implements smartBag by objective-c runtime functions.
extension SmartBagManagerable {
public var smartBag: DisposeBag {
get {
var disposeBag: DisposeBag!
synchronized {
if let lookup = objc_getAssociatedObject(self, &DisposeBag.AllocatedObject.instance) as? DisposeBag {
disposeBag = lookup
} else {
// If a new dispose bag were setted,`smartBag` will release current disposable reference immediately.
disposeBag = associateObject(newValue: DisposeBag())
}
}
return disposeBag
}
set {
associateObject(newValue: newValue)
}
}
private func synchronized(_ closure: () -> ()) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
closure()
}
@discardableResult
private func associateObject(newValue: DisposeBag) -> DisposeBag {
synchronized {
objc_setAssociatedObject(self, &DisposeBag.AllocatedObject.instance, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return newValue
}
}
// For more simply syntax, like `smartBag += A.subscribe(...)`.
public func += (lhs: DisposeBag, rhs: Disposable) {
rhs.disposed(by: lhs)
}
extension Disposable {
public func disposed(by bag: SmartBagManagerable) {
bag.smartBag.insert(self)
}
}
|
mit
|
ae86fd741c8a7c4a09c3eb4d5451ce8a
| 26.955882 | 126 | 0.624934 | 4.647922 | false | false | false | false |
soapyigu/LeetCode_Swift
|
LinkedList/ReorderList.swift
|
1
|
1668
|
/**
* Question Link: https://leetcode.com/problems/reorder-list/
* Primary idea: Use Runner Tech to split the list, reverse the second half, and merge them
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class ReorderList {
func reorderList(head: ListNode?) {
guard let head = head else {
return
}
var prev: ListNode? = head
var post: ListNode? = head
_split(&prev, &post)
prev = head
post = _reverse(&post)
_merge(&prev, &post)
}
private func _split(inout prev: ListNode?, inout _ post: ListNode?) {
while post != nil && post!.next != nil {
prev = prev!.next
post = post!.next!.next
}
post = prev!.next
prev!.next = nil
}
private func _reverse(inout head: ListNode?) -> ListNode? {
var prev = head
var temp: ListNode?
while prev != nil {
let post = prev!.next
prev!.next = temp
temp = prev
prev = post
}
return temp
}
private func _merge(inout prev: ListNode?, inout _ post: ListNode?) {
while prev != nil && post != nil{
let preNext = prev!.next
let posNext = post!.next
prev!.next = post
post!.next = preNext
prev = preNext
post = posNext
}
}
}
|
mit
|
64bd0bba76265615e77c94a8582484f1
| 22.180556 | 91 | 0.502998 | 4.233503 | false | false | false | false |
iOSDevLog/iOSDevLog
|
201. UI Test/Swift/ListerOSX/AppDelegate.swift
|
1
|
2875
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The application delegate.
*/
import Cocoa
import ListerKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: Properties
@IBOutlet weak var todayListMenuItem: NSMenuItem!
var ubiquityIdentityDidChangeNotificationToken: NSObjectProtocol?
// MARK: NSApplicationDelegate
func applicationDidFinishLaunching(notification: NSNotification) {
AppConfiguration.sharedConfiguration.runHandlerOnFirstLaunch {
// If iCloud is enabled and it's the first launch, we'll show the Today document initially.
if AppConfiguration.sharedConfiguration.isCloudAvailable {
// Make sure that no other documents are visible except for the Today document.
NSDocumentController.sharedDocumentController().closeAllDocumentsWithDelegate(nil, didCloseAllSelector: nil, contextInfo: nil)
self.openTodayDocument()
}
}
// Update the menu item at app launch.
updateTodayListMenuItemForCloudAvailability()
ubiquityIdentityDidChangeNotificationToken = NSNotificationCenter.defaultCenter().addObserverForName(NSUbiquityIdentityDidChangeNotification, object: nil, queue: nil) { [weak self] _ in
// Update the menu item once the iCloud account changes.
self?.updateTodayListMenuItemForCloudAvailability()
return
}
}
// MARK: IBActions
/**
Note that there are two possibile callers for this method. The first is the application delegate if
it's the first launch. The other possibility is if you use the keyboard shortcut (Command-T) to open
your Today document.
*/
@IBAction func openTodayDocument(_: AnyObject? = nil) {
TodayListManager.fetchTodayDocumentURLWithCompletionHandler { url in
if let url = url {
dispatch_async(dispatch_get_main_queue()) {
let documentController = NSDocumentController.sharedDocumentController()
documentController.openDocumentWithContentsOfURL(url, display: true) { _ in
// Configuration of the document can go here...
}
}
}
}
}
// MARK: Convenience
func updateTodayListMenuItemForCloudAvailability() {
if AppConfiguration.sharedConfiguration.isCloudAvailable {
todayListMenuItem.action = "openTodayDocument:"
todayListMenuItem.target = self
}
else {
todayListMenuItem.action = nil
todayListMenuItem.target = nil
}
}
}
|
mit
|
028d1548c235cf9cf03bc902f83687ac
| 35.367089 | 193 | 0.643578 | 5.839431 | false | true | false | false |
Harry-L/5-3-1
|
PlateMath/PlateMath/ViewController.swift
|
1
|
2006
|
//
// ViewController.swift
// PlateMath
//
// Created by Harry Liu on 2016-01-18.
// Copyright © 2016 HarryLiu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Plates.doTheMath(weight: 315, collar: 0, five: 2, ten: 2, twentyFive: 2, thirtyFive: 2, fortyFive: 20)
let p = Plates()
let array = p.doTheMath(weight: 285, bar: 45, collar: 5, five: 9, ten: 9, twentyFive: 9, thirtyFive: 9, fortyFive: 20)
addView(array)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addView(plates: [Int]) {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 256, height: 256), false, 0)
let context = UIGraphicsGetCurrentContext()
var counter = 0
var values = [45, 35, 25, 10, 5]
for (index,weight) in plates.enumerate() {
for _ in 0 ..< weight {
let rect = CGRect(x: 15 + counter * 5, y: 30 + (45-values[index])/2, width: 5, height: values[index])
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetLineWidth(context, 1)
CGContextAddRect(context, rect)
CGContextDrawPath(context, .FillStroke)
counter++
}
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 512, height: 512))
imageView.image = img
view.addSubview(imageView)
}
}
|
mit
|
9d036b20371f025c53226f5f7c9733a0
| 29.846154 | 126 | 0.579551 | 4.684579 | false | false | false | false |
itechline/bonodom_new
|
SlideMenuControllerSwift/AddAdmonitor.swift
|
1
|
14943
|
//
// AddAdmonitor.swift
// Bonodom
//
// Created by Attila Dán on 2016. 07. 07..
// Copyright © 2016. Itechline. All rights reserved.
//
import UIKit
import SwiftyJSON
class AddAdmonitor: UIViewController {
var items = [SpinnerModel]()
var kivitel_id = 0
var szintek_min_id = 0
var szintek_max_id = 0
var szobaszam_min_id = 0
var szobaszam_max_id = 0
var lift_id = 0
var erkely_id = 0
var meret_id = 0
var kilatas_id = 0
var butorozott_id = 0
var parkolas_id = 0
var allapot_id = 0
var etan_id = 0
var pickerData_butorozott = [[String : String]]()
var pickerData_szobaszam = [[String : String]]()
var pickerData_allapot = [[String : String]]()
var pickerData_emelet = [[String : String]]()
var pickerData_ing_tipus = [[String : String]]()
var pickerData_erkely = [[String : String]]()
var pickerData_meret = [[String : String]]()
var pickerData_parkolas = [[String : String]]()
var pickerData_futes = [[String : String]]()
var pickerData_lift = [[String : String]]()
var pickerData_etan = [[String : String]]()
var pickerData_kilatas = [[String : String]]()
@IBOutlet weak var figyelo_neve: UITextField!
@IBOutlet weak var kereses: UITextField!
@IBOutlet weak var ar_min_text: UITextField!
@IBOutlet weak var ar_max_text: UITextField!
@IBOutlet weak var kivitel_text: UIButton!
@IBAction func kivitel_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Ingatlan típus", options: pickerData_ing_tipus, selected: "0") {
(value, display) -> Void in
self.kivitel_text.setTitle(display, forState: UIControlState.Normal)
self.kivitel_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var szintek_text: UIButton!
@IBAction func szintek_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Szintek Minimum", options: pickerData_emelet, selected: "0") {
(value, display) -> Void in
self.szintek_text.setTitle(display, forState: UIControlState.Normal)
self.szintek_min_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var szintek_max_text: UIButton!
@IBAction func szintek_max_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Szintek Maximum", options: pickerData_emelet, selected: "0") {
(value, display) -> Void in
self.szintek_max_text.setTitle(display, forState: UIControlState.Normal)
self.szintek_max_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var szobaszam_min_text: UIButton!
@IBAction func szobaszam_min_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Szobaszám Minimum", options: pickerData_szobaszam, selected: "0") {
(value, display) -> Void in
self.szobaszam_min_text.setTitle(display, forState: UIControlState.Normal)
self.szobaszam_min_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var szobaszam_max_text: UIButton!
@IBAction func szobaszam_max_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Szobaszám Minimum", options: pickerData_szobaszam, selected: "0") {
(value, display) -> Void in
self.szobaszam_max_text.setTitle(display, forState: UIControlState.Normal)
self.szobaszam_max_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var lift_text: UIButton!
@IBAction func lift_button(sender: AnyObject) {
self.dismissKeyboard()
pickerData_lift = [
["value": "0", "display": "Nincs megadva"],
["value": "1", "display": "Van"],
["value": "2", "display": "Nincs"]
]
PickerDialog().show("Lift", options: pickerData_lift, selected: "0") {
(value, display) -> Void in
self.lift_text.setTitle(display, forState: UIControlState.Normal)
self.lift_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var erkely_text: UIButton!
@IBAction func erkely_button(sender: AnyObject) {
self.dismissKeyboard()
pickerData_erkely = [
["value": "0", "display": "Nincs megadva"],
["value": "1", "display": "Van"],
["value": "2", "display": "Nincs"]
]
PickerDialog().show("Erkély", options: pickerData_erkely, selected: "0") {
(value, display) -> Void in
self.erkely_text.setTitle(display, forState: UIControlState.Normal)
self.erkely_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var meret_text: UIButton!
@IBAction func meret_button(sender: AnyObject) {
self.dismissKeyboard()
pickerData_meret = [
["value": "0", "display": "Nincs megadva"],
["value": "1", "display": "25-ig"],
["value": "2", "display": "26-50"],
["value": "3", "display": "51-75"],
["value": "4", "display": "76_100"],
["value": "5", "display": "101-125"],
["value": "6", "display": "126-150"],
["value": "7", "display": "150+"]
]
PickerDialog().show("Méret", options: pickerData_meret, selected: "0") {
(value, display) -> Void in
self.meret_text.setTitle(display, forState: UIControlState.Normal)
self.meret_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var kilatas_text: UIButton!
@IBAction func kilatas_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Kilátás", options: pickerData_kilatas, selected: "0") {
(value, display) -> Void in
self.kilatas_text.setTitle(display, forState: UIControlState.Normal)
self.kilatas_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var butorozott_text: UIButton!
@IBAction func butorozott_button(sender: AnyObject) {
self.dismissKeyboard()
pickerData_butorozott = [
["value": "0", "display": "Nincs megadva"],
["value": "1", "display": "Nem"],
["value": "2", "display": "Igen"],
["value": "3", "display": "Alku tárgya"]
]
PickerDialog().show("Bútor", options: pickerData_butorozott, selected: "0") {
(value, display) -> Void in
self.butorozott_text.setTitle(display, forState: UIControlState.Normal)
self.butorozott_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var parkolas_text: UIButton!
@IBAction func parkolas_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Parkolás", options: pickerData_parkolas, selected: "0") {
(value, display) -> Void in
self.parkolas_text.setTitle(display, forState: UIControlState.Normal)
self.parkolas_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var allapot_text: UIButton!
@IBAction func allapot_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Állapot", options: pickerData_allapot, selected: "0") {
(value, display) -> Void in
self.allapot_text.setTitle(display, forState: UIControlState.Normal)
self.allapot_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBOutlet weak var etan_text: UIButton!
@IBAction func etan_button(sender: AnyObject) {
self.dismissKeyboard()
PickerDialog().show("Energia tanusítvány", options: pickerData_etan, selected: "0") {
(value, display) -> Void in
self.etan_text.setTitle(display, forState: UIControlState.Normal)
self.etan_id = Int(value)!
print("Unit selected: \(value)")
}
}
@IBAction func save_admonitor_button(sender: AnyObject) {
self.dismissKeyboard()
let name : String = figyelo_neve!.text!
let search : String = kereses!.text!
let ar_min : String = ar_min_text!.text!
let ar_max : String = ar_max_text!.text!
AdMonitorUtil.sharedInstance.add_admonitor(name, butor: String(butorozott_id), lift: String(lift_id), erkely: String(erkely_id), meret: String(meret_id), szsz_max: String(szobaszam_max_id), szsz_min: String(szobaszam_min_id), emelet_max: String(szintek_max_id), emelet_min: String(szintek_min_id), tipus_id: kivitel_id, allapot_id: allapot_id, energia_id: etan_id, kilatas_id: kilatas_id, parkolas: parkolas_id, ar_min: ar_min, ar_max: ar_max, kulcsszo: search, onCompletion: { (json: JSON) in
print (json)
var err: Bool!
err = json["error"].boolValue
if (!err) {
dispatch_async(dispatch_get_main_queue(),{
//viewController.dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.popViewControllerAnimated(true);
})
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
loadSpinners()
// Do view setup here.
}
func loadSpinners() {
SpinnerUtil.sharedInstance.get_list_ingatlantipus{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "tipus"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_ing_tipus.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_ing_tipus.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlanemelet{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "emelet"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_emelet.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_emelet.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlanszoba{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "szsz"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_szobaszam.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_szobaszam.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlankilatas{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "kilatas"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_kilatas.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_kilatas.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlanparkolas{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "parkolas"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_parkolas.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_parkolas.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlanallapota{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "allapot"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_allapot.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_allapot.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
SpinnerUtil.sharedInstance.get_list_ingatlanenergia{ (json: JSON) in
self.items.removeAll()
if let results = json.array {
for entry in results {
self.items.append(SpinnerModel(json: entry, type: "etan"))
}
for i in 0...self.items.count-1 {
if (i != 0) {
self.pickerData_etan.append(["value": self.items[i].value, "display": self.items[i].display])
} else {
self.pickerData_etan.append(["value": self.items[i].value, "display": "Nincs megadva"])
}
}
}
}
}
}
|
mit
|
62cfb1fff366a56c18e733441b2a6844
| 38.808 | 501 | 0.533628 | 4.011825 | false | false | false | false |
polkahq/PLKSwift
|
Sources/polka/network/PLKRest.swift
|
1
|
3962
|
//
// PLKRest.swift
//
// Created by Alvaro Talavera on 4/13/16.
// Copyright © 2016 Polka. All rights reserved.
//
import Foundation
import SwiftyJSON
public enum PLKRestMethods : String {
case GET
case POST
case PUT
case DELETE
}
public class PLKRest : NSObject {
var url:URL?
var method:PLKRestMethods
var session:URLSession?
public var task:URLSessionDataTask?
public init(url:String, method:PLKRestMethods = .GET) {
self.url = URL(string: url)
self.method = method
let configuration = URLSessionConfiguration.default
self.session = URLSession(configuration: configuration)
}
private var _header:Dictionary<String,String>?
public func setHeader(params:Dictionary<String,String>) -> PLKRest {
_header = params
return self
}
private var _formData:Dictionary<String,String>?
public func setFormData(params:Dictionary<String,String>) -> PLKRest {
_formData = params
return self
}
public func cancelTask() {
if task != nil {
task?.cancel()
task = nil
}
}
public func executeWithData(completion: @escaping (_ data: Data?, _ response: URLResponse?) -> Void) {
self.cancelTask()
guard let s = self.session, let req = getRequest() else {
DispatchQueue.main.sync {
completion(nil, nil)
}
return
}
task = s.dataTask(with:req, completionHandler: {(data, response, error) in
if let error = error as NSError? {
if error.code == NSURLErrorCancelled {
return
}
}
DispatchQueue.main.sync {
completion(data, response)
}
});
task?.resume()
}
public func executeWithJSON(completion: @escaping (_ data: JSON?, _ response: URLResponse?) -> Void) {
self.cancelTask()
guard let s = self.session, let req = getRequest() else {
DispatchQueue.main.sync { completion(nil, nil) }
return
}
task = s.dataTask(with:req, completionHandler: {(data, response, error) in
if let error = error as NSError? {
if error.code == NSURLErrorCancelled {
return
}
}
if let data = data, let json = PLKJSON.decode(data: data) {
DispatchQueue.main.sync {
completion(json, response)
}
return
}
DispatchQueue.main.sync { completion(nil, response) }
});
task?.resume()
}
// -----------
private func getRequest() -> URLRequest? {
guard let url = self.url else {
return nil
}
var request = URLRequest(url: url)
switch (self.method) {
case .GET:
request.httpMethod = "get"
case .POST:
request.httpMethod = "post"
case .PUT:
request.httpMethod = "put"
case .DELETE:
request.httpMethod = "delete"
}
if(_header != nil) {
for (key, value) in _header! {
request.addValue(value, forHTTPHeaderField: key)
}
}
if(_formData != nil) {
request.httpBody = queryStringWithParams().data(using: String.Encoding.utf8);
}
return request
}
private func queryStringWithParams() -> String {
let query = NSMutableArray()
for (key, value) in _formData! {
query.add(key + "=" + value)
}
return query.componentsJoined(by: "&");
}
}
|
mit
|
3034c4cbab97934e0950a9864e02bafb
| 24.554839 | 106 | 0.506185 | 4.932752 | false | false | false | false |
LamineNdy/SampleApp
|
SampleApp/Classes/ViewControllers/AlbumTableViewController.swift
|
1
|
2488
|
//
// AlbumTableViewController.swift
// QontoTest
//
// Created by Lamine Ndiaye on 30/11/2016.
// Copyright © 2016 Lamine. All rights reserved.
//
import UIKit
private let albumCellId = "albumCellReuseIdentifier"
private let photoSegue = "photos"
class AlbumTableViewController: UITableViewController {
var albums: [Album]?
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
self.title = user?.userName
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(triggerFetch), for: UIControlEvents.valueChanged)
triggerFetch()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let albums = albums else {
return 0
}
return albums.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let album = albums?[indexPath.row] else {
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(withIdentifier: albumCellId, for: indexPath)
cell.textLabel?.text = album.title
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == photoSegue {
let vc = segue.destination as? PhotoCollectionViewController
if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) {
let album = self.albums?[indexPath.row]
vc?.album = album
}
}
}
func triggerFetch () {
self.refreshControl?.beginRefreshing()
self.addIndicator()
WebService.fetchAlbums((user?.userId)!) { (albums, error) -> () in
if error == nil {
DispatchQueue.main.async {
self.albums = albums
}
} else {
DispatchQueue.main.async {
self.showAlert(message: "Error")
self.refreshControl?.endRefreshing()
print(error!)
}
}
DispatchQueue.main.async {
self.removeIndicator()
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
}
}
|
mit
|
8ea93b47d46b5a784f855a55656e37f8
| 26.94382 | 108 | 0.666265 | 4.710227 | false | false | false | false |
callumboddy/Buttons
|
ButtonKit/ButtonKit/ButtonEffects.swift
|
1
|
2087
|
//
// ButtonGlow.swift
// Buttons
//
// Created by Callum Boddy on 22/08/2016.
// Copyright © 2016 Callum Boddy. All rights reserved.
//
import Foundation
import UIKit
public enum ButtonEffectStyle {
case ThreeDimentional
case Shadow
case Glow
}
public struct ButtonEffect {
static func applyEffectForEffectStyle(button: UIButton, effect: ButtonEffectStyle) {
switch effect {
case .ThreeDimentional:
button.apply3D()
case .Shadow:
button.applyShadow()
case .Glow:
button.applyGlow()
}
}
}
private extension UIButton {
func applyGlow() {
guard let color = backgroundColor else { return }
let layer = shadowLayer(color: color.darkenColor(30), offet: CGSize(width: 0.0, height: 0.0), opacity: 0.7, radius: 3)
applyLayer(layer)
}
func apply3D() {
guard let color = backgroundColor else { return }
let layer = shadowLayer(color: color.darkenColor(30), offet: CGSize(width: 0.0, height: 4.0), opacity: 1, radius: 0)
applyLayer(layer)
}
func applyShadow() {
let layer = shadowLayer(color: UIColor.blackColor(), offet: CGSize(width: 1.0, height: 1.0), opacity: 0.3, radius: 2)
applyLayer(layer)
}
private func applyLayer(layer: UIView) {
self.superview?.addSubview(layer)
self.superview?.sendSubviewToBack(layer)
}
private func shadowLayer(color color: UIColor, offet: CGSize, opacity: Float, radius: CGFloat) -> UIView {
let shadowLayer = UIView(frame: self.frame)
shadowLayer.backgroundColor = UIColor.clearColor()
shadowLayer.layer.shadowColor = color.CGColor
shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).CGPath
shadowLayer.layer.shadowOffset = offet
shadowLayer.layer.shadowOpacity = opacity
shadowLayer.layer.shadowRadius = radius
shadowLayer.layer.masksToBounds = true
shadowLayer.clipsToBounds = false
return shadowLayer
}
}
|
mit
|
4b1ed9a0a4456ac06daaff1b1a7ab264
| 30.606061 | 126 | 0.658677 | 4.222672 | false | false | false | false |
lanstonpeng/Focord2
|
Focord2/MotionManager.swift
|
1
|
2948
|
//
// MotionManager.swift
// Focord2
//
// Created by Lanston Peng on 8/2/14.
// Copyright (c) 2014 Vtm. All rights reserved.
//
import UIKit
import CoreMotion
import QuartzCore
public protocol MotionManagerDelegate
{
func deviceDidFlipToBack()
func deviceDidFlipToFront()
}
class MotionManager: NSObject {
internal var boundView:UIView?
var didFlipToBack:Bool
var delegate:MotionManagerDelegate?
var duration:CGFloat
var motionManager:CMMotionManager
class var instance:MotionManager{
struct Singleton{
static let single = MotionManager()
}
return Singleton.single
}
override init()
{
motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 1.0
motionManager.deviceMotionUpdateInterval = 1.0 / 60
self.didFlipToBack = false
duration = 0.0;
}
func startListen()
{
let updateQueue:NSOperationQueue = NSOperationQueue()
updateQueue.name = "update motion"
motionManager.startAccelerometerUpdatesToQueue(updateQueue, withHandler: { (accelerometerData:CMAccelerometerData!,error:NSError!) -> Void in
let accelData:CMAccelerometerData = self.motionManager.accelerometerData
if( abs(accelData.acceleration.z - 1) < 0.01 )
{
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.delegate!.deviceDidFlipToBack()
})
self.didFlipToBack = true
self.duration += 1.0
/*
CGFloat angle = atan2( motion.gravity.x, motion.gravity.y );
CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
self.horizon.transform = transform;
*/
}
else
{
self.didFlipToBack = false
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.delegate!.deviceDidFlipToFront()
})
}
})
}
func startListenDeviceMotion(callback:(deviceMotion:CMDeviceMotion!,error:NSError!) -> Void)
{
let deviceQueue:NSOperationQueue = NSOperationQueue()
motionManager.startDeviceMotionUpdatesToQueue(deviceQueue, withHandler: {(motion:CMDeviceMotion! , error:NSError! ) -> Void in
var transform = CATransform3DMakeRotation(CGFloat(motion.attitude.pitch), 1, 0, 0)
transform = CATransform3DRotate(transform, CGFloat(motion.attitude.roll), 0, 1, 0)
// dispatch_async(dispatch_get_main_queue(), {() -> Void in
// })
callback(deviceMotion: motion, error: error)
})
}
func stopListen()
{
duration = 0
motionManager.stopAccelerometerUpdates()
}
}
|
mit
|
d126e74cff1a2e0a5bd51da2a6e83a45
| 30.698925 | 150 | 0.592605 | 5.039316 | false | false | false | false |
jakubholik/mi-ios
|
mi-ios/PanoramaViewController.swift
|
1
|
3416
|
//
// SecondViewController.swift
//
// Created by Jakub Holík on 06.03.17.
// Copyright © 2017 Symphony No. 9 s.r.o. All rights reserved.
//
import UIKit
import CoreLocation
import CoreMotion
import GLKit
struct Attitude{
var roll: Double
var pitch: Double
var yaw: Double
var quaternion: CMQuaternion
}
class PanoramaViewController: UIViewController, CLLocationManagerDelegate {
let viewModel = PanoramaViewModel()
var locationManager = CLLocationManager()
var motionManager = CMMotionManager()
var currentPage = 0
var currentView: UIView?
var imageVRView: GVRPanoramaView?
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.headingAvailable() {
locationManager.headingFilter = 1
locationManager.startUpdatingHeading()
locationManager.delegate = self
viewModel.headingAvailable = true
}
GrayTheme.setTheme(for: self)
viewModel.delegate = self
viewModel.initializePanoramaView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.reloadPanoramaView()
if motionManager.isDeviceMotionAvailable {
motionManager.deviceMotionUpdateInterval = 1.0/60.0
motionManager.startDeviceMotionUpdates(to: OperationQueue.main) { (data, _) in
guard let data = data else { return }
self.viewModel.deviceMotionUpdate(with: data.gravity, and: data.attitude)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if motionManager.isDeviceMotionAvailable {
motionManager.stopDeviceMotionUpdates()
}
if CLLocationManager.headingAvailable() {
locationManager.stopUpdatingHeading()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewModel.isPanoramaLoaded = false
viewModel.viewStandby = true
if let imageVRView = imageVRView {
imageVRView.removeFromSuperview()
self.imageVRView = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
if !viewModel.isPanoramaLoaded {
viewModel.loadFirstPanorama(with: newHeading)
}
}
func setCurrentViewFromTouch(touchPoint point:CGPoint) {
if imageVRView!.frame.contains(point) {
currentView = imageVRView
}
}
}
extension PanoramaViewController: GVRWidgetViewDelegate {
func widgetView(_ widgetView: GVRWidgetView!, didLoadContent content: Any!) {
if content is UIImage && (imageVRView != nil){
imageVRView?.isHidden = false
}
}
func widgetView(_ widgetView: GVRWidgetView!, didFailToLoadContent content: Any!, withErrorMessage errorMessage: String!) {
print(errorMessage)
}
func widgetView(_ widgetView: GVRWidgetView!, didChange displayMode: GVRWidgetDisplayMode) {
currentView = widgetView
viewModel.currentDisplayMode = displayMode
if currentView == imageVRView && viewModel.currentDisplayMode != GVRWidgetDisplayMode.embedded {
view.isHidden = true
} else {
view.isHidden = false
}
}
func widgetViewDidTap(_ widgetView: GVRWidgetView!) {
guard viewModel.currentDisplayMode != GVRWidgetDisplayMode.embedded else {return}
if currentView == imageVRView {
print("WidgetView tapped and is of type VRView")
}
}
}
|
mit
|
64186d1173f173c016ad9a3d23f137ed
| 23.042254 | 125 | 0.739895 | 4.108303 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/DAOObjects/SingleDayActivityGoal.swift
|
1
|
2319
|
//
// SingleDayActivityGoal.swift
// Yona
//
// Created by Anders Liebl on 29/06/2016.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class SingleDayActivityGoal : NSObject {
var totalActivityDurationMinutes : Int
var goalAccomplished : Bool = false
var totalMinutesBeyondGoal : Int
var dayofweek : DayOfWeek
var yonadayDetails : String
init(data : (String, AnyObject) , allGoals : [Goal]) {
let key = data.0
let value = data.1
dayofweek = SingleDayActivityGoal.dayOfWeekFromString(key)
if let total = value[YonaConstants.jsonKeys.totalActivityDurationMinutes] as? Int {
totalActivityDurationMinutes = total
} else {
totalActivityDurationMinutes = 0
}
if let total = value[YonaConstants.jsonKeys.goalAccomplished] as? Bool {
goalAccomplished = total
} else {
goalAccomplished = false
}
if let total = value[YonaConstants.jsonKeys.totalMinutesBeyondGoal] as? Int {
totalMinutesBeyondGoal = total
} else {
totalMinutesBeyondGoal = 0
}
if let links = value[YonaConstants.jsonKeys.linksKeys] as? [String: AnyObject]{
if let link = links[YonaConstants.jsonKeys.yonaDayDetails] as? [String: AnyObject],
let dayLink = link[YonaConstants.jsonKeys.hrefKey] as? String{
yonadayDetails = dayLink
} else {
yonadayDetails = ""
}
} else {
yonadayDetails = ""
}
}
class func dayOfWeekFromString(_ day:String) -> DayOfWeek {
if day.lowercased() == "sunday" {
return .sunday
} else if day.lowercased() == "monday" {
return .monday
} else if day.lowercased() == "tuesday" {
return .tuesday
} else if day.lowercased() == "wednesday" {
return .wednesday
} else if day.lowercased() == "thursday" {
return .thursday
} else if day.lowercased() == "friday" {
return .friday
} else if day.lowercased() == "saturday" {
return .saturday
}
return .sunday
}
}
|
mpl-2.0
|
5dbfad61e43fbc8f7abfac4c9aa4bc79
| 29.5 | 95 | 0.564711 | 4.682828 | false | false | false | false |
rlaferla/InfiniteTableView
|
InfiniteTableView/Date+Extensions.swift
|
1
|
1274
|
//
// Date+Extensions.swift
// InfiniteTableView
import Foundation
public extension Date {
/// SwiftRandom extension
public static func randomWithinDaysBeforeToday(days: Int) -> Date {
let today = Date()
let r1 = arc4random_uniform(UInt32(days))
let r2 = arc4random_uniform(UInt32(23))
let r3 = arc4random_uniform(UInt32(23))
let r4 = arc4random_uniform(UInt32(23))
var offsetComponents = DateComponents()
offsetComponents.day = Int(r1) * -1
offsetComponents.hour = Int(r2)
offsetComponents.minute = Int(r3)
offsetComponents.second = Int(r4)
let rndDate1 = Calendar.current.date(byAdding: offsetComponents, to: today)
return rndDate1!
}
/// SwiftRandom extension
public static func random() -> Date {
let randomTime = TimeInterval(arc4random_uniform(UInt32.max))
return Date(timeIntervalSince1970: randomTime)
}
func dateWithoutTime() -> Date {
let cal:Calendar = Calendar.current
let components:DateComponents = (cal as NSCalendar).components([.year, .month, .day], from: self)
let date:Date = cal.date(from: components)!
return date
}
}
|
mit
|
ce625c34f863559ba5f7b6e2df4183ac
| 30.073171 | 105 | 0.624019 | 4.163399 | false | false | false | false |
ElegantTeam/ETCollectionViewWaterFallLayout
|
Class/ETCollectionViewWaterFallLayout.swift
|
1
|
18018
|
//
// ETCollectionViewWaterFallLayout.swift
// ETCollectionViewWaterFallLayout
//
// Created by Volley on 2017/4/20.
// Copyright © 2017年 Elegant Team. All rights reserved.
//
import UIKit
public enum ETCollectionViewWaterfallLayoutItemRenderDirection {
case shortestFirst
case leftToRight
case rightToLeft
}
@objc protocol ETCollectionViewDelegateWaterfallLayout: class, UICollectionViewDelegate {
@objc func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, columnCountFor section: Int) -> Int
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, heightForFooterIn section: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, insetForSectionAt index: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, insetForHeaderIn section: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, insetForFooterIn section: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt index: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, minimumColumnSpacingForSectionAt index: Int) -> CGFloat
}
class ETCollectionViewWaterfallLayout: UICollectionViewLayout {
open var columnCount: Int = 2 {
didSet {
if columnCount != oldValue {
self.invalidateLayout()
}
}
}
open var minimumColumnSpacing: CGFloat = 10.0 {
didSet {
if minimumColumnSpacing != oldValue {
self.invalidateLayout()
}
}
}
open var minimumInteritemSpacing: CGFloat = 10.0 {
didSet {
if minimumInteritemSpacing != oldValue {
self.invalidateLayout()
}
}
}
open var headerHeight: CGFloat = 0.0 {
didSet {
if headerHeight != oldValue {
self.invalidateLayout()
}
}
}
open var footerHeight: CGFloat = 0.0 {
didSet {
if footerHeight != oldValue {
self.invalidateLayout()
}
}
}
open var headerInset: UIEdgeInsets = UIEdgeInsets.zero {
didSet {
if headerInset != oldValue {
self.invalidateLayout()
}
}
}
open var footerInset: UIEdgeInsets = UIEdgeInsets.zero {
didSet {
if footerInset != oldValue {
self.invalidateLayout()
}
}
}
open var sectionInset: UIEdgeInsets = UIEdgeInsets.zero {
didSet {
if sectionInset != oldValue {
self.invalidateLayout()
}
}
}
open var itemRenderDirection: ETCollectionViewWaterfallLayoutItemRenderDirection = .shortestFirst {
didSet {
if itemRenderDirection != oldValue {
self.invalidateLayout()
}
}
}
open var minimumContentHeight: CGFloat = 0.0
fileprivate weak var delegate: ETCollectionViewDelegateWaterfallLayout! {
return (self.collectionView?.delegate as! ETCollectionViewDelegateWaterfallLayout)
}
fileprivate var columnHeights: [[CGFloat]] = []
fileprivate var sectionItemAttributes: [[UICollectionViewLayoutAttributes]] = []
fileprivate var allItemAttributes: [UICollectionViewLayoutAttributes] = []
fileprivate var headersAttributes: [Int: UICollectionViewLayoutAttributes] = [:]
fileprivate var footersAttributes: [Int: UICollectionViewLayoutAttributes] = [:]
fileprivate var unionRects: [CGRect] = []
fileprivate let unionSize = 20
// MARK: - function
fileprivate func columnCount(forSection section: Int) -> Int {
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:columnCountFor:))) {
return delegate.collectionView!(self.collectionView!, layout: self, columnCountFor: section)
}
return columnCount
}
fileprivate func evaluatedSectionInsetForSection(at index: Int) -> UIEdgeInsets {
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:insetForSectionAt:))) {
return delegate.collectionView!(self.collectionView!, layout: self, insetForSectionAt: index)
}
return sectionInset
}
fileprivate func evaluatedMinimumColumnSpacing(at index: Int) -> CGFloat {
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:minimumColumnSpacingForSectionAt:))) {
return delegate.collectionView!(self.collectionView!, layout: self, minimumColumnSpacingForSectionAt: index)
}
return minimumColumnSpacing
}
fileprivate func evaluatedMinimumInteritemSpaing(at index: Int) -> CGFloat {
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:minimumInteritemSpacingForSectionAt:))) {
return delegate.collectionView!(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAt: index)
}
return minimumInteritemSpacing
}
open func itemWidthInSection(at index: Int) -> CGFloat {
let sectionInset = evaluatedSectionInsetForSection(at: index)
let width = (self.collectionView?.bounds.size.width)! - sectionInset.left - sectionInset.right
let columnCount = CGFloat(self.columnCount(forSection: index))
let columnSpacing = evaluatedMinimumColumnSpacing(at: index)
return (width - (columnCount - 1) * columnSpacing) / columnCount
}
// MARK: - methods to override
override func prepare() {
super.prepare()
headersAttributes.removeAll()
footersAttributes.removeAll()
unionRects.removeAll()
columnHeights.removeAll()
allItemAttributes.removeAll()
sectionItemAttributes.removeAll()
guard self.collectionView?.numberOfSections != 0 else {
return
}
assert(delegate!.conforms(to: ETCollectionViewDelegateWaterfallLayout.self), "UICollectionView's delegate should conform to ETCollectionViewDelegateWaterfallLayout protocol")
assert(columnCount > 0, "WaterfallLayout's columnCount should be greater than 0")
let numberOfsections = (self.collectionView?.numberOfSections)!
// Initialize variables
for index in 0 ..< numberOfsections{
let columnCount = self.columnCount(forSection: index)
let sectionColumnHeights = Array(repeatElement(CGFloat(0), count: columnCount))
self.columnHeights.append(sectionColumnHeights)
}
// Create attributes
var top: CGFloat = 0
for section in 0 ..< numberOfsections {
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
let interitemSpacing = evaluatedMinimumInteritemSpaing(at: section)
let columnSpacing = evaluatedMinimumColumnSpacing(at: section)
let sectionInset = evaluatedSectionInsetForSection(at: section)
let width = (self.collectionView?.bounds.size.width)! - sectionInset.left - sectionInset.right
let columnCount = self.columnCount(forSection: section)
let itemWidth = (width - (CGFloat(columnCount - 1)) * columnSpacing) / CGFloat(columnCount)
/*
* 2. Section header
*/
var headerHeight = self.headerHeight
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:heightForHeaderIn:))) {
headerHeight = delegate.collectionView!(self.collectionView!, layout: self, heightForHeaderIn: section)
}
var headerInset = self.headerInset
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:insetForHeaderIn:))) {
headerInset = delegate.collectionView!(self.collectionView!, layout: self, insetForHeaderIn: section)
}
top += headerInset.top
if headerHeight > 0 {
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: headerInset.left,
y: top,
width: (self.collectionView?.bounds.size.width)!,
height: headerHeight)
self.headersAttributes[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY + headerInset.bottom
}
top += sectionInset.top
for idx in 0 ..< columnCount {
self.columnHeights[section][idx] = top
}
/*
* 3. Section items
*/
let itemCount = (self.collectionView?.numberOfItems(inSection: section))!
var itemAttributes: [UICollectionViewLayoutAttributes] = []
for idx in 0 ..< itemCount {
let indexPath = IndexPath(item: idx, section: section)
let columnIndex = nextColumnIndex(forItem: idx, section: section)
let xOffset = sectionInset.left + (itemWidth + columnSpacing) * CGFloat(columnIndex)
let yOffset = self.columnHeights[section][columnIndex]
let itemSize = delegate.collectionView(self.collectionView!, layout: self, sizeForItemAt: indexPath)
var itemHeight: CGFloat = 0
if itemSize.width > 0 {
itemHeight = itemSize.height * itemWidth / itemSize.width
}
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemWidth, height: itemHeight)
itemAttributes.append(attributes)
self.allItemAttributes.append(attributes)
self.columnHeights[section][columnIndex] = attributes.frame.maxY + interitemSpacing
}
self.sectionItemAttributes.append(itemAttributes)
/*
* 4. Section footer
*/
let columnIndex = longestColumnIndexIn(section: section)
top = self.columnHeights[section][columnIndex] - interitemSpacing + sectionInset.bottom
var footerHeight = self.footerHeight
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:heightForFooterIn:))) {
footerHeight = delegate.collectionView!(self.collectionView!, layout: self, heightForFooterIn: section)
}
var footerInset = self.footerInset
if delegate.responds(to: #selector(ETCollectionViewDelegateWaterfallLayout.collectionView(_:layout:insetForFooterIn:))) {
footerInset = delegate.collectionView!(self.collectionView!, layout: self, insetForFooterIn: section)
}
top += footerInset.top
if footerHeight > 0 {
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: footerInset.left,
y: top,
width: (self.collectionView?.bounds.size.width)! - (footerInset.left + footerInset.right),
height: footerHeight)
self.footersAttributes[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY + footerInset.bottom
}
for idx in 0 ..< columnCount {
self.columnHeights[section][idx] = top
}
}
// Build union rects
var idx = 0
let itemCounts = self.allItemAttributes.count
while idx < itemCounts {
var unionRect = self.allItemAttributes[idx].frame
let rectEndIndex = min(idx + unionSize, itemCounts)
for i in idx+1 ..< rectEndIndex {
unionRect = unionRect.union(self.allItemAttributes[i].frame)
}
idx = rectEndIndex
self.unionRects.append(unionRect)
}
}
override var collectionViewContentSize: CGSize {
let numberOfSections = (self.collectionView?.numberOfSections)!
if numberOfSections == 0 {
return CGSize.zero
}
var contentSize = self.collectionView?.bounds.size
contentSize?.height = (self.columnHeights.last?.first)!
if (contentSize?.height)! < minimumContentHeight {
contentSize?.height = self.minimumContentHeight
}
return contentSize!
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard indexPath.section < self.sectionItemAttributes.count
&& indexPath.item < self.sectionItemAttributes[indexPath.section].count else {
return nil
}
return self.sectionItemAttributes[indexPath.section][indexPath.item]
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if elementKind == UICollectionView.elementKindSectionHeader {
return self.headersAttributes[indexPath.section]
}
if elementKind == UICollectionView.elementKindSectionFooter {
return self.footersAttributes[indexPath.section]
}
return nil
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var begin = 0, end = 0
var attrs: [UICollectionViewLayoutAttributes] = []
for i in 0 ..< self.unionRects.count {
if rect.intersects(self.unionRects[i]) {
begin = i * unionSize
break
}
}
var idx = self.unionRects.count - 1
while idx >= 0 {
if rect.intersects(self.unionRects[idx]) {
end = min((idx+1) * unionSize, self.allItemAttributes.count)
break
}
idx -= 1
}
for i in begin ..< end {
let attr = self.allItemAttributes[i]
if rect.intersects(attr.frame) {
attrs.append(attr)
}
}
return attrs
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let oldBounds = (self.collectionView?.bounds)!
if newBounds.width != oldBounds.width {
return true
}
return false
}
// MARK: - Find the shortest column
fileprivate func shortestColumnIndexIn(section: Int) -> Int {
var index = 0
var shortestHeight = CGFloat(Float.greatestFiniteMagnitude)
for (idx, height) in self.columnHeights[section].enumerated() {
if height < shortestHeight {
shortestHeight = height
index = idx
}
}
return index
}
/**
* Find the longest column.
*
* @return index for the longest column
*/
fileprivate func longestColumnIndexIn(section: Int) -> Int {
var index = 0
var longestHeight: CGFloat = 0
for (idx, height) in self.columnHeights[section].enumerated() {
if height > longestHeight {
longestHeight = height
index = idx
}
}
return index
}
/**
* Find the index for the next column.
*
* @return index for the next column
*/
fileprivate func nextColumnIndex(forItem item: Int, section: Int) -> Int {
var index = 0
let columnCount = self.columnCount(forSection: section)
switch itemRenderDirection {
case .shortestFirst:
index = shortestColumnIndexIn(section: section)
case .leftToRight:
index = item % columnCount
case .rightToLeft:
index = (columnCount - 1) - (item % columnCount)
}
return index
}
}
|
mit
|
f0ce56f41bea375a8f7b59f45b17959c
| 37.329787 | 182 | 0.604219 | 5.86999 | false | false | false | false |
P0ed/FireTek
|
Source/SpaceEngine/Systems/LevelSystem.swift
|
1
|
1378
|
import Fx
import PowerCore
struct LevelSystem {
struct State {
let player: Entity
}
private let mutableState: MutableProperty<State>
private let world: World
private let level: SpaceLevel
let state: Property<State>
init(world: World, level: SpaceLevel) {
self.world = world
self.level = level
mutableState = MutableProperty(.initialState(world: world, level: level))
state = mutableState.map(id)
}
mutating func update() {
if !world.entityManager.isAlive(state.value.player) {
/// Game over
}
}
}
extension LevelSystem.State {
static func initialState(world: World, level: SpaceLevel) -> LevelSystem.State {
let player = UnitFactory.createShip(world: world, position: level.spawnPosition, team: .blue)
// UnitFactory.createAIPlayer(world: world, position: Point(x: 220, y: 40))
// UnitFactory.createAIPlayer(world: world, position: Point(x: 40, y: 220))
//
// let buildings: [Point] = [
// Point(x: 140, y: 120),
// Point(x: 220, y: 140),
// Point(x: 280, y: 120),
// Point(x: 360, y: 140),
// Point(x: 140, y: 320),
// Point(x: 220, y: 340),
// Point(x: 280, y: 320),
// Point(x: 360, y: 340)
// ]
//
// buildings.forEach {
// UnitFactory.createBuilding(world: world, position: $0)
// }
StarSystemFactory.createSystem(world: world, data: level.starSystem)
return LevelSystem.State(
player: player
)
}
}
|
mit
|
4883252a5b4837ec2715234f2f711e67
| 22.758621 | 95 | 0.671988 | 2.919492 | false | false | false | false |
Epaus/SimpleParseTimelineAndMenu
|
SimpleParseTimelineAndMenu/TimelineCell.swift
|
1
|
5463
|
//////
// TimelineCell.swift
// SimpleParseTimelineAndMenu
//
// Created by Estelle Paus on 12/1/14.
// Copyright (c) 2014 Estelle Paus. All rights reserved.
import Foundation
import UIKit
class TimelineCell : UITableViewCell {
var leftMargin : CGFloat!
var topMargin : CGFloat!
var rightMargin : CGFloat!
var width : CGFloat!
var profileImageView: UIImageView!
var nameLabel: UILabel!
var dateLabel: UILabel!
var timeLabel: UILabel!
var titleLabel: UILabel!
var postLabel: UILabel!
override func awakeFromNib() {
self.leftMargin = self.contentView.layer.frame.width * 0.05
self.topMargin = self.contentView.layer.frame.height * 0.05
self.rightMargin = self.contentView.layer.frame.width * 0.95
self.width = self.contentView.layer.frame.width
self.contentView.frame = self.bounds
let layer: CALayer = self.layer;
layer.masksToBounds = false
layer.cornerRadius = 5.0
layer.borderWidth = 0.5
layer.borderColor = UIColor.blackColor().CGColor //(white: 0.8, alpha: 1.0).CGColor
setupProfileImageView()
setupNameLabel()
setupDateLabel()
setupTimeLabel()
setupTitleLabel()
setupPostLabel()
}
override func layoutSubviews() {
super.layoutSubviews()
}
func setupProfileImageView()
{
self.profileImageView = UIImageView()
var profileImageViewX = self.leftMargin
var profileImageViewSideLen = self.contentView.frame.width * 0.20
self.profileImageView.frame = CGRectMake(profileImageViewX, self.topMargin, profileImageViewSideLen, profileImageViewSideLen)
self.profileImageView.layer.cornerRadius = 5.0
self.profileImageView.clipsToBounds = true
self.contentView.addSubview(self.profileImageView)
}
func setupNameLabel()
{
self.nameLabel = UILabel()
var nameLabelX = self.contentView.frame.width * 0.30
self.nameLabel.frame = CGRectMake(nameLabelX, self.topMargin, self.contentView.frame.width * 0.25, self.contentView.frame.height * 0.10)
self.nameLabel.backgroundColor = UIColor.clearColor()
self.nameLabel.textColor = UIColor.blackColor()
self.nameLabel.textAlignment = NSTextAlignment.Left
self.nameLabel.font = UIFont(name: "Avenir-Book", size: 20.0)!
self.contentView.addSubview(self.nameLabel)
}
func setupDateLabel()
{
self.dateLabel = UILabel()
var dateLabelLength = self.contentView.frame.width * 0.32
var dateLabelX = self.contentView.frame.width - dateLabelLength * 0.34
self.dateLabel.frame = CGRectMake(dateLabelX,self.topMargin,dateLabelLength, self.contentView.frame.height * 0.10)
self.dateLabel.backgroundColor = UIColor.clearColor()
self.dateLabel.textColor = UIColor.grayColor()
self.dateLabel.textAlignment = NSTextAlignment.Right
self.dateLabel.font = UIFont(name: "Avenir-Book", size: 16.0)!
self.contentView.addSubview(self.dateLabel)
}
func setupTimeLabel()
{
self.timeLabel = UILabel()
var timeLabelLength = self.contentView.frame.width * 0.32
var timeLabelX = self.contentView.frame.width - timeLabelLength * 0.34
self.timeLabel.frame = CGRectMake(timeLabelX,4*self.topMargin,timeLabelLength, self.contentView.frame.height * 0.10)
self.timeLabel.backgroundColor = UIColor.clearColor()
self.timeLabel.textColor = UIColor.grayColor()
self.timeLabel.textAlignment = NSTextAlignment.Right
self.timeLabel.font = UIFont(name: "Avenir-Book", size: 16.0)!
self.contentView.addSubview(self.timeLabel)
}
func setupTitleLabel()
{
self.titleLabel = UILabel()
var titleLabelLength = self.contentView.frame.width * 0.50
var titleLabelX = self.contentView.frame.width * 0.30
self.titleLabel.frame = CGRectMake(titleLabelX,4*self.topMargin,titleLabelLength, self.contentView.frame.height * 0.20)
self.titleLabel.backgroundColor = UIColor.clearColor()
self.titleLabel.textColor = UIColor.blackColor()
self.titleLabel.textAlignment = NSTextAlignment.Left
self.titleLabel.font = UIFont(name: "Avenir-Heavy", size: 21.0)!
self.contentView.addSubview(self.titleLabel)
}
func setupPostLabel()
{
self.postLabel = UILabel()
var postLabelX = self.contentView.frame.width * 0.05
var postLabelLength = self.contentView.frame.width * 1.5
self.postLabel.backgroundColor = UIColor.clearColor()
self.postLabel.textColor = UIColor.blackColor()
self.postLabel.textAlignment = NSTextAlignment.Left
self.postLabel.font = UIFont(name: "Avenir-Book", size: 20.0)!
self.postLabel.lineBreakMode = .ByWordWrapping;
self.postLabel.numberOfLines = 0 // limits to 5 lines; use 0 for unlimited.
self.postLabel.preferredMaxLayoutWidth = self.contentView.frame.size.width;
self.postLabel.frame = CGRectMake(postLabelX, self.contentView.frame.height * 0.45, CGRectGetWidth(self.contentView.bounds), CGRectGetHeight(self.contentView.bounds))
self.contentView.addSubview(self.postLabel)
}
}
|
gpl-3.0
|
8a8cd7037fe1873e597856511099b7f6
| 35.426667 | 174 | 0.665568 | 4.556297 | false | false | false | false |
codepgq/LearningSwift
|
ImageScrollEffect/ImageScrollEffect/ViewController.swift
|
1
|
3432
|
//
// ViewController.swift
// ImageScrollEffect
//
// Created by ios on 16/9/13.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class ViewController: UIViewController , UIScrollViewDelegate{
@IBOutlet weak var scrollView: UIScrollView!
var top : CGFloat = 0
var imageView : UIImageView = {
let iv = UIImageView(image: UIImage(named: "item"))
iv.sizeToFit()
return iv
}()
var showImageView: UIImageView = {
let iv = UIImageView(image: UIImage(named: "item"))
iv.userInteractionEnabled = true
return iv
}()
@objc private func showScrollView(){
UIView.animateWithDuration(0.5, animations: {
self.showImageView.frame = self.scrollView.frame
self.showImageView.frame.size.width = self.scrollView.contentSize.width
}) { (completion) in
self.scrollView.hidden = false
self.showImageView.removeFromSuperview()
self.top = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.addSubview(imageView)
scrollView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
scrollView.zoomScale = scrollView.minimumZoomScale
scrollView.delegate = self
setZoomScaleFor(scrollView.frame.size)
let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.showScrollView))
showImageView.addGestureRecognizer(tap)
}
private func setZoomScaleFor(srollViewSize: CGSize) {
let imageSize = imageView.bounds.size
let widthScale = srollViewSize.width / imageSize.width
let heightScale = srollViewSize.height / imageSize.height
let minimunScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minimunScale
scrollView.maximumZoomScale = 3.0
}
private func recenterImage() {
let scrollViewSize = scrollView.bounds.size
let imageViewSize = imageView.frame.size
let horizontalSpace = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2.0 : 0
let verticalSpace = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.width) / 2.0 :0
scrollView.contentInset = UIEdgeInsetsMake(verticalSpace, horizontalSpace, verticalSpace, horizontalSpace)
}
func scrollViewDidZoom(scrollView: UIScrollView) {
top = scrollView.contentInset.top
self.recenterImage()
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if top >= 1 {
scrollView.hidden = true
showImageView.layoutMargins = scrollView.contentInset
self.view.addSubview(showImageView)
UIView.animateWithDuration(0.5, animations: {
self.showImageView.frame = CGRect(x: 10, y: 20, width: 100, height: 100)
})
}
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
if top > 1 {
return nil
}
return self.imageView
}
}
|
apache-2.0
|
3c57d25fce0b7b511b2dd90328082d61
| 29.078947 | 129 | 0.614465 | 5.408517 | false | false | false | false |
zhaobin19918183/zhaobinCode
|
FamilyShop/FamilyShop/EndViewController/EndTableViewCell.swift
|
1
|
2752
|
//
// EndTableViewCell.swift
// NBALive
//
// Created by Zhao.bin on 16/10/12.
// Copyright © 2016年 Zhao.bin. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
class EndTableViewCell: UITableViewCell {
@IBOutlet weak var _teamName1: UILabel!
@IBOutlet weak var _teamNumber: UILabel!
@IBOutlet weak var _teamName2: UILabel!
@IBOutlet weak var _teamActionTime: UILabel!
@IBOutlet weak var _teamImageView1: UIImageView!
@IBOutlet weak var _teamImageView2: UIImageView!
@IBOutlet weak var dataStatisticsButton: UIButton!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var dateTitleLabel: UILabel!
@IBOutlet weak var videoButton: UIButton!
var navigationController:UINavigationController!
var dataString:String!
var videoString:String!
override func awakeFromNib()
{
super.awakeFromNib()
// Initialization code
}
func endLiveAction(dic:[String:AnyObject])
{
dateLabel.text = dic["title"] as? String
}
func endLiveDicAction(dic:[String:AnyObject] ,tableview:UITableView)
{
_teamName1.text = dic["player1"] as? String
_teamName2.text = dic["player2"] as? String
_teamNumber.text = dic["score"] as? String
_teamActionTime.text = dic["time"] as? String
_teamImageView1.tag = 1
_teamImageView2.tag = 2
teamImagelogo(url: dic["player2logo"] as! String,imageview:_teamImageView2)
teamImagelogo(url: dic["player1logobig"] as! String,imageview:_teamImageView1)
self.dataString = dic["link1url"] as! String
}
@IBAction func dataAction(_ sender: UIButton)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let targetVC0 = storyboard.instantiateViewController(withIdentifier: "EndWebViewController") as! EndWebViewController
targetVC0.uslString = self.dataString
self.navigationController?.pushViewController(targetVC0, animated:true)
}
func teamImagelogo(url:String,imageview:UIImageView)
{
Alamofire.request(url).responseImage { (response) in
if imageview.tag == 1
{
if let image = response.result.value {
self._teamImageView1.image = image
}
}
else
{
if let image = response.result.value {
self._teamImageView2.image = image
}
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
gpl-3.0
|
e26549e13ebe478efa0eaa519b04f607
| 29.88764 | 125 | 0.628956 | 4.551325 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-399/examples/LendingLibrary/LendingLibrary/Source/Model/LentItem.swift
|
1
|
1823
|
//
// LentItem.swift
// LendingLibrary
//
import CoreData
import UIKit
import UserNotifications
public class LentItem: NSManagedObject {
// MARK: NSManagedObject
public override func didSave() {
super.didSave()
// Make local constants so the completion handler closures below don't capture the CoreData entity
let identifier = objectID.uriRepresentation().absoluteString
let isDeleted = self.isDeleted
let notify = self.notify!
let dateToReturn = self.dateToReturn!
let title = "Borrowed Item Reminder"
let body = "\(borrower!) should return \(name!) soon."
// Only handle notifications when dealing with objects in the viewContext
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
if LendingLibraryService.shared.isInViewContext(self) {
if !isDeleted && notify.boolValue && dateToReturn.earlierDate(Date()) != dateToReturn as Date {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: dateToReturn as Date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
else {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
if isDeleted || !notify.boolValue {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])
}
}
}
}
}
}
}
|
gpl-3.0
|
3beaced50038b234376b931ef7121715
| 32.759259 | 125 | 0.735601 | 4.5575 | false | false | false | false |
michelleran/FicFeed
|
iOS/FicFeed/MyFeedController.swift
|
1
|
1615
|
//
// MyFeedController.swift
// FicFeed
//
// Created by Michelle Ran on 7/27/16.
// Copyright © 2016 Michelle Ran LLC. All rights reserved.
//
import Foundation
import UIKit
class MyFeedController: UITableViewController {
var subscribed: [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "My Feed"
}
override func viewWillAppear(animated: Bool) {
Cloud.getSubscribedTags { (subscribed: [Int]) in
self.subscribed = subscribed
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return subscribed.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyFeedCell")!
let id = subscribed[indexPath.row]
if let index = Info.IDS.indexOf(id) {
cell.textLabel!.text = Info.TAGS[index]
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let feed = segue.destinationViewController as? FeedController {
let index = tableView.indexPathForSelectedRow!.row
feed.feedId = subscribed[index]
if let i = Info.IDS.indexOf(subscribed[index]) {
feed.feedTitle = Info.TAGS[i]
}
feed.url = NSURL(string: "http://archiveofourown.org/tags/\(subscribed[index])/feed.atom")
}
}
}
|
mit
|
122c588270d8f6d9fb71b586413428ab
| 31.28 | 118 | 0.635688 | 4.651297 | false | false | false | false |
amieka/FlickStream
|
FlickStream/FlickrAPIUrlBuilder.swift
|
1
|
1816
|
//
// FlickrAPIUrlBuilder.swift
// FlickStream
//
// Created by Arunoday Sarkar on 6/4/16.
// Copyright © 2016 Sark Software LLC. All rights reserved.
//
import Foundation
func urlBuilder(urlParams: [String:AnyObject]) -> NSURL {
let urlComponents = NSURLComponents()
urlComponents.scheme = FlickrAPIConstants.API_SCHEME
urlComponents.host = FlickrAPIConstants.API_HOST
urlComponents.path = FlickrAPIConstants.API_PATH
urlComponents.queryItems = [NSURLQueryItem]()
for (key, value) in urlParams {
let queryItem = NSURLQueryItem(name: key, value: "\(value)")
urlComponents.queryItems!.append(queryItem)
}
return urlComponents.URL!
}
func staticPhotoUrlFromParams(farm_id:NSNumber, server_id:String, id:String, secret:String, type:String) -> NSURL {
// https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
// http://farm{icon-farm}.staticflickr.com/{icon-server}/buddyicons/{nsid}.jpg
let staticPhotoUrlComponents = NSURLComponents()
staticPhotoUrlComponents.scheme = FlickrAPIConstants.API_SCHEME
staticPhotoUrlComponents.host = String(format: "farm%@.%@", farm_id, FlickrAPIConstants.STATIC_FLICKR)
staticPhotoUrlComponents.path = String(format: "/%@/%@_%@_%@.jpg", server_id, id, secret, type)
return staticPhotoUrlComponents.URL!
}
func staticProfilePhotoUrlFromParams(icon_farm:String, icon_server:String, id:String) -> NSURL {
// http://farm{icon-farm}.staticflickr.com/{icon-server}/buddyicons/{nsid}.jpg
let staticPhotoUrlComponents = NSURLComponents()
staticPhotoUrlComponents.scheme = FlickrAPIConstants.API_SCHEME
staticPhotoUrlComponents.host = String(format: "farm%@.%@", icon_farm, FlickrAPIConstants.STATIC_FLICKR)
staticPhotoUrlComponents.path = String(format: "/%@/buddyicons/%@.jpg", icon_server, id)
return staticPhotoUrlComponents.URL!
}
|
mit
|
53284b607fe97c68695bbb56b472c346
| 41.209302 | 115 | 0.762534 | 3.503861 | false | false | false | false |
HassanEskandari/Eureka
|
Source/Core/Cell.swift
|
1
|
5210
|
// Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Base class for the Eureka cells
open class BaseCell: UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Enabled and Disabled Colors
public var enabledColor: UIColor = .black
public var disabledColor: UIColor = .gray
public var fieldFont : UIFont {
get {
return textLabel?.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
}
set {
textLabel?.font = newValue
}
}
/// Block that returns the height for this cell.
public var height: (() -> CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder: AnyObject? = self
while responder != nil {
if let formVC = responder as? FormViewController {
return formVC
}
responder = responder?.next
}
return nil
}
open func setup() {}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T>: BaseCell, TypedCellType where T: Equatable {
public typealias Value = T
/// The row associated to this cell
public weak var row: RowOf<T>!
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row) {
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup() {
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update() {
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? self.disabledColor : self.enabledColor
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
return false
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
/// The untyped row associated to this cell.
public override var baseRow: BaseRow! { return row }
}
|
mit
|
033aa1ed597741a9789043ce00ea7a38
| 30.011905 | 126 | 0.660845 | 5.04845 | false | false | false | false |
dictav/SwiftLint
|
Source/SwiftLintFramework/Rules/VariableNameMinLengthRule.swift
|
1
|
1880
|
//
// VariableNameMinLengthRule.swift
// SwiftLint
//
// Created by Mickaël Morier on 04/11/2015.
// Copyright © 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct VariableNameMinLengthRule: ASTRule, ParameterizedRule {
public init() {
self.init(parameters: [
RuleParameter(severity: .Warning, value: 3),
RuleParameter(severity: .Error, value: 2)
])
}
public init(parameters: [RuleParameter<Int>]) {
self.parameters = parameters
}
public let parameters: [RuleParameter<Int>]
public static let description = RuleDescription(
identifier: "variable_name_min_length",
name: "Variable Name Min Length Rule",
description: "Variable name should not be too short.",
nonTriggeringExamples: [
"let myLet = 0",
"var myVar = 0",
"private let _myLet = 0"
],
triggeringExamples: [
"let i = 0",
"var id = 0",
"private let _i = 0"
]
)
public func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
return file.validateVariableName(dictionary, kind: kind).map { name, offset in
let charCount = name.characters.count
for parameter in self.parameters.reverse() where charCount < parameter.value {
return [StyleViolation(ruleDescription: self.dynamicType.description,
severity: parameter.severity,
location: Location(file: file, offset: offset),
reason: "Variable name should be \(parameter.value) characters " +
"or more: currently \(charCount) characters")]
}
return []
} ?? []
}
}
|
mit
|
b18f23433fe9dd8768a107f4f1b2f0a7
| 32.535714 | 90 | 0.5836 | 4.890625 | false | false | false | false |
buyiyang/iosstar
|
iOSStar/AppAPI/NewsAPI/NewsSocketAPI.swift
|
4
|
1668
|
//
// NewsSocketAPI.swift
// iOSStar
//
// Created by J-bb on 17/5/11.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class NewsSocketAPI: BaseSocketAPI, NewsApi {
func requestNewsList(startnum:Int, endnum:Int, complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.name : "1",
SocketConst.Key.starCode : "1",
SocketConst.Key.startnum : startnum,
SocketConst.Key.endnum : endnum,
SocketConst.Key.all : 1]
let packet = SocketDataPacket(opcode: .newsInfo, dict: parameters as [String : AnyObject], type: .news)
startModelsRequest(packet, listName: "list", modelClass: NewsModel.self, complete: complete, error: error)
}
func requestBannerList(complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.starCode : "1", SocketConst.Key.all : 1]
let packet = SocketDataPacket(opcode: .banners, dict: parameters as [String : AnyObject], type: .news)
startModelsRequest(packet, listName: "list", modelClass: BannerModel.self, complete: complete, error: error)
}
func requestStarInfo(code:String,complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.starCode : code]
let packet = SocketDataPacket(opcode: .starInfo, parameters: parameters)
startModelRequest(packet, modelClass: BannerDetaiStarModel.self, complete: complete, error: error)
}
}
|
gpl-3.0
|
99d43b46e86a8bd2c579879b8add0f87
| 42.815789 | 116 | 0.628228 | 4.291237 | false | false | false | false |
KyoheiG3/ProtobufExample
|
ProtobufClient/ProtobufClient/ViewController.swift
|
1
|
5677
|
//
// ViewController.swift
// ProtobufClient
//
// Created by Kyohei Ito on 2016/11/19.
// Copyright © 2016年 Kyohei Ito. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SwiftProtobuf
import Protobuf
private let stabJSON = "{\"id\":\"20\",\"name\":\"Swift\",\"books\":[{\"id\":\"10\",\"title\":\"Welcome to Swift\",\"author\":\"Apple Inc.\"}],\"keys\":{\"route\":\"66\"}}"
class TableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var acceptLabel: UILabel!
@IBOutlet weak var pathLabel: UILabel!
@IBOutlet weak var dataLabel: UILabel!
@IBOutlet weak var byteLabel: UILabel!
fileprivate let requests = [
RequestInfo(api: .go, type: .json, path: "/"),
RequestInfo(api: .go, type: .protobuf, path: "/"),
RequestInfo(api: .go, type: .protobuf, path: "/stab"),
RequestInfo(api: .swift, type: .json, path: "/"),
RequestInfo(api: .swift, type: .protobuf, path: "/"),
RequestInfo(api: .swift, type: .json, path: "/protobuf"),
RequestInfo(api: .swift, type: .protobuf, path: "/json"),
RequestInfo(api: .swift, type: .protobuf, path: "/stab"),
]
fileprivate let disposeBag = DisposeBag()
func data<T>(request: URLRequest) -> Observable<T> {
guard request.url?.path != "/stab" else {
self.typeLabel.text = "-"
self.byteLabel.text = "-"
self.typeLabel.text = "-"
// return stab data.
return .just(try! MyLibrary(json: stabJSON) as! T)
}
return URLSession.shared.rx.response(request: request)
.observeOn(MainScheduler.instance)
.map { [unowned self] (response, data) -> T in
if 200 ..< 300 ~= response.statusCode {
let contentType = response.allHeaderFields["Content-Type"] as? String
let accept = request.allHTTPHeaderFields?["Accept"]
self.byteLabel.text = "\(data)"
self.typeLabel.text = contentType
// This examples return serialized json string if json string needed. also return deserialized protobuf object if protobuf needed.
if let type = contentType, type == "application/protobuf" {
let library = try MyLibrary(protobuf: data)
if accept == "application/json" {
return try library.serializeJSON() as! T
} else {
return library as! T
}
} else {
let json = String(bytes: data, encoding: .utf8)
if accept == "application/protobuf" {
return try MyLibrary(json: json!) as! T
} else {
return json as! T
}
}
}
else {
throw RxCocoaURLError.httpRequestFailed(response: response, data: data)
}
}
.do(onError: { [unowned self] _ in
self.byteLabel.text = "-"
self.typeLabel.text = "-"
})
.catchError { error in
.just(error as! T)
}
}
func getRequest(url: String) -> URLRequest {
let url = URL(string: url)!
pathLabel.text = ":\(url.port!)\(url.path)"
var request = URLRequest(url: url)
request.httpMethod = "GET"
return request
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let info = requests[indexPath.row]
cell.textLabel?.text = "\(info.api.port)\(info.path)"
cell.detailTextLabel?.text = info.type.description
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let info = requests[indexPath.row]
acceptLabel.text = info.type.description
var request = getRequest(url: info.url)
request.setValue(info.type.description, forHTTPHeaderField: "Accept")
data(request: request)
.single()
.map { (data: CustomDebugStringConvertible) in data.debugDescription }
.bindTo(dataLabel.rx.text)
.addDisposableTo(disposeBag)
}
}
|
mit
|
0f8c9487ce1da58d7c3844fc08ee7276
| 36.328947 | 172 | 0.547585 | 4.994718 | false | false | false | false |
mohssenfathi/MTLImage
|
MTLImage/Sources/Core/MTLLib.swift
|
1
|
902
|
//
// MTLLibrary.swift
// Pods
//
// Created by Mohssen Fathi on 9/12/16.
//
//
import Metal
public
class MTLLib: NSObject {
static let sharedLib = MTLLib()
var library: MTLLibrary! = nil
// TODO: Make throw
class func sharedLibrary(device: MTLDevice) -> MTLLibrary? {
if MTLLib.sharedLib.library == nil {
let bundle = Bundle(for: MTLImage.classForCoder())
guard let path = bundle.path(forResource: "default", ofType: "metallib") else {
print("Cannot find metallib")
return nil
}
do {
MTLLib.sharedLib.library = try device.makeLibrary(filepath: path)
}
catch {
print("Error creating metallib")
return nil
}
}
return MTLLib.sharedLib.library
}
}
|
mit
|
63b6d02dacc121d8aac53cea004b9719
| 21.55 | 91 | 0.521064 | 4.421569 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Systems/Autocomplete/AutocompleteController.swift
|
1
|
3102
|
//
// AutocompleteController.swift
// Freetime
//
// Created by Ryan Nystrom on 1/1/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import UIKit
import MessageViewController
final class AutocompleteController: NSObject,
UITableViewDataSource,
UITableViewDelegate,
IssueCommentAutocompleteDelegate,
MessageAutocompleteControllerDelegate {
let messageAutocompleteController: MessageAutocompleteController
let autocomplete: IssueCommentAutocomplete
init(
messageAutocompleteController: MessageAutocompleteController,
autocomplete: IssueCommentAutocomplete
) {
self.messageAutocompleteController = messageAutocompleteController
self.autocomplete = autocomplete
super.init()
for prefix in autocomplete.prefixes {
messageAutocompleteController.register(prefix: prefix)
}
messageAutocompleteController.delegate = self
let tableView = messageAutocompleteController.tableView
tableView.delegate = self
tableView.dataSource = self
autocomplete.configure(tableView: tableView, delegate: self)
}
// MARK: MessageAutocompleteControllerDelegate
func didFind(controller: MessageAutocompleteController, prefix: String, word: String) {
autocomplete.didChange(tableView: controller.tableView, prefix: prefix, word: word)
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocomplete.resultCount(prefix: messageAutocompleteController.selection?.prefix)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return autocomplete.cell(
tableView: tableView,
prefix: messageAutocompleteController.selection?.prefix,
indexPath: indexPath
)
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let accepted = autocomplete.accept(
prefix: messageAutocompleteController.selection?.prefix,
indexPath: indexPath
) {
messageAutocompleteController.accept(autocomplete: accepted, keepPrefix: false)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return autocomplete.cellHeight
}
// MARK: IssueCommentAutocompleteDelegate
func didChangeStore(autocomplete: IssueCommentAutocomplete) {
for prefix in autocomplete.prefixes {
messageAutocompleteController.register(prefix: prefix)
if let attributes = autocomplete.highlightAttributes(prefix: prefix) {
messageAutocompleteController.registerAutocomplete(prefix: prefix, attributes: attributes)
}
}
messageAutocompleteController.tableView.reloadData()
}
func didFinish(autocomplete: IssueCommentAutocomplete, hasResults: Bool) {
messageAutocompleteController.show(hasResults)
}
}
|
mit
|
4735ac69e3ad3165a98e701bbbe7e931
| 31.989362 | 106 | 0.712996 | 5.828947 | false | false | false | false |
katsumeshi/PhotoInfo
|
PhotoInfo/SettingViewController.swift
|
1
|
5515
|
//
// SettingViewController.swift
// photoinfo
//
// Created by Yuki Matsushita on 12/19/15.
// Copyright © 2015 Yuki Matsushita. All rights reserved.
//
import UIKit
import Social
enum SettingType {
case Review
case RemoveAdvertisement
case Facebook
case TwitterShare
case FacebookShare
}
class SettingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView?
var titles = [[SettingType.Review:"Review the app".toGrobal()],
[SettingType.RemoveAdvertisement:"Remove advertisement".toGrobal()],
[SettingType.Facebook:"Facebook fun site".toGrobal()],
[SettingType.TwitterShare:"Share the app via Twitter".toGrobal()],
[SettingType.FacebookShare:"Share the app via Facebook".toGrobal()]]
let purchaseManager = PurchaseManager()
override func viewDidLoad() {
super.viewDidLoad()
self.reloadTitles()
self.tableView?.contentInset.bottom = PurchaseManager.purchased ? 0 : 50
purchaseManager.purchaseClouser = reloadTitles
purchaseManager.restoreClosure = { () -> Void in
self.reloadTitles()
let alertController = UIAlertController(title:"Confirmation".toGrobal(),
message: "Restored your bought item".toGrobal(), preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Close".toGrobal(), style: UIAlertActionStyle.Default, handler:
nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion:nil)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// if !(self.navigationController!.viewControllers.contains(self)) {
// self.tableView?.removeFromSuperview()
// }
}
func reloadTitles() {
if PurchaseManager.purchased {
titles.removeAtIndex(1)
self.tableView!.reloadData()
for var i = 0; i < self.tabBarController!.viewControllers!.count; i++ {
let naviViewController = self.tabBarController!.viewControllers![i] as! UINavigationController
for var j = 0; j < naviViewController.viewControllers.count; j++ {
// let viewController = naviViewController.viewControllers[j] as! UIViewController
// viewController.view.purchasedRemoveAds()
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch (titles[indexPath.item].keys.first!) {
case SettingType.Review:
UIApplication.sharedApplication().openURL(Review.reviewUrl)
case SettingType.RemoveAdvertisement:
let alertController = UIAlertController(title:"Remove advertisement".toGrobal(), message: "", preferredStyle: .Alert)
let purchaseAction = UIAlertAction(title: "Purchase".toGrobal(), style: .Default) { _ in
self.purchaseManager.buy()
}
let restoreAction = UIAlertAction(title: "Restore".toGrobal(), style: .Default) { _ in
self.purchaseManager.restore()
}
let cancelAction = UIAlertAction(title: "Close".toGrobal(), style: .Default, handler: nil)
alertController.addAction(purchaseAction)
alertController.addAction(restoreAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion:nil)
case SettingType.Facebook:
let fbURL = NSURL(string: "fb://profile/472766872878196")
let httpURL = NSURL(string: "https://www.facebook.com/photoinfoapp")
if UIApplication.sharedApplication().canOpenURL(fbURL!) {
UIApplication.sharedApplication().openURL(fbURL!)
} else {
UIApplication.sharedApplication().openURL(httpURL!)
}
case SettingType.TwitterShare:
self.presentViewController(SLComposeViewController.getTwitterControllerWithText(), animated: true, completion: nil)
case SettingType.FacebookShare:
self.presentViewController(SLComposeViewController.getFacebookControllerWithText(), animated: true, completion: nil)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SettingTableViewCell", forIndexPath: indexPath)
cell.textLabel?.text = titles[indexPath.item].values.first
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.titles.count
}
}
extension SLComposeViewController {
static func getTwitterControllerWithText() -> SLComposeViewController {
let twitterController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterController.setInitialText("the recommendation app!\n\"Photo Info! - 写真情報、撮影位置確認\"\n#PhotoInfo!\nhttps://goo.gl/9TrJNf".toGrobal())
return twitterController
}
static func getFacebookControllerWithText() -> SLComposeViewController {
let facebookController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
facebookController.setInitialText("the recommendation app!\n\"Photo Info! - 写真情報、撮影位置確認\"\n#PhotoInfo!\nhttps://goo.gl/9TrJNf".toGrobal())
return facebookController
}
}
|
mit
|
1da653bea02ca99e532b63afaf87de44
| 35.466667 | 142 | 0.710055 | 4.910233 | false | false | false | false |
SquidKit/SquidKit
|
SquidKit/DismissibleViewController.swift
|
1
|
1258
|
//
// DismissibleViewController.swift
// SquidKit
//
// Created by Mike Leavy on 8/15/14.
// Copyright © 2017-2019 Squid Store, LLC. All rights reserved.
//
import UIKit
open class DismissibleViewController: UIViewController {
@IBAction open func dismissOrPop() {
if self.parent != nil {
self.pop()
}
else if self.presentingViewController != nil {
self.dismissModal()
}
else {
self.pop()
}
}
fileprivate func pop() {
if self.navigationController != nil &&
self.navigationController!.viewControllers[0] as NSObject == self &&
self.navigationController!.presentingViewController != nil {
self.navigationController!.presentingViewController!.dismiss(animated: true, completion: nil)
}
else if self.navigationController != nil {
self.navigationController!.popViewController(animated: true)
}
}
fileprivate func dismissModal() {
if self.navigationController != nil {
self.navigationController!.dismiss(animated: true, completion: nil)
}
else {
self.dismiss(animated: true, completion: nil)
}
}
}
|
mit
|
fc75b7118145538f4302b3f1bcbc223d
| 26.933333 | 109 | 0.600636 | 4.968379 | false | false | false | false |
d3QUone/Calculator
|
Calculator/CalculatorBrain.swift
|
1
|
3237
|
//
// CalculatorBrain.swift
// Calculator
//
// Created by Владимир on 06.02.15.
// Copyright (c) 2015 Kasatkin. All rights reserved.
//
import Foundation
class CalculatorBrain {
private enum Op: Printable {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double, Double) -> Double)
//case Constant(String, Double) // save M_PI here
var description: String {
get {
switch self {
case .Operand(let operand): return "\(operand)"
case .UnaryOperation(let symbol, _): return symbol
case .BinaryOperation(let symbol, _): return symbol
//case .Constant(let symbol, _): return symbol
}
}
}
}
private var opStack = [Op]()
private var knownOps = [String: Op]()
init(){
func learnOp(op: Op){
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", *))
learnOp(Op.BinaryOperation("÷") { $1 / $0 })
learnOp(Op.BinaryOperation("+", +))
learnOp(Op.BinaryOperation("−") { $1 - $0 })
learnOp(Op.BinaryOperation("^", pow))
learnOp(Op.UnaryOperation("√", sqrt))
learnOp(Op.UnaryOperation("sin", sin))
learnOp(Op.UnaryOperation("cos", cos))
learnOp(Op.UnaryOperation("tan", tan))
learnOp(Op.UnaryOperation("+/−") { -1*$0 })
}
private func evaulate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand): return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaulate = evaulate(remainingOps)
if let operand = operandEvaulate.result {
return (operation(operand), operandEvaulate.remainingOps)
}
case .BinaryOperation(_, let operation):
let op1Eval = evaulate(remainingOps)
if let op1result = op1Eval.result {
let op2Eval = evaulate(op1Eval.remainingOps)
if let op2result = op2Eval.result {
return (operation(op1result, op2result), op2Eval.remainingOps)
}
}
}
}
return (nil, ops)
}
func evaulate() -> Double? {
let (result, remainder) = evaulate(opStack)
return result
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
println("pushed operand \(operand)")
return evaulate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol]{
opStack.append(operation)
}
println("pushed operation \(symbol)")
return evaulate()
}
func clearStack() {
opStack.removeAll(keepCapacity: false)
println("opStack clear")
}
}
|
mit
|
ab43162bfc8e1615eeba811e76d3104e
| 32.216495 | 90 | 0.529339 | 4.467406 | false | false | false | false |
reswifq/pool
|
Sources/Pool/Pool.swift
|
1
|
3488
|
//
// Pool.swift
// Reswifq
//
// Created by Valerio Mazzeo on 26/02/2017.
// Copyright © 2017 VMLabs Limited. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import Dispatch
open class Pool<T> {
// MARK: Initialization
/**
- parameter maxElementCount: Specifies the maximum number of element that the pool can manage.
- parameter factory: Closure used to create new items for the pool.
*/
public init(maxElementCount: Int, factory: @escaping () throws -> T) {
self.factory = factory
self.maxElementCount = maxElementCount
self.semaphore = DispatchSemaphore(value: maxElementCount)
}
// MARK: Setting and Getting Attributes
/// The maximum number of element that the pool can manage.
public let maxElementCount: Int
/// Closure used to create new items for the pool.
public let factory: () throws -> T
// MARK: Storage
var elements = [T]()
var elementCount = 0
// MARK: Concurrency Management
private let queue = DispatchQueue(label: "com.reswifq.Pool")
private let semaphore: DispatchSemaphore
// MARK: Accessing Elements
/**
It draws an element from the pool.
This method creates a new element using the instance `factory` until it reaches `maxElementCount`,
in that case it returns an existing element from the pool or wait until one is available.
- returns: The first available element from the pool.
*/
public func draw() throws -> T {
// when count reaches zero, calls to the semaphore will block
guard self.semaphore.wait(timeout: .distantFuture) == .success else {
throw PoolError.drawTimeOut
}
return try self.queue.sync {
guard self.elements.isEmpty, self.elementCount < self.maxElementCount else {
// Use an existing element
return self.elements.removeFirst()
}
// Create a new element
do {
let element = try self.factory()
self.elementCount += 1
return element
} catch {
self.semaphore.signal()
throw PoolError.factoryError(error)
}
}
}
/**
It returns a previously drawn element to the pool.
- parameter element: The element to put back in the pool.
*/
public func release(_ element: T, completion: (() -> Void)? = nil) {
self.queue.async {
self.elements.append(element)
self.semaphore.signal()
completion?()
}
}
deinit {
for _ in 0..<self.elementCount {
self.semaphore.signal()
}
}
}
public enum PoolError: Swift.Error {
case drawTimeOut
case factoryError(Swift.Error)
}
|
lgpl-3.0
|
ce6e433482d89cb6d3c7abe4f49c1317
| 27.818182 | 103 | 0.634643 | 4.564136 | false | false | false | false |
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev
|
iOS/Pods/BMSAnalytics/Source/Constants.swift
|
2
|
3129
|
/*
* Copyright 2016 IBM Corp.
* 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 BMSCore
internal struct Constants {
static let uncaughtException = "loggerUncaughtExceptionDetected"
static let outboundLogPayload = "__logdata"
static let analyticsApiKey = "x-mfp-analytics-api-key"
static let userDefaultsSuiteName = "com.ibm.mobilefirstplatform.clientsdk.swift.Analytics"
struct Package {
static let logger = Logger.bmsLoggerPrefix + "logger"
static let analytics = Logger.bmsLoggerPrefix + "analytics"
}
struct AnalyticsServer {
static let hostName = "mobile-analytics-dashboard"
static let uploadPath = "/analytics-service/rest/data/events/clientlogs/"
}
struct File {
static let unknown = "[Unknown]"
struct Logger {
static let logs = Constants.Package.logger + ".log"
static let overflowLogs = Constants.Package.logger + ".log.overflow"
static let outboundLogs = Constants.Package.logger + ".log.send"
}
struct Analytics {
static let logs = Constants.Package.analytics + ".log"
static let overflowLogs = Constants.Package.analytics + ".log.overflow"
static let outboundLogs = Constants.Package.analytics + ".log.send"
}
}
struct Metadata {
struct Logger {
static let metadata = "metadata"
static let level = "level"
static let timestamp = "timestamp"
static let package = "pkg"
static let message = "msg"
}
struct Analytics {
static let sessionId = "$appSessionID"
static let duration = "$duration"
static let category = "$category"
static let closedBy = "$closedBy"
static let appSession = "appSession"
static let deviceId = "deviceId"
static let user = "userSwitch"
static let userId = "$userID"
static let initialContext = "initialCtx"
static let timestamp = "$timestamp"
static let location = "logLocation"
static let latitude = "$latitude"
static let longitude = "$longitude"
static let stacktrace = "$stacktrace"
static let exceptionMessage = "$exceptionMessage"
static let exceptionClass = "$exceptionClass"
}
}
}
|
apache-2.0
|
a8dedc838903894070ac1a2956f638a7
| 32.322581 | 94 | 0.600516 | 4.950479 | false | false | false | false |
touchopia/HackingWithSwift
|
project27/Project27/ViewController.swift
|
1
|
4077
|
//
// ViewController.swift
// Project27
//
// Created by TwoStraws on 19/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var currentDrawType = 0
override func viewDidLoad() {
super.viewDidLoad()
drawRectangle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func redrawTapped(_ sender: AnyObject) {
currentDrawType += 1
if currentDrawType > 5 {
currentDrawType = 0
}
switch currentDrawType {
case 0:
drawRectangle()
case 1:
drawCircle()
case 2:
drawCheckerboard()
case 3:
drawRotatedSquares()
case 4:
drawLines()
case 5:
drawImagesAndText()
default:
break
}
}
func drawRectangle() {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
ctx.cgContext.setFillColor(UIColor.red.cgColor)
ctx.cgContext.setStrokeColor(UIColor.black.cgColor)
ctx.cgContext.setLineWidth(10)
ctx.cgContext.addRect(rectangle)
ctx.cgContext.drawPath(using: .fillStroke)
}
imageView.image = img
}
func drawCircle() {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
let rectangle = CGRect(x: 5, y: 5, width: 502, height: 502)
ctx.cgContext.setFillColor(UIColor.red.cgColor)
ctx.cgContext.setStrokeColor(UIColor.black.cgColor)
ctx.cgContext.setLineWidth(10)
ctx.cgContext.addEllipse(in: rectangle)
ctx.cgContext.drawPath(using: .fillStroke)
}
imageView.image = img
}
func drawCheckerboard() {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
ctx.cgContext.setFillColor(UIColor.black.cgColor)
for row in 0 ..< 8 {
for col in 0 ..< 8 {
if (row + col) % 2 == 0 {
ctx.cgContext.fill(CGRect(x: col * 64, y: row * 64, width: 64, height: 64))
}
}
}
}
imageView.image = img
}
func drawRotatedSquares() {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
ctx.cgContext.translateBy(x: 256, y: 256)
let rotations = 16
let amount = Double.pi / Double(rotations)
for _ in 0 ..< rotations {
ctx.cgContext.rotate(by: CGFloat(amount))
ctx.cgContext.addRect(CGRect(x: -128, y: -128, width: 256, height: 256))
}
ctx.cgContext.setStrokeColor(UIColor.black.cgColor)
ctx.cgContext.strokePath()
}
imageView.image = img
}
func drawLines() {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
ctx.cgContext.translateBy(x: 256, y: 256)
var first = true
var length: CGFloat = 256
for _ in 0 ..< 256 {
ctx.cgContext.rotate(by: CGFloat.pi / 2)
if first {
ctx.cgContext.move(to: CGPoint(x: length, y: 50))
first = false
} else {
ctx.cgContext.addLine(to: CGPoint(x: length, y: 50))
}
length *= 0.99
}
ctx.cgContext.setStrokeColor(UIColor.black.cgColor)
ctx.cgContext.strokePath()
}
imageView.image = img
}
func drawImagesAndText() {
// 1
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
// 2
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
// 3
let attrs = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 36)!, NSParagraphStyleAttributeName: paragraphStyle]
// 4
let string = "The best-laid schemes o'\nmice an' men gang aft agley"
string.draw(with: CGRect(x: 32, y: 32, width: 448, height: 448), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
// 5
let mouse = UIImage(named: "mouse")
mouse?.draw(at: CGPoint(x: 300, y: 150))
}
// 6
imageView.image = img
}
}
|
unlicense
|
3e65a8343245132661dac402d0fcfa3f
| 21.152174 | 134 | 0.67419 | 3.34647 | false | false | false | false |
strongself/rambobot
|
Rambobot/Sources/App/Models/Answer.swift
|
1
|
1184
|
import Vapor
import Fluent
import Foundation
final class Answer: Model {
fileprivate struct FieldName {
static let id = "id"
static let roundId = "round_id"
static let userId = "user_id"
static let answer = "answer"
}
var id: Node?
var roundId: Int
var userId: Int
var answer: Int
init(roundId: Int, userId: Int, answer: Int) {
self.id = nil
self.roundId = roundId
self.userId = roundId
self.answer = answer
}
init(node: Node, in context: Context) throws {
id = node
roundId = try node.extract(FieldName.roundId)
userId = try node.extract(FieldName.userId)
answer = try node.extract(FieldName.answer)
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
FieldName.id : id,
FieldName.roundId : roundId,
FieldName.userId : userId,
FieldName.answer : answer
])
}
}
extension Answer: Preparation {
static func prepare(_ database: Database) throws {
}
static func revert(_ database: Database) throws {
}
}
|
mit
|
6fa7a1ea6d4a42b6ad28f2b72298afd7
| 22.215686 | 54 | 0.576858 | 4.13986 | false | false | false | false |
mahomealex/MASQLite
|
MASQLite/Classes/MAProperty.swift
|
1
|
6527
|
//
// MAProperty.swift
// FaceU
//
// Created by 林东鹏 on 25/04/2017.
// Copyright © 2017 miantanteam. All rights reserved.
//
import Foundation
import SQLite
enum MAPropertyType : Int {
case String = 0, OptionString, Int64, Double, Bool
}
public final class MAProperty : NSObject {
let name:String
let type:MAPropertyType
let primary:Bool
private let _express:Expressible
init(name:String , type:MAPropertyType, primary:Bool = false) {
self.name = name
self.type = type
self.primary = primary
switch self.type {
case .String:
self._express = Expression<String>(name)
case .OptionString:
self._express = Expression<String?>(name)
case .Int64:
self._express = Expression<Int64>(name)
case .Bool:
self._express = Expression<Bool>(name)
case .Double:
self._express = Expression<Double>(name)
}
}
// var express : Expressible {
//// return self._express
// switch type {
// case .String:
// return optional ? _express as! Expression<String?> : _express as! Expression<String> // Expression<String?>(name) : Expression<String>(name)
// case .Int64:
// return optional ? Expression<Int64?>(name) : Expression<Int64>(name)
// case .Bool:
// return optional ? Expression<Bool?>(name) : Expression<Bool>(name)
// case .Double:
// return optional ? Expression<Double?>(name) : Expression<Double>(name)
// }
// }
func generalSetter(model:MAObject) -> SQLite.Setter {
switch type {
case .String:
return _express as! Expression<String> <- model.value(forKey: name) as! String
case .OptionString:
return _express as! Expression<String?> <- model.value(forKey: name) as? String
case .Int64:
return _express as! Expression<Int64> <- model.value(forKey: name) as! Int64
case .Bool:
return _express as! Expression<Bool> <- model.value(forKey: name) as! Bool
case .Double:
return _express as! Expression<Double> <- model.value(forKey: name) as! Double
}
}
func convertcolumnToModel(model:MAObject, row:Row) {
switch type {
case .String:
model.setValue(row[_express as! Expression<String>], forKey: name)
case .OptionString:
model.setValue(row[_express as! Expression<String?>], forKey: name)
case .Int64:
model.setValue(row[_express as! Expression<Int64>], forKey: name)
case .Bool:
model.setValue(row[_express as! Expression<Bool>], forKey: name)
case .Double:
model.setValue(row[_express as! Expression<Double>], forKey: name)
}
}
func filter(model:MAObject) -> Expression<Bool> {
switch type {
case .String:
return (_express as! Expression<String> == model.value(forKey: name) as! String)
case .OptionString:
return (_express as! Expression<String> == (model.value(forKey: name) as? String)!)
case .Int64:
return (_express as! Expression<Int64> == model.value(forKey: name) as! Int64)
case .Bool:
return (_express as! Expression<Bool> == model.value(forKey: name) as! Bool)
case .Double:
return (_express as! Expression<Double> == model.value(forKey: name) as! Double)
}
}
func filter(key:Any) -> Expression<Bool> {
switch type {
case .String:
return (_express as! Expression<String> == key as! String)
case .OptionString:
return (_express as! Expression<String> == key as! String)
case .Int64:
return (_express as! Expression<Int64> == key as! Int64)
case .Bool:
return (_express as! Expression<Bool> == key as! Bool)
case .Double:
return (_express as! Expression<Double> == key as! Double)
}
}
// public func filterOptional(model:MAObject) -> Expression<Bool?> {
// switch type {
// case .String:
// return (_express as! Expression<String?> == model.value(forKey: name) as? String)
// case .Int64:
// return (_express as! Expression<Int64> == model.value(forKey: name) as! Int64)
// case .Bool:
// return (_express as! Expression<Bool> == model.value(forKey: name) as! Bool)
// case .Double:
// return (_express as! Expression<Double> == model.value(forKey: name) as! Double)
// }
// }
public func buildColumn(builder:SQLite.TableBuilder) {
switch type {
case .String:
if primary {
builder.column(_express as! Expression<String>, primaryKey: true)
} else {
builder.column(_express as! Expression<String>, defaultValue: "")
}
case .OptionString:
builder.column(_express as! Expression<String?>, defaultValue: "")
case .Int64:
if primary {
builder.column(_express as! Expression<Int64>, primaryKey: true)
} else {
builder.column(_express as! Expression<Int64>, defaultValue: 0)
}
case .Bool:
if primary {
builder.column(_express as! Expression<Bool>, primaryKey: true)
} else {
builder.column(_express as! Expression<Bool>, defaultValue: false)
}
case .Double:
if primary {
builder.column(_express as! Expression<Double>, primaryKey: true)
} else {
builder.column(_express as! Expression<Double>, defaultValue: 0)
}
}
}
public func addColumn(table:Table) -> String {
switch type {
case .String:
return table.addColumn(_express as! Expression<String>, defaultValue: "")
case .OptionString:
return table.addColumn(_express as! Expression<String?>, defaultValue: "")
case .Int64:
return table.addColumn(_express as! Expression<Int64>, defaultValue: 0)
case .Bool:
return table.addColumn(_express as! Expression<Bool>, defaultValue: false)
case .Double:
return table.addColumn(_express as! Expression<Double>, defaultValue: 0)
}
}
}
|
mit
|
04f7d9f4f9c40cdec0b8d53f00a7da13
| 35.424581 | 156 | 0.568558 | 4.228275 | false | false | false | false |
123okin123/NKPickerTextField
|
NKPickerTextField/NKPickerTextField.swift
|
1
|
2682
|
//
// PickerTextField.swift
// PickerTextField
//
// Created by Nikolai Kratz on 21.06.17.
// Copyright © 2017 Nikolai Kratz. All rights reserved.
//
import UIKit
class NKPickerTextField: UITextField, UIPickerViewDataSource, UIPickerViewDelegate {
/// UIPickerView of the TextField.
private let picker = UIPickerView()
/// The avalaible options of the UIPickerView associated with this TextField.
var pickerOptions: [String]? {didSet {
if self.text != nil {
if self.text!.isEmpty {
self.text = pickerOptions?[0]
}
}
self.picker.reloadAllComponents()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
init() {
super.init(frame: CGRect.zero)
setup()
}
private func setup() {
picker.dataSource = self
picker.delegate = self
self.inputView = picker
let toolbar = UIToolbar(frame: CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: picker.frame.size.width, height: 44)))
toolbar.items = [
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed))
]
self.inputAccessoryView = toolbar
}
/// Called when the done Button of the inputAccessoryView is pressed. The original implementation calls the resignFirstResponder() method of the PickerTextField.
func doneButtonPressed() {
self.resignFirstResponder()
}
override func becomeFirstResponder() -> Bool {
if text != nil {
if let index = pickerOptions?.index(of: self.text!) {
picker.selectRow(index, inComponent: 0, animated: true)
}
}
return super.becomeFirstResponder()
}
//MARK: PickerViewDelegate and PickerViewDatasource
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerOptions?.count ?? 0
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerOptions?[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let option = pickerOptions?[row]
self.text = option
}
}
|
mit
|
c3a8a344d8d3bd74f657739519052185
| 29.465909 | 165 | 0.620291 | 4.90128 | false | false | false | false |
prebid/prebid-mobile-ios
|
Example/PrebidDemo/PrebidDemoSwift/Examples/In-App/InAppVideoRewardedViewController.swift
|
1
|
1753
|
/* Copyright 2019-2022 Prebid.org, Inc.
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 PrebidMobile
fileprivate let storedImpVideoRewarded = "imp-prebid-video-rewarded-320-480"
fileprivate let storedResponseVideoRewarded = "response-prebid-video-rewarded-320-480"
class InAppVideoRewardedViewController: InterstitialBaseViewController, RewardedAdUnitDelegate {
// Prebid
private var rewardedAdUnit: RewardedAdUnit!
override func loadView() {
super.loadView()
Prebid.shared.storedAuctionResponse = storedResponseVideoRewarded
createAd()
}
func createAd() {
// 1. Create a RewardedAdUnit
rewardedAdUnit = RewardedAdUnit(configID: storedImpVideoRewarded)
rewardedAdUnit.delegate = self
// 2. Load the rewarded ad
rewardedAdUnit.loadAd()
}
// MARK: - RewardedAdUnitDelegate
func rewardedAdDidReceiveAd(_ rewardedAd: RewardedAdUnit) {
rewardedAdUnit.show(from: self)
}
func rewardedAd(_ rewardedAd: RewardedAdUnit, didFailToReceiveAdWithError error: Error?) {
PrebidDemoLogger.shared.error("Rewarded ad unit did fail to receive ad: \(error?.localizedDescription ?? "")")
}
}
|
apache-2.0
|
525ac7fdb3ab230ac9b54a9155fde5a0
| 32.711538 | 118 | 0.720479 | 4.529716 | false | false | false | false |
a1b2c3d4e5x/IRR
|
FinancialFunction/IRR/IRR.swift
|
1
|
1791
|
//
// IRR.swift
// FinancialFunction
//
// Created by GuoHao on 2017/3/3.
// Copyright © 2017年 cgh. All rights reserved.
//
import Foundation
/**
Internal Rate Of Return (IRR)
*/
public class IRR {
static func computeIRR(cashFlows:[Double], presentValues: (([Double]) -> ())? = nil) -> Double? {
// const
let MAX_ITERATION = 1000 // Max Iteration
let PRECISION_REQ = 0.00000001 // Percision
// variable
var guessRate0: Double = 0.1; // Default: 10%
var guessRate1: Double = 0.0;
var derivative: Double = 0.0;
var nowCash: Double = 0.0;
var npv: Double = 0.0;
let numOfFlows = cashFlows.count;
var nowCashs = [Double?](repeating: nil, count: numOfFlows)
for _ in 0 ..< MAX_ITERATION {
npv = 0.0;
derivative = 0.0;
for j in 0 ..< numOfFlows {
nowCash = (cashFlows[j] / pow(1 + guessRate0, Double(j)));
npv = npv + nowCash;
derivative += (Double(-j) * cashFlows[j] / pow(1 + guessRate0, Double(j + 1)));
if nil != presentValues { nowCashs[j] = nowCash }
}
guessRate1 = guessRate0 - (npv / derivative);
if (PRECISION_REQ >= abs(guessRate1 - guessRate0)) {
presentValues?(nowCashs as! [Double])
if nil != presentValues { nowCashs.removeAll() }
return guessRate1;
}
guessRate0 = guessRate1;
}
if nil != presentValues { nowCashs.removeAll() }
return nil
}
}
|
apache-2.0
|
dfa70cae8245f5ff774c259d73696ede
| 27.83871 | 101 | 0.475391 | 4.063636 | false | false | false | false |
taqun/HBR
|
HBR/Classes/Model/Bookmark.swift
|
1
|
1686
|
//
// Bookmark.swift
// HBR
//
// Created by taqun on 2014/09/15.
// Copyright (c) 2014年 envoixapp. All rights reserved.
//
import UIKit
class Bookmark: NSObject {
var data: AnyObject
var items: [BookmarkItem] = []
/*
* Initialize
*/
init(data: AnyObject){
self.data = data
super.init()
self.parseData()
}
/*
* Public Method
*/
func getCommentItem(index: Int) -> (BookmarkItem) {
var predicate = NSPredicate(format: "comment != nil AND comment != ''")
var filteredArray = NSArray(array: items).filteredArrayUsingPredicate(predicate) as! [BookmarkItem]
return filteredArray[index]
}
/*
* Private Method
*/
private func parseData(){
if var bookmarks: NSArray = self.data["bookmarks"] as? NSArray {
for bookmark in bookmarks {
let item = BookmarkItem(data: bookmark)
self.items.append(item)
}
func bookmarkSort(b1: BookmarkItem, b2: BookmarkItem) -> (Bool) {
return b1.date.timeIntervalSinceNow > b2.date.timeIntervalSinceNow
}
self.items = sorted(self.items, bookmarkSort)
}
}
/*
* Getter, Setter
*/
var commentItemCount: Int {
get {
var predicate = NSPredicate(format: "comment != nil AND comment != ''")
var filteredArray = NSArray(array: items).filteredArrayUsingPredicate(predicate) as! [BookmarkItem]
return filteredArray.count
}
}
}
|
mit
|
4c245589d6467f0851caa347c4bea66d
| 22.388889 | 111 | 0.536223 | 4.797721 | false | false | false | false |
sadawi/PrimarySource
|
Pod/iOS/DataSource+UICollectionView.swift
|
1
|
1999
|
//
// DataSource+UICollectionView.swift
// Pods
//
// Created by Sam Williams on 1/28/16.
//
//
import UIKit
extension DataSource: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func registerPresenterIfNeeded(collectionView:UICollectionView) {
if !self.didRegisterPresenter {
self.registerPresenter(collectionView)
}
}
// MARK: - Delegate methods
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.visibleSections.count
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self[section]?.itemCount ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
self.registerPresenterIfNeeded(collectionView: collectionView)
if let item = self.item(at: indexPath), let identifier = item.reuseIdentifier {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
item.configure(cell)
return cell
} else {
// This is an error state. TODO: only on debug
let cell = UICollectionViewCell()
cell.backgroundColor = UIColor.red
return cell
}
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
self.item(at: indexPath)?.onTap()
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let item = self.item(at: indexPath), let size = item.desiredSize?() {
return size
} else {
return self.defaultItemSize
}
}
}
|
mit
|
ba5704f5aa0e71e31b3b9362749509f5
| 34.696429 | 167 | 0.671836 | 5.630986 | false | false | false | false |
ankitthakur/SHSwiftKit
|
Sources/iOS/ImageHelper.swift
|
1
|
6478
|
//
// ImageHelper.swift
// SHSwiftKit
//
// Created by ankitthakur on 08/02/16.
// Copyright © 2016 Ankit Thakur. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
public extension UIImage {
/**
Create image from a view.
- parameter view: view, whose snapshot is needed.
- returns: returns a snapshot image of the view.
*/
class func image(view: UIView) -> UIImage? {
var newImage: UIImage?
localAutoreleasePool { () -> () in
let scale: CGFloat = UIScreen.main().scale
local(closure: { () -> () in
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
})
}
return newImage
}
/**
Scale image to particular size
- parameter image: original image.
- parameter rect: frame to which the original image will be resized.
- returns: resized image to particular rect.
*/
class func image(image: UIImage, withRect rect: CGRect) -> UIImage? {
let imageRef: CGImage = image.cgImage!.cropping(to: rect)!
let croppedImage = UIImage(cgImage: imageRef)
return croppedImage
}
/**
Crop image in square format, with size of width:width or height:height, depending on if width is smaller than height or vice-versa.
- parameter image: original image
- returns: cropped image
*/
class func squareImage(image: UIImage) -> UIImage? {
let originalWidth = image.size.width
let originalHeight = image.size.height
var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}
let xOrigin = (originalWidth - edge) / 2.0
let yOrigin = (originalHeight - edge) / 2.0
let cropSquare = CGRect(x: xOrigin, y: yOrigin, width: edge, height: edge)
let imageRef = image.cgImage!.cropping(to: cropSquare)
return UIImage.init(cgImage:imageRef!, scale: UIScreen.main().scale, orientation: image.imageOrientation)
}
/**
Scale and crop image from original image to a particular required size.
- parameter sourceImage: original image which is needed to be scaled and cropped.
- parameter targetSize: the size to which image needs to be scaled and cropped.
- returns: Returns an image, with target size with proper scaling and cropping.
*/
class func scaleAndCropImage(sourceImage: UIImage, forSize targetSize: CGSize) -> UIImage? {
var newImage: UIImage?
let imageSize: CGSize = sourceImage.size
let width: CGFloat = imageSize.width
let height: CGFloat = imageSize.height
let targetWidth: CGFloat = targetSize.width
let targetHeight: CGFloat = targetSize.height
var scaleFactor: CGFloat = 0.0
var scaledWidth: CGFloat = targetWidth
var scaledHeight: CGFloat = targetHeight
var thumbnailPoint = CGPoint(x: 0.0, y: 0.0)
if imageSize.equalTo(targetSize) == false {
let widthFactor = targetWidth/width
let heightFactor = targetHeight/height
if widthFactor > heightFactor {
scaleFactor = widthFactor; // scale to fit height
} else {
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor
scaledHeight = height * scaleFactor
// center the image
if widthFactor > heightFactor {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5
} else {
if widthFactor < heightFactor {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5
}
}
}
local { () -> () in
UIGraphicsBeginImageContext(targetSize); // this will crop
var thumbnailRect: CGRect = CGRect.zero
thumbnailRect.origin = thumbnailPoint
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
sourceImage.draw(in: thumbnailRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
if newImage == nil {
NSLog("could not scale image")
}
//pop the context to get back to the default
UIGraphicsEndImageContext()
}
return newImage
}
/**
Scale and crop current image to particular required size.
- parameter targetSize: the size to which image needs to be scaled and cropped.
- returns: Returns an image, with target size with proper scaling and cropping.
*/
func scaleAndCropImageForSize(targetSize: CGSize) -> UIImage? {
return UIImage.scaleAndCropImage(sourceImage: self, forSize: targetSize)
}
/**
create image with border color
- parameter sourceImage: original image which needs border
- parameter borderColor: border color
- returns: new image with border color
*/
class func image(sourceImage: UIImage, withBorderColor borderColor: UIColor) -> UIImage? {
var newImage: UIImage?
let size: CGSize = sourceImage.size
localAutoreleasePool { () -> () in
UIGraphicsBeginImageContext(size)
let rect: CGRect = CGRect(x: 0, y:0, width: size.width, height: size.height)
sourceImage.draw(in: rect, blendMode: .normal, alpha: 1)
let context: CGContext = UIGraphicsGetCurrentContext()!
let components: ColorComponents = borderColor.colorComponents()
context.setStrokeColor(red: components.red, green: components.green, blue: components.blue, alpha: components.alpha)
context.stroke(rect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return newImage
}
/**
create image with black border color
- parameter sourceImage: original image which needs border
- returns: new image with black border
*/
class func imageWithBlackBorder(sourceImage: UIImage) -> UIImage? {
return UIImage.image(sourceImage: sourceImage, withBorderColor: UIColor.black())
}
}
|
mit
|
796c587ddfcec9ca4cc81dc49a85c9ad
| 31.064356 | 136 | 0.62776 | 5.194066 | false | false | false | false |
iAladdin/SwiftyFORM
|
Source/FormItems/ViewControllerFormItem.swift
|
1
|
1705
|
//
// ViewControllerFormItem.swift
// SwiftyFORM
//
// Created by Simon Strandgaard on 20-06-15.
// Copyright © 2015 Simon Strandgaard. All rights reserved.
//
import Foundation
public class ViewControllerFormItemPopContext {
public let parentViewController: UIViewController
public let childViewController: UIViewController
public let cell: ViewControllerFormItemCell
public let returnedObject: AnyObject?
public init(parentViewController: UIViewController, childViewController: UIViewController, cell: ViewControllerFormItemCell, returnedObject: AnyObject?) {
self.parentViewController = parentViewController
self.childViewController = childViewController
self.cell = cell
self.returnedObject = returnedObject
}
}
public class ViewControllerFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visitViewController(self)
}
public var placeholder: String = ""
public func placeholder(placeholder: String) -> Self {
self.placeholder = placeholder
return self
}
public var title: String = ""
public func title(title: String) -> Self {
self.title = title
return self
}
public func viewController(aClass: UIViewController.Type) -> Self {
createViewController = { (dismissCommand: CommandProtocol) in
return aClass.init()
}
return self
}
// the view controller must invoke the dismiss block when it's being dismissed
public typealias CreateViewController = CommandProtocol -> UIViewController?
public var createViewController: CreateViewController?
// dismissing the view controller
public typealias PopViewController = ViewControllerFormItemPopContext -> Void
public var willPopViewController: PopViewController?
}
|
mit
|
d6b836b35f2a3dec20a52a4a7add73c1
| 29.428571 | 155 | 0.785798 | 4.694215 | false | false | false | false |
Urinx/SublimeCode
|
Sublime/Pods/Swifter/Sources/Socket.swift
|
2
|
7591
|
//
// Socket.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
/* Low level routines for POSIX sockets */
public enum SocketError: ErrorType {
case SocketCreationFailed(String)
case SocketSettingReUseAddrFailed(String)
case BindFailed(String)
case ListenFailed(String)
case WriteFailed(String)
case GetPeerNameFailed(String)
case ConvertingPeerNameFailed
case GetNameInfoFailed(String)
case AcceptFailed(String)
case RecvFailed(String)
}
public class Socket: Hashable, Equatable {
public class func tcpSocketForListen(port: in_port_t, maxPendingConnection: Int32 = SOMAXCONN) throws -> Socket {
#if os(Linux)
let socketFileDescriptor = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
#else
let socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0)
#endif
if socketFileDescriptor == -1 {
throw SocketError.SocketCreationFailed(Socket.descriptionOfLastError())
}
var value: Int32 = 1
if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(sizeof(Int32))) == -1 {
let details = Socket.descriptionOfLastError()
Socket.release(socketFileDescriptor)
throw SocketError.SocketSettingReUseAddrFailed(details)
}
Socket.setNoSigPipe(socketFileDescriptor)
#if os(Linux)
var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = Socket.htonsPort(port)
addr.sin_addr = in_addr(s_addr: in_addr_t(0))
addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
#else
var addr = sockaddr_in()
addr.sin_len = __uint8_t(sizeof(sockaddr_in))
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = Socket.htonsPort(port)
addr.sin_addr = in_addr(s_addr: inet_addr("0.0.0.0"))
addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
#endif
var bind_addr = sockaddr()
memcpy(&bind_addr, &addr, Int(sizeof(sockaddr_in)))
if bind(socketFileDescriptor, &bind_addr, socklen_t(sizeof(sockaddr_in))) == -1 {
let details = Socket.descriptionOfLastError()
Socket.release(socketFileDescriptor)
throw SocketError.BindFailed(details)
}
if listen(socketFileDescriptor, maxPendingConnection ) == -1 {
let details = Socket.descriptionOfLastError()
Socket.release(socketFileDescriptor)
throw SocketError.ListenFailed(details)
}
return Socket(socketFileDescriptor: socketFileDescriptor)
}
private let socketFileDescriptor: Int32
public init(socketFileDescriptor: Int32) {
self.socketFileDescriptor = socketFileDescriptor
}
public var hashValue: Int { return Int(self.socketFileDescriptor) }
public func release() {
Socket.release(self.socketFileDescriptor)
}
public func shutdwn() {
Socket.shutdwn(self.socketFileDescriptor)
}
public func acceptClientSocket() throws -> Socket {
var addr = sockaddr()
var len: socklen_t = 0
let clientSocket = accept(self.socketFileDescriptor, &addr, &len)
if clientSocket == -1 {
throw SocketError.AcceptFailed(Socket.descriptionOfLastError())
}
Socket.setNoSigPipe(clientSocket)
return Socket(socketFileDescriptor: clientSocket)
}
public func writeUTF8(string: String) throws {
try writeUInt8(ArraySlice(string.utf8))
}
public func writeUInt8(data: [UInt8]) throws {
try writeUInt8(ArraySlice(data))
}
public func writeUInt8(data: ArraySlice<UInt8>) throws {
try data.withUnsafeBufferPointer {
var sent = 0
while sent < data.count {
#if os(Linux)
let s = send(self.socketFileDescriptor, $0.baseAddress + sent, Int(data.count - sent), Int32(MSG_NOSIGNAL))
#else
let s = write(self.socketFileDescriptor, $0.baseAddress + sent, Int(data.count - sent))
#endif
if s <= 0 {
throw SocketError.WriteFailed(Socket.descriptionOfLastError())
}
sent += s
}
}
}
public func read() throws -> UInt8 {
var buffer = [UInt8](count: 1, repeatedValue: 0)
let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), 0)
if next <= 0 {
throw SocketError.RecvFailed(Socket.descriptionOfLastError())
}
return buffer[0]
}
private static let CR = UInt8(13)
private static let NL = UInt8(10)
public func readLine() throws -> String {
var characters: String = ""
var n: UInt8 = 0
repeat {
n = try self.read()
if n > Socket.CR { characters.append(Character(UnicodeScalar(n))) }
} while n != Socket.NL
return characters
}
public func peername() throws -> String {
var addr = sockaddr(), len: socklen_t = socklen_t(sizeof(sockaddr))
if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
throw SocketError.GetPeerNameFailed(Socket.descriptionOfLastError())
}
var hostBuffer = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
throw SocketError.GetNameInfoFailed(Socket.descriptionOfLastError())
}
guard let name = String.fromCString(hostBuffer) else {
throw SocketError.ConvertingPeerNameFailed
}
return name
}
private class func descriptionOfLastError() -> String {
return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
}
private class func setNoSigPipe(socket: Int32) {
#if os(Linux)
// There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(),
// or use signal(SIGPIPE, SIG_IGN) to make your entire application ignore SIGPIPE.
#else
// Prevents crashes when blocking calls are pending and the app is paused ( via Home button ).
var no_sig_pipe: Int32 = 1
setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(sizeof(Int32)))
#endif
}
private class func shutdwn(socket: Int32) {
#if os(Linux)
shutdown(socket, Int32(SHUT_RDWR))
#else
Darwin.shutdown(socket, SHUT_RDWR)
#endif
}
private class func release(socket: Int32) {
#if os(Linux)
shutdown(socket, Int32(SHUT_RDWR))
#else
Darwin.shutdown(socket, SHUT_RDWR)
#endif
close(socket)
}
private class func htonsPort(port: in_port_t) -> in_port_t {
#if os(Linux)
return htons(port)
#else
let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
return isLittleEndian ? _OSSwapInt16(port) : port
#endif
}
}
public func ==(socket1: Socket, socket2: Socket) -> Bool {
return socket1.socketFileDescriptor == socket2.socketFileDescriptor
}
|
gpl-3.0
|
4a12f1a95f9687635ad0c8a4dfcfd271
| 34.138889 | 137 | 0.601976 | 4.3125 | false | false | false | false |
dzenbot/XCSwiftr
|
XCSwiftr/Classes/DataControllers/XCSCommandController.swift
|
1
|
3247
|
//
// XCSCommandController.swift
// XCSwiftr
//
// Created by Ignacio Romero on 4/3/16.
// Copyright © 2016 DZN Labs. All rights reserved.
//
import Foundation
open class XCSCommandController: NSObject {
fileprivate var scriptName = "objc2swift"
fileprivate var scriptVersion = "1.0"
open func objc2Swift(_ objcPath: String, completion: @escaping ((String) -> Void)) {
let bundle = Bundle(for: XCSCommandController.self)
var scriptPath = ""
if let path = bundle.path(forResource: "\(scriptName)-\(scriptVersion)", ofType: "jar") {
scriptPath = path
}
let args: [String] = ["-jar", scriptPath, objcPath]
return self.runJavaWithArguments(args, completion: completion)
}
fileprivate func runJavaWithArguments(_ arguments: [String], completion: @escaping ((String) -> Void)) {
isJDKInstalled { (available) in
if available == true {
return self.runWithLaunchPath("/usr/bin/java", arguments: arguments, completion: completion)
} else {
completion("JDK is not available. Please download and install from http://www.oracle.com/technetwork/java/javase/downloads/index.html")
}
}
}
fileprivate func runBashWithArguments(_ arguments: [String], completion: @escaping ((String) -> Void)) {
return self.runWithLaunchPath("/bin/sh", arguments: arguments, completion: completion)
}
fileprivate func runWithLaunchPath(_ launchPath: String, arguments: [String], completion: @escaping ((String) -> Void)) {
DispatchQueue.global(qos: .default).async {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let outputPipe = Pipe()
let errorPipe = Pipe()
task.standardOutput = outputPipe
task.standardError = errorPipe
let outputFileHandler = outputPipe.fileHandleForReading
let errorFileHandler = errorPipe.fileHandleForReading
task.terminationHandler = { (task: Process) in print("termination reason : \(task.terminationReason) | termination status : \(task.terminationStatus)") }
task.launch()
let outputData = outputFileHandler.readDataToEndOfFile()
let errorData = errorFileHandler.readDataToEndOfFile()
var result = ""
if outputData.count > 0 {
result = String(data: outputData, encoding: String.Encoding.utf8)!
} else if errorData.count > 0 {
result = String(data: errorData, encoding: String.Encoding.utf8)!
} else {
result = "Unkown error!"
}
DispatchQueue.main.async {
completion(result)
}
}
}
fileprivate func isJDKInstalled(_ completion: @escaping ((Bool) -> Void)) {
let args = ["-version"]
self.runBashWithArguments(args) { (result) in
print(result)
if result.lowercased().range(of: "cannot execute binary file") != nil {
completion(false)
} else {
completion(true)
}
}
}
}
|
mit
|
d536fb1312a87f3410a40d61345597e1
| 31.138614 | 165 | 0.600739 | 4.816024 | false | false | false | false |
iOS-Swift-Developers/Swift
|
RxSwift使用教程/6-RxSwift的UITableVIew使用/6-RxSwift的UITableVIew使用/ViewController.swift
|
1
|
1934
|
//
// ViewController.swift
// 6-RxSwift的UITableVIew使用
//
// Created by 韩俊强 on 2017/8/2.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
fileprivate lazy var bag : DisposeBag = DisposeBag()
fileprivate var heros : [Hero] = [Hero]()
fileprivate lazy var heroVM : HeroViewModel = HeroViewModel(searchText:self.searchText)
var searchText: Observable<String> {
return searchBar.rx.text.orEmpty.throttle(0.5, scheduler: MainScheduler.instance)
}
override func viewDidLoad() {
super.viewDidLoad()
// 1.取出调整底部内边距
automaticallyAdjustsScrollViewInsets = false
// 2.给tableView绑定数据
heroVM.heroVariable.asObservable().bind(to: tableView.rx.items(cellIdentifier:"HeroCellID", cellType: UITableViewCell.self)) { row, hero, cell in
cell.textLabel?.text = hero.name
cell.detailTextLabel?.text = hero.intro
cell.imageView?.image = UIImage.init(named: hero.icon)
}.addDisposableTo(bag)
// 3.监听UITableView的点击
tableView.rx.itemSelected.subscribe(onNext: { (indexPath) in
print(indexPath)
}).addDisposableTo(bag)
tableView.rx.modelSelected(Hero.self).subscribe(onNext: { (hero : Hero) in
print(hero.name)
}, onError: { (error : Error) in
print(error)
}, onCompleted: {
}).addDisposableTo(bag)
}
@IBAction func itemAction(_ sender: UIBarButtonItem) {
let hero = Hero(dict: ["icon" : "nss", "name" : "xiaohange", "intro" : "最强王者!!"])
heroVM.heroVariable.value = [hero]
}
}
|
mit
|
d68c69ed9397113d2f91c87d87002a54
| 29.209677 | 153 | 0.616658 | 4.376168 | false | false | false | false |
kharrison/CodeExamples
|
Playgrounds/ContentMode.playground/Sources/CircleView.swift
|
1
|
651
|
import UIKit
public class CircleView: UIView {
var lineWidth: CGFloat = 5 {
didSet { setNeedsDisplay() }
}
var color: UIColor = .red {
didSet { setNeedsDisplay() }
}
public override func draw(_ rect: CGRect) {
let circleCenter = convert(center, from: superview)
let circleRadius = min(bounds.size.width,bounds.size.height)/2 * 0.80
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
circlePath.lineWidth = lineWidth
color.set()
circlePath.stroke()
}
}
|
bsd-3-clause
|
275f8f11c3a4a220b1d342674a6b2f32
| 28.590909 | 148 | 0.626728 | 4.584507 | false | false | false | false |
apple/swift-argument-parser
|
Sources/ArgumentParser/Usage/DumpHelpGenerator.swift
|
1
|
5720
|
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import ArgumentParserToolInfo
@_implementationOnly import class Foundation.JSONEncoder
internal struct DumpHelpGenerator {
var toolInfo: ToolInfoV0
init(_ type: ParsableArguments.Type) {
self.init(commandStack: [type.asCommand])
}
init(commandStack: [ParsableCommand.Type]) {
self.toolInfo = ToolInfoV0(commandStack: commandStack)
}
func rendered() -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
encoder.outputFormatting.insert(.sortedKeys)
}
guard let encoded = try? encoder.encode(self.toolInfo) else { return "" }
return String(data: encoded, encoding: .utf8) ?? ""
}
}
fileprivate extension BidirectionalCollection where Element == ParsableCommand.Type {
/// Returns the ArgumentSet for the last command in this stack, including
/// help and version flags, when appropriate.
func allArguments() -> ArgumentSet {
guard var arguments = self.last.map({ ArgumentSet($0, visibility: .private, parent: .root) })
else { return ArgumentSet() }
self.versionArgumentDefinition().map { arguments.append($0) }
self.helpArgumentDefinition().map { arguments.append($0) }
return arguments
}
}
fileprivate extension ArgumentSet {
func mergingCompositeArguments() -> ArgumentSet {
var arguments = ArgumentSet()
var slice = self[...]
while var argument = slice.popFirst() {
if argument.help.isComposite {
// If this argument is composite, we have a group of arguments to
// merge together.
let groupEnd = slice
.firstIndex { $0.help.keys != argument.help.keys }
?? slice.endIndex
let group = [argument] + slice[..<groupEnd]
slice = slice[groupEnd...]
switch argument.kind {
case .named:
argument.kind = .named(group.flatMap(\.names))
case .positional, .default:
break
}
argument.help.valueName = group.map(\.valueName).first { !$0.isEmpty } ?? ""
argument.help.defaultValue = group.compactMap(\.help.defaultValue).first
argument.help.abstract = group.map(\.help.abstract).first { !$0.isEmpty } ?? ""
argument.help.discussion = group.map(\.help.discussion).first { !$0.isEmpty } ?? ""
}
arguments.append(argument)
}
return arguments
}
}
fileprivate extension ToolInfoV0 {
init(commandStack: [ParsableCommand.Type]) {
self.init(command: CommandInfoV0(commandStack: commandStack))
}
}
fileprivate extension CommandInfoV0 {
init(commandStack: [ParsableCommand.Type]) {
guard let command = commandStack.last else {
preconditionFailure("commandStack must not be empty")
}
let parents = commandStack.dropLast()
var superCommands = parents.map { $0._commandName }
if let superName = parents.first?.configuration._superCommandName {
superCommands.insert(superName, at: 0)
}
let defaultSubcommand = command.configuration.defaultSubcommand?
.configuration.commandName
let subcommands = command.configuration.subcommands
.map { subcommand -> CommandInfoV0 in
var commandStack = commandStack
commandStack.append(subcommand)
return CommandInfoV0(commandStack: commandStack)
}
let arguments = commandStack
.allArguments()
.mergingCompositeArguments()
.compactMap(ArgumentInfoV0.init)
self = CommandInfoV0(
superCommands: superCommands,
commandName: command._commandName,
abstract: command.configuration.abstract,
discussion: command.configuration.discussion,
defaultSubcommand: defaultSubcommand,
subcommands: subcommands,
arguments: arguments)
}
}
fileprivate extension ArgumentInfoV0 {
init?(argument: ArgumentDefinition) {
guard let kind = ArgumentInfoV0.KindV0(argument: argument) else { return nil }
self.init(
kind: kind,
shouldDisplay: argument.help.visibility.base == .default,
sectionTitle: argument.help.parentTitle.nonEmpty,
isOptional: argument.help.options.contains(.isOptional),
isRepeating: argument.help.options.contains(.isRepeating),
names: argument.names.map(ArgumentInfoV0.NameInfoV0.init),
preferredName: argument.names.preferredName.map(ArgumentInfoV0.NameInfoV0.init),
valueName: argument.valueName,
defaultValue: argument.help.defaultValue,
allValues: argument.help.allValues,
abstract: argument.help.abstract,
discussion: argument.help.discussion)
}
}
fileprivate extension ArgumentInfoV0.KindV0 {
init?(argument: ArgumentDefinition) {
switch argument.kind {
case .named:
switch argument.update {
case .nullary:
self = .flag
case .unary:
self = .option
}
case .positional:
self = .positional
case .default:
return nil
}
}
}
fileprivate extension ArgumentInfoV0.NameInfoV0 {
init(name: Name) {
switch name {
case let .long(n):
self.init(kind: .long, name: n)
case let .short(n, _):
self.init(kind: .short, name: String(n))
case let .longWithSingleDash(n):
self.init(kind: .longWithSingleDash, name: n)
}
}
}
|
apache-2.0
|
966ede022f3bd5d7d3ac121f62ca4c7a
| 32.450292 | 97 | 0.66486 | 4.313725 | false | false | false | false |
mcrollin/S2Geometry
|
Sources/Protocols/Interval.swift
|
1
|
1974
|
//
// Interval.swift
// S2Geometry
//
// Created by Marc Rollin on 4/16/17.
// Copyright © 2017 Marc Rollin. All rights reserved.
//
import Foundation
protocol Interval: CustomStringConvertible, Equatable, AlmostEquatable {
var low: Double { get }
var high: Double { get }
var length: Double { get }
var center: Double { get }
var isEmpty: Bool { get }
init(point: Double)
func contains(point: Double) -> Bool
func contains(interval other: Self) -> Bool
func interiorContains(point: Double) -> Bool
func interiorContains(interval other: Self) -> Bool
func intersects(with other: Self) -> Bool
func interiorIntersects(with other: Self) -> Bool
func add(point: Double) -> Self
func expanded(by margin: Double) -> Self
func intersection(with other: Self) -> Self
func union(with other: Self) -> Self
}
extension CustomStringConvertible where Self: Interval {
var description: String {
return "[low:\(low.debugDescription), high:\(high.debugDescription)]"
}
}
extension Equatable where Self: Interval {
// Returns true iff the interval lhs contains the same points as rhs.
static func == (lhs: Self, rhs: Self) -> Bool {
return (lhs.low == rhs.low && lhs.high == rhs.high)
|| (lhs.isEmpty && rhs.isEmpty)
}
}
extension AlmostEquatable where Self: Interval {
/// The empty interval is considered to be positioned arbitrarily on the real line,
/// so any interval with a small enough length will match the empty interval.
///
/// - returns: true iff the interval can be transformed into the other one by moving each endpoint a small distance.
static func ==~ (lhs: Self, rhs: Self) -> Bool {
if lhs.isEmpty {
return rhs.length <= 2 * Double.epsilon
} else if rhs.isEmpty {
return lhs.length <= 2 * Double.epsilon
}
return lhs.low ==~ rhs.low && lhs.high ==~ rhs.high
}
}
|
mit
|
912a76c739540cd2cbc916e57817b45e
| 29.828125 | 120 | 0.647238 | 4.144958 | false | false | false | false |
darrarski/SharedShopping-iOS
|
SharedShoppingAppTests/Services/Shopping/ShoppingServiceRealmSpec.swift
|
1
|
4835
|
import Quick
import Nimble
import RxSwift
import RxTest
import RxBlocking
import RealmSwift
import RxRealm
@testable import SharedShoppingApp
class ShoppingServiceRealmSpec: QuickSpec {
override func spec() {
describe("ShoppingServiceRealm") {
var sut: ShoppingServiceRealm!
var realm: Realm!
beforeEach {
let realmConfig = Realm.Configuration(inMemoryIdentifier: "ShoppingServiceRealmSpec")
realm = try! Realm(configuration: realmConfig)
try! realm.write { realm.deleteAll() }
sut = ShoppingServiceRealm(realm: realm)
}
it("should have no shoppings") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([]))
}
context("create shopping") {
var shopping: Shopping!
beforeEach {
shopping = sut.createShopping(name: "Shopping")
}
it("should have one shopping") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([shopping]))
}
it("should created shopping have correct name") {
expect(try! sut.shoppings.toBlocking().first()!.first!.name).to(equal("Shopping"))
}
context("remove shopping") {
beforeEach {
sut.removeShopping(shopping)
}
it("should have no shoppings") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([]))
}
}
context("remove invalid shopping") {
beforeEach {
sut.removeShopping(ShoppingFake(name: "Invalid", date: Date()))
}
it("should have one shopping") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([shopping]))
}
}
}
describe("with some shoppings") {
var shopping1: Shopping!
var shopping2: Shopping!
var shopping3: Shopping!
var shopping4: Shopping!
var shopping5: Shopping!
func createShopping(name: String, date: Date) -> Shopping {
let shopping = ShoppingRealm()
shopping.name = name
shopping.date = date
try! realm.write { realm.add(shopping) }
return shopping
}
beforeEach {
shopping3 = createShopping(name: "Shopping 3", date: Date(timeIntervalSince1970: 30))
shopping5 = createShopping(name: "Shopping 5", date: Date(timeIntervalSince1970: 50))
shopping1 = createShopping(name: "Shopping 1", date: Date(timeIntervalSince1970: 10))
shopping4 = createShopping(name: "Shopping 4", date: Date(timeIntervalSince1970: 40))
shopping2 = createShopping(name: "Shopping 2", date: Date(timeIntervalSince1970: 20))
}
it("should have shoppings ordered by date") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([
shopping1,
shopping2,
shopping3,
shopping4,
shopping5
]))
}
context("add shopping") {
var newShopping: Shopping!
beforeEach {
newShopping = createShopping(name: "New Shopping", date: Date(timeIntervalSince1970: 31))
}
it("should have correct shoppings") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([
shopping1,
shopping2,
shopping3,
newShopping,
shopping4,
shopping5
]))
}
}
context("remove shopping") {
beforeEach {
sut.removeShopping(shopping2)
}
it("should have correct shoppings") {
expect(try! sut.shoppings.toBlocking().first()).to(equal([
shopping1,
shopping3,
shopping4,
shopping5
]))
}
}
}
}
}
}
|
mit
|
620602de7dc5c883afd6eafaf6d39100
| 34.814815 | 113 | 0.450879 | 5.939803 | false | false | false | false |
johndpope/ClangWrapper.Swift
|
ClangASTViewer/AST.swift
|
1
|
9011
|
//
// AST.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/24.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import ClangWrapper
enum ASTNodeField {
case Spelling
case Extent
case Kind
// case Mangling
case Description
}
class ASTNode {
var name:String = ""
init() {
}
func textForField(f:ASTNodeField) -> String {
return ""
}
func shouldDisplayAsInactive() -> Bool {
return false
}
}
class ASTRootNode: ASTNode {
var translationUnitChildNodes:[TranslationUnitNode] = []
override init() {
super.init()
name = "(Root)"
}
}
class TranslationUnitNode: ASTNode {
let translationUnitData:TranslationUnit
let cursorNode:CursorNode
init(_ translationUnit:TranslationUnit) {
self.translationUnitData = translationUnit
cursorNode = CursorNode(translationUnitData.cursor, "[C] cursor")
super.init()
self.name = "[U] \(translationUnitData.cursor.spelling.lastPathComponent)"
}
}
class CursorNode: ASTNode {
let cursorData:Cursor
lazy var lazyData:LazyData = LazyData(self.cursorData)
init(_ data:Cursor, _ name:String) {
self.cursorData = data
super.init()
self.name = name
}
struct LazyData {
let typeNode:TypeNode
let typedefDeclarationUnderlyingTypeNode:TypeNode
let childCursorNodes:[CursorNode]
let resultTypeNode:TypeNode?
let argumentCursorNodes:[CursorNode]
init(_ data:Cursor) {
self.typeNode = TypeNode(data.type, "[T] type")
self.typedefDeclarationUnderlyingTypeNode = TypeNode(data.typedefDeclarationUnderlyingType, "[T] typedefDeclUnderlyingType")
////
if data.spelling == "ReadRawData" {
println(data.sourceCode)
println(data.children.count)
println(data.visitChildrenWithBlock({ (cursor, parent) -> ChildVisitResult in
println(cursor)
return ChildVisitResult.Recurse
}))
}
var a1 = [] as [CursorNode]
for i in 0..<data.children.count {
let c1 = data.children[i]
let cn1 = CursorNode(c1, "[C] \(c1.spelling)")
// cn1.name = "children[\(i)] \(c1.spelling)"
a1.append(cn1)
}
childCursorNodes = a1
var a2 = [] as [CursorNode]
if data.kind == CursorKind.FunctionDecl || data.kind == CursorKind.CXXMethod {
resultTypeNode = TypeNode(data.resultType, "resultType")
for i in 0..<data.argumentCursors.count {
let c = data.argumentCursors[i]
let n = CursorNode(c, "argument[\(i)]")
a2.append(n)
}
} else {
resultTypeNode = nil
}
argumentCursorNodes = a2
// if data.kind == CursorKind.FunctionDecl || data.kind == CursorKind.CXXMethod {
// for i in 0..<data.argumentCursors.count {
// let c1 = data.argumentCursors[i]
// let cn1 = CursorNode(c1, "[C] \(c1.spelling)")
// argumentCursorNodes.append(cn1)
// }
// }
}
}
override func textForField(f: ASTNodeField) -> String {
switch f {
case .Spelling: return cursorData.spelling
case .Extent: return cursorData.extent.description
case .Kind: return cursorData.kind.description
// case .Mangling: return cursorData.mangling
case .Description: return cursorData.description
default: return ""
}
}
override func shouldDisplayAsInactive() -> Bool {
return cursorData.isNull
}
}
class TypeNode: ASTNode {
let typeData:Type
lazy var lazyData:LazyData = LazyData(self.typeData)
init(_ data:Type, _ name:String) {
self.typeData = data
super.init()
self.name = name
}
struct LazyData {
let canonicalTypeNode:TypeNode
let declarationCursorLinkNode:CursorLinkNode
/// Array or vectors.
let elementTypeNode:TypeNode
let arrayElementTypeNode:TypeNode
/// For function-like types.
let resultTypeNode:TypeNode?
let argumentTypeNodes:[TypeNode]?
/// For point/reference types.
let pointeeTypeNode:TypeNode?
init(_ data:Type) {
let invalid = data.kind == TypeKind.Invalid
func numberExpr(n:Int?) -> String {
return n == nil ? "????" : "\(n!)"
}
canonicalTypeNode = TypeNode(data.canonicalType, "[T] canonicalType")
declarationCursorLinkNode = CursorLinkNode(data.declaration, "[@C] declaration")
elementTypeNode = TypeNode(data.elementType, "elementType x \(numberExpr(data.numberOfElements))")
arrayElementTypeNode = TypeNode(data.arrayElementType, "arrayElementType x \(numberExpr(data.arraySize))")
if data.kind == TypeKind.Invalid {
resultTypeNode = nil
argumentTypeNodes = nil
pointeeTypeNode = nil
return
}
////
resultTypeNode = TypeNode(data.resultType, "[T] resultType")
argumentTypeNodes = {
if let args = data.argumentTypes {
return (0..<args.count).map { i in
let t = args[i]
return TypeNode(t,"[T] argumentTypes[\(i)]")
}
} else {
return nil
}
}()
//// if data.kind == TypeKind.FunctionProto || data.kind == TypeKind.FunctionNoProto || data.kind == TypeKind.Unexposed {
// resultTypeNode = TypeNode(data.resultType, "[T] resultType")
// if let args = data.argumentTypes {
// argumentTypeNodes = (0..<args.count).map { i in
// let t = args[i]
// return TypeNode(t,"[T] argumentTypes[\(i)]")
// }
//// argumentTypeNodes = []
//// for i in 0..<args.count {
//// let t = args[i]
//// argumentTypeNodes!.append(TypeNode(t,"[T] argumentTypes[\(i)]"))
//// }
// }
//// }
pointeeTypeNode = {
if data.kind == TypeKind.Pointer {
return TypeNode(data.pointeeType, "[T] pointeeType")
}
if data.kind == TypeKind.LValueReference {
return TypeNode(data.pointeeType, "[T] pointeeType")
}
if data.kind == TypeKind.RValueReference {
return TypeNode(data.pointeeType, "[T] pointeeType")
}
return nil
}()
}
}
override func textForField(f: ASTNodeField) -> String {
switch f {
case .Spelling: return typeData.spelling
case .Kind: return typeData.kind.description
// case .Mangling: return ""
case .Description: return typeData.description
default: return ""
}
}
override func shouldDisplayAsInactive() -> Bool {
return typeData.kind == TypeKind.Invalid
}
}
class CursorLinkNode: ASTNode {
let cursorData:Cursor
init(_ data:Cursor, _ name:String) {
self.cursorData = data
super.init()
self.name = name
}
override func textForField(f: ASTNodeField) -> String {
switch f {
case .Spelling: return cursorData.spelling
case .Extent: return cursorData.extent.description
case .Kind: return cursorData.kind.description
// case .Mangling: return cursorData.mangling
case .Description: return cursorData.description
default: return ""
}
}
override func shouldDisplayAsInactive() -> Bool {
return cursorData.isNull
}
}
protocol ASTNodeNavigation: AnyObject {
var name:String { get }
var description:String { get }
var allChildNodes:[ASTNodeNavigation] { get }
}
extension ASTRootNode: ASTNodeNavigation {
var description:String {
get {
return ""
}
}
var allChildNodes:[ASTNodeNavigation] {
get {
return translationUnitChildNodes.map({ a in a as ASTNodeNavigation })
}
}
}
extension TranslationUnitNode: ASTNodeNavigation {
var description:String {
get {
return ""
}
}
var allChildNodes:[ASTNodeNavigation] {
get {
return [cursorNode]
}
}
}
extension CursorNode: ASTNodeNavigation {
var description:String {
get {
return self.cursorData.description
}
}
var allChildNodes:[ASTNodeNavigation] {
get {
var a = [] as [ASTNodeNavigation]
a.append(lazyData.typeNode)
a.append(lazyData.typedefDeclarationUnderlyingTypeNode)
// Doesn't work in Swift 1.2.
// lazyData.childCursorNodes.map({ x in a.append(x as ASTNodeNavigation) })
for x in lazyData.childCursorNodes {
a.append(x)
}
if let n = lazyData.resultTypeNode {
a.append(n)
}
for x in lazyData.argumentCursorNodes {
a.append(x)
}
// Doesn't work in Swift 1.2.
// lazyData.argumentCursorNodes.map(a.append)
return a
}
}
}
extension TypeNode: ASTNodeNavigation {
var description:String {
get {
return self.typeData.description
}
}
var allChildNodes:[ASTNodeNavigation] {
get {
var ns = [] as [ASTNodeNavigation]
// ns.append(lazyData.canonicalTypeNode)
ns.append(lazyData.declarationCursorLinkNode)
if let n = lazyData.resultTypeNode {
ns.append(n)
}
if let ns1 = lazyData.argumentTypeNodes {
// Doesn't work in Swift 1.2.
// ns.extend(ns1 as [ASTNodeNavigation])
for x in ns1 {
ns.append(x)
}
}
if let n = lazyData.pointeeTypeNode {
ns.append(n)
}
ns.append(lazyData.elementTypeNode)
ns.append(lazyData.arrayElementTypeNode)
return ns
}
}
}
extension CursorLinkNode: ASTNodeNavigation {
var description:String {
get {
return cursorData.description
}
}
var allChildNodes:[ASTNodeNavigation] {
get {
return []
}
}
}
|
mit
|
4952f497763ecfcb11e19708ab6f3ff7
| 17.094378 | 127 | 0.662746 | 3.039123 | false | false | false | false |
roecrew/AudioKit
|
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Mandolin.xcplaygroundpage/Contents.swift
|
1
|
3167
|
//: ## Mandolin
//: Physical model of a mandolin
import AudioKit
import XCPlayground
let playRate = 2.0
let mandolin = AKMandolin()
mandolin.detune = 1
mandolin.bodySize = 1
var pluckPosition = 0.2
var delay = AKDelay(mandolin)
delay.time = 1.5 / playRate
delay.dryWetMix = 0.3
delay.feedback = 0.2
let reverb = AKReverb(delay)
AudioKit.output = reverb
AudioKit.start()
let scale = [0, 2, 4, 5, 7, 9, 11, 12]
class PlaygroundView: AKPlaygroundView {
var detuneSlider: AKPropertySlider?
var bodySizeSlider: AKPropertySlider?
override func setup() {
addTitle("Mandolin")
detuneSlider = AKPropertySlider(
property: "Detune",
format: "%0.2f",
value: mandolin.detune, minimum: 0.5, maximum: 2,
color: AKColor.magentaColor()
) { detune in
mandolin.detune = detune
}
addSubview(detuneSlider!)
bodySizeSlider = AKPropertySlider(
property: "Body Size",
format: "%0.2f",
value: mandolin.bodySize, minimum: 0.2, maximum: 3,
color: AKColor.cyanColor()
) { bodySize in
mandolin.bodySize = bodySize
}
addSubview(bodySizeSlider!)
addSubview(AKPropertySlider(
property: "Pluck Position",
format: "%0.2f",
value: pluckPosition,
color: AKColor.redColor()
) { position in
pluckPosition = position
})
let presets = ["Large, Resonant", "Electric Guitar-ish", "Small-Bodied, Distorted", "Acid Mandolin"]
addSubview(AKPresetLoaderView(presets: presets) { preset in
switch preset {
case "Large, Resonant":
mandolin.presetLargeResonantMandolin()
case "Electric Guitar-ish":
mandolin.presetElectricGuitarMandolin()
case "Small-Bodied, Distorted":
mandolin.presetSmallBodiedDistortedMandolin()
case "Acid Mandolin":
mandolin.presetAcidMandolin()
default: break
}
self.updateUI()
}
)
}
func updateUI() {
detuneSlider!.value = mandolin.detune
bodySizeSlider!.value = mandolin.bodySize
}
}
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
AKPlaygroundLoop(frequency: playRate) {
var note1 = scale.randomElement()
let octave1 = (2...5).randomElement() * 12
let course1 = (1...4).randomElement()
if random(0, 10) < 1.0 { note1 += 1 }
var note2 = scale.randomElement()
let octave2 = (2...5).randomElement() * 12
let course2 = (1...4).randomElement()
if random(0, 10) < 1.0 { note2 += 1 }
if random(0, 6) > 1.0 {
mandolin.fret(noteNumber: note1+octave1, course: course1 - 1)
mandolin.pluck(course: course1 - 1, position: pluckPosition, velocity: 127)
}
if random(0, 6) > 3.0 {
mandolin.fret(noteNumber: note2+octave2, course: course2 - 1)
mandolin.pluck(course: course2 - 1, position: pluckPosition, velocity: 127)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
|
mit
|
c0776a27b5b1f093e1eae22e88559cde
| 27.790909 | 108 | 0.601831 | 3.770238 | false | false | false | false |
ZhaoBingDong/CYPhotosLibrary
|
CYPhotoKit/Model/CYResourceAssets.swift
|
1
|
2268
|
//
// CYResourceAssets.swift
// CYPhotosKit
//
// Created by 董招兵 on 2017/8/7.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import UIKit
/// PKHUDAssets provides a set of default images, that can be supplied to the PKHUD's content views.
open class CYResourceAssets: NSObject {
open class var addIcon: UIImage { return CYResourceAssets.bundledImage(named:"xiangqing_add2") }
open class var checkmarkImage: UIImage { return CYResourceAssets.bundledImage(named: "AssetsPickerChecked") }
open class var checkmarkNormal : UIImage { return CYResourceAssets.bundledImage(named: "imagepick_normal.png")
}
open class var fullImageNormal : UIImage { return CYResourceAssets.bundledImage(named: "photo_original_def") }
open class var fullImageSelected: UIImage { return CYResourceAssets.bundledImage(named: "photo_original_sel") }
open class var locked : UIImage { return CYResourceAssets.bundledImage(named: "lock") }
open class var takePhotos : UIImage { return CYResourceAssets.bundledImage(named: "takePicture") }
internal class func bundledImage(named name: String) -> UIImage {
let imageName = imageNameInBundle(name: name)
let bundle = bundleWithClass(cls: CYResourceAssets.self)
let image = UIImage(named: imageName, in:bundle, compatibleWith:nil)
if let image = image {
return image
} else {
return UIImage()
}
}
}
public extension UIActivityIndicatorView {
@discardableResult
public class func show() -> UIActivityIndicatorView {
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityView.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0)
activityView.hidesWhenStopped = true
activityView.tag = 1000
activityView.center = (CYAppKeyWindow?.center)!
activityView.startAnimating()
CYAppKeyWindow?.addSubview(activityView)
return activityView
}
public class func hide() {
if let activityView = CYAppKeyWindow?.viewWithTag(1000) as? UIActivityIndicatorView {
activityView.stopAnimating()
activityView.removeFromSuperview()
}
}
}
|
apache-2.0
|
b313b9af47beac85578b96730ecc4f97
| 34.109375 | 115 | 0.690699 | 4.585714 | false | false | false | false |
Brightify/ReactantUI
|
Sources/Tokenizer/Templates/Template.swift
|
1
|
6947
|
//
// Template.swift
// Example
//
// Created by Robin Krenecky on 05/10/2018.
//
import Foundation
#if canImport(UIKit)
import Reactant
#endif
public protocol XMLAttributeName {
init(from value: String) throws
}
/**
* Template identifier used to resolve the template name.
*/
public enum TemplateName: XMLAttributeDeserializable, XMLAttributeName {
case local(name: String)
case global(group: String, name: String)
/**
* Gets the `name` variable from either of the cases.
*/
public var name: String {
switch self {
case .local(let name):
return name
case .global(_, let name):
return name
}
}
public init(from value: String) throws {
let notationCharacter: String
if value.contains(".") {
notationCharacter = "."
} else {
notationCharacter = ":"
}
let components = value.components(separatedBy: notationCharacter).filter { !$0.isEmpty }
if components.count == 2 {
self = .global(group: components[0], name: components[1])
} else if components.count == 1 {
self = .local(name: components[0])
} else {
throw TokenizationError.invalidTemplateName(text: value)
}
}
/**
* Generates an XML `String` representation of the `TemplateName`.
* - returns: XML `String` representation of the `TemplateName`
*/
public func serialize() -> String {
switch self {
case .local(let name):
return name
case .global(let group, let name):
return ":\(group):\(name)"
}
}
/**
* Tries to parse the passed XML attribute into a `TemplateName` identifier.
* - parameter attribute: XML attribute to be parsed into `TemplateName`
* - returns: if not thrown, the parsed `TemplateName`
*/
public static func deserialize(_ attribute: XMLAttribute) throws -> TemplateName {
return try TemplateName(from: attribute.text)
}
}
extension TemplateName: Equatable {
public static func == (lhs: TemplateName, rhs: TemplateName) -> Bool {
switch (lhs, rhs) {
case (.local(let lName), .local(let rName)):
return lName == rName
case (.global(let lGroup, let lName), .global(let rGroup, let rName)):
return lGroup == rGroup && lName == rName
default:
return false
}
}
}
extension Array: XMLAttributeDeserializable where Iterator.Element: XMLAttributeName {
public static func deserialize(_ attribute: XMLAttribute) throws -> Array {
let names = attribute.text.components(separatedBy: CharacterSet.whitespacesAndNewlines).filter {
!$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty
}
return try names.map {
try Iterator.Element(from: $0)
}
}
}
/**
* Structure representing an XML template.
*
* Example:
* ```
* <templates>ont
* <attributedText style="attributedStyle" name="superTemplate">
* <b>Hello</b> {{name}}, {{foo}}
* </attributedText>
* </templates>
* ```
*/
public struct Template: XMLElementDeserializable {
public var name: TemplateName
public var extend: [TemplateName]
public var parentModuleImport: String
public var properties: [Property]
public var type: TemplateType
init(node: XMLElement, groupName: String?) throws {
let name = try node.value(ofAttribute: "name") as String
let extendedStyles = try node.value(ofAttribute: "extend", defaultValue: []) as [TemplateName]
if let groupName = groupName {
self.name = .global(group: groupName, name: name)
self.extend = extendedStyles.map {
if case .local(let name) = $0 {
return .global(group: groupName, name: name)
} else {
return $0
}
}
} else {
self.name = .local(name: name)
self.extend = extendedStyles
}
if node.name == "attributedText" {
parentModuleImport = "Reactant"
properties = try PropertyHelper.deserializeSupportedProperties(properties: Properties.attributedText.allProperties, in: node) as [Property]
type = .attributedText(template: try AttributedTextTemplate(node: node))
} else {
throw TokenizationError(message: "Unknown template \(node.name). (\(node))")
}
}
/**
* Checks if any of Template's properties require theming.
* - parameter context: context to use
* - returns: `Bool` whether or not any of its properties require theming
*/
public func requiresTheme(context: DataContext) -> Bool {
return properties.contains(where: { $0.anyValue.requiresTheme }) ||
extend.contains(where: {
context.template(named: $0)?.requiresTheme(context: context) == true
})
}
/**
* Tries to create the `Template` structure from an XML element.
* - parameter element: XML element to parse
* - returns: if not thrown, `Template` obtained from the passed XML element
*/
public static func deserialize(_ element: XMLElement) throws -> Template {
return try Template(node: element, groupName: nil)
}
}
/**
* Represents `Template`'s type.
* Currently, there are:
* - attributedText: attributed string styling allowing multiple attributed style tags with custom arguments to be defined within it
*/
public enum TemplateType {
case attributedText(template: AttributedTextTemplate)
public var styleType: String {
switch self {
case .attributedText:
return "attributedText"
}
}
}
public struct AttributedTextTemplate {
public var attributedText: ElementAssignableProperty<AttributedText>
public var arguments: [String]
init(node: XMLElement) throws {
let text = try AttributedText.materialize(from: node)
let description = "attributedText"
attributedText = ElementAssignableProperty(namespace: [],
name: description,
description: ElementAssignablePropertyDescription(
namespace: [], name: description,
swiftName: description, key: description),
value: text)
arguments = []
node.children.forEach {
let tokens = Lexer.tokenize(input: $0.description)
tokens.forEach { token in
if case .argument(let argument) = token, !arguments.contains(argument) {
arguments.append(argument)
}
}
}
}
}
|
mit
|
84c58ec6ca59a36e3ec845f974ecb034
| 32.399038 | 151 | 0.595077 | 4.810942 | false | false | false | false |
MyAppConverter/HTMLtoPDF-Demo-Swift
|
HTMLtoPDF-Demo/HTMLtoPDF-Demo/NDHTMLtoPDF.swift
|
1
|
8768
|
//
// NDHTMLtoPDF.m
// Nurves
//
// Created by Clement Wehrung on 31/10/12.
// Copyright (c) 2012-2014 Clement Wehrung. All rights reserved.
//
// Released under the MIT license
//
// Contact [email protected] for any question.
//
// Sources : http://www.labs.saachitech.com/2012/10/23/pdf-generation-using-uiprintpagerenderer/
// Addons : http://developer.apple.com/library/ios/#samplecode/PrintWebView/Listings/MyPrintPageRenderer_m.html#//apple_ref/doc/uid/DTS40010311-MyPrintPageRenderer_m-DontLinkElementID_7
// *******************************************************************************************
// * *
// **This code has been automaticaly ported to Swift language1.2 using MyAppConverter.com **
// * 11/06/2015 *
// *******************************************************************************************
import UIKit
typealias NDHTMLtoPDFCompletionBlock = (htmlToPDF:NDHTMLtoPDF) -> Void
protocol NDHTMLtoPDFDelegate{
func HTMLtoPDFDidSucceed( htmlToPDF:NDHTMLtoPDF )
func HTMLtoPDFDidFail( htmlToPDF:NDHTMLtoPDF )
}
class NDHTMLtoPDF :UIViewController,UIWebViewDelegate
{
var PDFpath:NSString?
var successBlock:NDHTMLtoPDFCompletionBlock?
var delegate:AnyObject?/////////NDHTMLtoPDFDelegate?
var PDFdata:NSData?
var errorBlock:NDHTMLtoPDFCompletionBlock?
var URL:NSURL?
var HTML:NSString?
var webview:UIWebView?
var pageSize:CGSize?
var pageMargins:UIEdgeInsets?
class func createPDFWithURL( URL:NSURL ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(URL:URL , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
class func createPDFWithHTML( HTML:NSString ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: nil , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
class func createPDFWithHTML( HTML:NSString ,baseURL:NSURL ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: baseURL , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
class func createPDFWithURL( URL:NSURL ,pathForPDF PDFpath:NSString ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(URL:URL , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
class func createPDFWithHTML( HTML:NSString ,pathForPDF PDFpath:NSString ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: nil , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
class func createPDFWithHTML( HTML:NSString ,baseURL:NSURL ,pathForPDF PDFpath:NSString , pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML: HTML , baseURL: baseURL , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
init(){
super.init(nibName: nil, bundle: nil)
self.PDFdata = nil
}
init( URL:NSURL? ,delegate:AnyObject? ,pathForPDF PDFpath:NSString? ,pageSize:CGSize? ,margins pageMargins:UIEdgeInsets? ){
super.init(nibName:nil, bundle:nil)
self.URL = URL!
self.delegate = delegate
self.PDFpath = PDFpath!
self.pageMargins = pageMargins!
self.pageSize = pageSize!
self.forceLoadView()
}
init( HTML:NSString ,baseURL:NSURL? ,delegate:AnyObject? ,pathForPDF PDFpath:NSString? ,pageSize:CGSize? ,margins pageMargins:UIEdgeInsets? ){
super.init(nibName:nil, bundle:nil)
self.HTML = HTML
self.URL = baseURL!
self.delegate = delegate
self.PDFpath = PDFpath!
self.pageMargins = pageMargins!
self.pageSize = pageSize!
self.forceLoadView()
}
func forceLoadView(){
UIApplication.sharedApplication().delegate!.window!!.addSubview(self.view )
self.view.frame = CGRectMake( 0 , 0 , 1 , 1 )
self.view.alpha = 0.000000
}
override func viewDidLoad(){
super.viewDidLoad()
self.webview = UIWebView(frame: self.view.frame )
webview!.delegate = self
self.view.addSubview(webview! )
if self.HTML == nil {
webview!.loadRequest(NSURLRequest(URL:self.URL! ) )
}else {
webview!.loadHTMLString(self.HTML as! String , baseURL:self.URL)
}
}
func webViewDidFinishLoad( webView:UIWebView ){
if webView.loading {
return
}
var render:UIPrintPageRenderer = UIPrintPageRenderer()
render.addPrintFormatter(webView.viewPrintFormatter() , startingAtPageAtIndex: 0 )
var printableRect:CGRect = CGRectMake(self.pageMargins!.left , self.pageMargins!.top , self.pageSize!.width - self.pageMargins!.left - self.pageMargins!.right , self.pageSize!.height - self.pageMargins!.top - self.pageMargins!.bottom )
var paperRect:CGRect = CGRectMake( 0 , 0 , self.pageSize!.width , self.pageSize!.height )
render.setValue(NSValue(CGRect: paperRect ) , forKey:"paperRect" )
render.setValue(NSValue(CGRect: printableRect ) , forKey:"printableRect" )
self.PDFdata = render.printToPDF()
if (self.PDFpath != nil) {
self.PDFdata?.writeToFile(self.PDFpath as! String , atomically:true )
}
self.terminateWebTask()
if (self.delegate != nil) && (self.delegate! as! UIViewController).respondsToSelector(Selector("HTMLtoPDFDidSucceed:") ) {
(self.delegate! as! NDHTMLtoPDFDelegate).HTMLtoPDFDidSucceed(self )
}
if (self.successBlock != nil) {
self.successBlock!(htmlToPDF: self);
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func webView(webView: UIWebView, didFailLoadWithError error:NSError)
{
if webView.loading {
return
}
self.terminateWebTask()
if self.delegate != nil && self.delegate!.respondsToSelector(Selector("HTMLtoPDFDidFail"))
{
(self.delegate! as! NDHTMLtoPDFDelegate).HTMLtoPDFDidFail(self)
}
if (self.errorBlock != nil) {
self.errorBlock!(htmlToPDF: self)
}
}
func terminateWebTask()
{
self.webview!.stopLoading()
self.webview!.delegate = nil
self.webview!.removeFromSuperview()
self.view.removeFromSuperview()
self.webview = nil
}
}
extension UIPrintPageRenderer
{
func printToPDF()->NSData
{
var pdfData:NSMutableData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, self.paperRect,nil )
self.prepareForDrawingPages(NSMakeRange(0, self.numberOfPages()))
var bounds:CGRect = UIGraphicsGetPDFContextBounds()
for var i:Int = 0 ; i < self.numberOfPages() ; i++
{
UIGraphicsBeginPDFPage()
self.drawPageAtIndex(i, inRect:bounds)
}
UIGraphicsEndPDFContext()
return pdfData
}
}
|
mit
|
8c93b373324e2505e8a7048fd4c41a98
| 36.797414 | 247 | 0.618613 | 5.059435 | false | false | false | false |
blinksh/blink
|
BlinkCode/Messages.swift
|
1
|
6123
|
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 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
enum CodeFileSystemAction: String, Codable {
case getRoot
case stat
case readDirectory
case readFile
case writeFile
case createDirectory
case delete
case rename
}
struct BaseFileSystemRequest: Codable {
let op: CodeFileSystemAction
}
struct GetRootRequest: Codable {
let op: CodeFileSystemAction
let token: Int
let version: Int
init(token: Int, version: Int) {
self.op = .getRoot
self.token = token
self.version = version
}
}
struct StatFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
init(uri: URI) {
self.op = .stat
self.uri = uri
}
}
struct ReadDirectoryFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
init(uri: URI) {
self.op = .readDirectory
self.uri = uri
}
}
struct ReadFileFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
init(uri: URI) {
self.op = .readFile
self.uri = uri
}
}
struct WriteFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
let options: FileSystemOperationOptions
init(uri: URI, options: FileSystemOperationOptions) {
self.op = .writeFile
self.uri = uri
self.options = options
}
}
struct RenameFileSystemRequest: Codable {
let op: CodeFileSystemAction
let oldUri: URI
let newUri: URI
let options: FileSystemOperationOptions
init(oldUri: URI, newUri: URI, options: FileSystemOperationOptions) {
self.op = .rename
self.oldUri = oldUri
self.newUri = newUri
self.options = options
}
}
struct DeleteFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
let options: FileSystemOperationOptions
init(uri: URI, options: FileSystemOperationOptions) {
self.op = .delete
self.uri = uri
self.options = options
}
}
struct CreateDirectoryFileSystemRequest: Codable {
let op: CodeFileSystemAction
let uri: URI
init(uri: URI) {
self.op = .createDirectory
self.uri = uri
}
}
struct URI {
let rootPath: RootPath
}
// <protocol>://<host>/<path>
// <protocol>:/<path>
extension URI: Codable {
init(from decoder: Decoder) throws {
let str = try String(from: decoder)
guard let url = URL(string: str)
else {
throw WebSocketError(message: "Not a valid URI")
}
self.init(rootPath: RootPath(url))
}
func encode(to encoder: Encoder) throws {
//var container = encoder.unkeyedContainer()
let output = rootPath.url.absoluteString
try output.encode(to: encoder)
}
}
struct FileSystemOperationOptions: Codable {
let overwrite: Bool?
let create: Bool?
let recursive: Bool?
init(overwrite: Bool? = nil, create: Bool? = nil, recursive: Bool? = nil) {
self.overwrite = overwrite
self.create = create
self.recursive = recursive
}
}
struct DirectoryTuple: Codable {
let name: String
let type: FileType
init(name: String, type: FileType) {
self.name = name
self.type = type
}
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(name)
try container.encode(type)
}
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
self.name = try container.decode(String.self)
self.type = try container.decode(FileType.self)
}
}
struct WebSocketError: Error, Encodable {
let message: String
}
enum CodeFileSystemError: Error, Encodable {
case fileExists(uri: URI)
case fileNotFound(uri: URI)
case noPermissions(uri: URI)
var info: (String, URI) {
switch self {
case .fileExists(let uri):
return ("FileExists", uri)
case .fileNotFound(let uri):
return ("FileNotFound", uri)
case .noPermissions(let uri):
return ("NoPermissions", uri)
}
}
enum CodingKeys: String, CodingKey { case errorCode; case uri; }
func encode(to encoder: Encoder) throws {
let (errorCode, uri) = self.info
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(errorCode, forKey: .errorCode)
try container.encode(uri, forKey: .uri)
}
}
enum FileType: Int, Codable {
case Unknown = 0
case File = 1
case Directory = 2
case SymbolicLink = 64
init(posixType: FileAttributeType?) {
guard let posixType = posixType else {
self = .Unknown
return
}
switch posixType {
case .typeRegular:
self = .File
case .typeDirectory:
self = .Directory
case .typeSymbolicLink:
self = .SymbolicLink
default:
self = .Unknown
}
}
}
struct FileStat: Codable {
let type: FileType
let ctime: Int?
let mtime: Int?
let size: Int?
init(type: FileType?, ctime: Int?, mtime: Int?, size: Int?) {
self.type = type ?? .Unknown
self.ctime = ctime
self.mtime = mtime
self.size = size
}
}
|
gpl-3.0
|
ca16c1aa6e97f39f11c646b6dff01612
| 21.847015 | 82 | 0.666177 | 3.960543 | false | false | false | false |
vbudhram/firefox-ios
|
Shared/UserAgent.swift
|
2
|
5559
|
/* 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 AVFoundation
import UIKit
open class UserAgent {
private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
private static func clientUserAgent(prefix: String) -> String {
return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))"
}
open static var syncUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Sync")
}
open static var tokenServerClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Token")
}
open static var fxaUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-FxA")
}
open static var defaultClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS")
}
/**
* Use this if you know that a value must have been computed before your
* code runs, or you don't mind failure.
*/
open static func cachedUserAgent(checkiOSVersion: Bool = true,
checkFirefoxVersion: Bool = true,
checkFirefoxBuildNumber: Bool = true) -> String? {
let currentiOSVersion = UIDevice.current.systemVersion
let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber")
let currentFirefoxBuildNumber = AppInfo.buildNumber
let currentFirefoxVersion = AppInfo.appVersion
let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber")
let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber")
if let firefoxUA = defaults.string(forKey: "UserAgent") {
if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion))
&& (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion)
&& (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) {
return firefoxUA
}
}
return nil
}
/**
* This will typically return quickly, but can require creation of a UIWebView.
* As a result, it must be called on the UI thread.
*/
open static func defaultUserAgent() -> String {
assert(Thread.current.isMainThread, "This method must be called on the main thread.")
if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) {
return firefoxUA
}
let webView = UIWebView()
let appVersion = AppInfo.appVersion
let buildNumber = AppInfo.buildNumber
let currentiOSVersion = UIDevice.current.systemVersion
defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber")
defaults.set(appVersion, forKey: "LastFirefoxVersionNumber")
defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber")
let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: [])
let match = webKitVersionRegex.firstMatch(in: userAgent, options: [],
range: NSRange(location: 0, length: userAgent.count))
if match == nil {
print("Error: Unable to determine WebKit version in UA.")
return userAgent // Fall back to Safari's.
}
let webKitVersion = (userAgent as NSString).substring(with: match!.rangeAt(1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).range(of: "Mobile/")
if mobileRange.location == NSNotFound {
print("Error: Unable to find Mobile section in UA.")
return userAgent // Fall back to Safari's.
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location)
let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
defaults.set(firefoxUA, forKey: "UserAgent")
return firefoxUA
}
open static func desktopUserAgent() -> String {
let userAgent = NSMutableString(string: defaultUserAgent())
// Spoof platform section
let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: [])
guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to determine platform in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)")
// Strip mobile section
let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: [])
guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to find Mobile section in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: mobileMatch.range, with: "")
return String(userAgent)
}
}
|
mpl-2.0
|
8ee480d8363e49ca7b35010eb250ee24
| 41.435115 | 171 | 0.654974 | 4.950134 | false | false | false | false |
exyte/Macaw-Examples
|
HealthStat/HealthStat/Views/DailySummaryView.swift
|
1
|
2632
|
import Macaw
open class DailySummaryView: MacawView {
private var animationGroup = Group()
private var animations = [Animation]()
private let backgroundColors = [
0.2,
0.14,
0.07
].map {
Color.rgba(r: 255, g: 255, b: 255, a: $0)
}
private let gradientColors = [
(top: 0xfc087e, bottom: 0xff6868),
(top: 0x06dfed, bottom: 0x03aafe),
(top: 0xffff5c, bottom: 0xffa170)
].map {
LinearGradient(
degree: 90,
from: Color(val: $0.top),
to: Color(val: $0.bottom)
)
}
private let extent = [
4.0,
2.0,
3.0
]
private let r = [
100.0,
80.0,
60.0
]
private func createArc(_ t: Double, _ i: Int) -> Shape {
return Shape(
form: Arc(
ellipse: Ellipse(cx: 0, cy: 0, rx: self.r[i], ry: self.r[i]),
shift: 5.0,
extent: self.extent[i] * t),
stroke: Stroke(
fill: gradientColors[i],
width: 19,
cap: .round
)
)
}
private func createScene() {
let viewCenterX = Double(self.frame.width / 2)
let text = Text(
text: "Daily Summary",
font: Font(name: "Serif", size: 24),
fill: Color(val: 0xFFFFFF)
)
text.align = .mid
text.place = .move(dx: viewCenterX, dy: 30)
let rootNode = Group(place: .move(dx: viewCenterX, dy: 200))
for i in 0...2 {
let circle = Shape(
form: Circle(cx: 0, cy: 0, r: r[i]),
stroke: Stroke(fill: backgroundColors[i], width: 19)
)
rootNode.contents.append(circle)
}
animationGroup = Group()
rootNode.contents.append(animationGroup)
self.node = [text, rootNode].group()
self.backgroundColor = UIColor(cgColor: Color(val: 0x4a2e7d).toCG())
}
private func createAnimations() {
animations.removeAll()
animations.append(
animationGroup.contentsVar.animation({ t in
var shapes1: [Shape] = []
for i in 0...2 {
shapes1.append(self.createArc(t, i))
}
return shapes1
}, during: 1).easing(Easing.easeInOut)
)
}
open func play() {
createScene()
createAnimations()
animations.forEach {
$0.play()
}
}
}
|
mit
|
8f25ac0a5cec85f358ea375a46837010
| 25.32 | 77 | 0.467325 | 4.012195 | false | false | false | false |
mlmc03/SwiftFM-DroidFM
|
SwiftFM/HanekeSwift/Haneke/Cache.swift
|
1
|
12535
|
//
// Cache.swift
// Haneke
//
// Created by Luis Ascorbe on 23/07/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
// Used to add T to NSCache
class ObjectWrapper : NSObject {
let value: Any
init(value: Any) {
self.value = value
}
}
extension HanekeGlobals {
// It'd be better to define this in the Cache class but Swift doesn't allow statics in a generic type
public struct Cache {
public static let OriginalFormatName = "original"
public enum ErrorCode : Int {
case ObjectNotFound = -100
case FormatNotFound = -101
}
}
}
public class Cache<T: DataConvertible where T.Result == T, T : DataRepresentable> {
let name: String
var memoryWarningObserver : NSObjectProtocol!
public init(name: String) {
self.name = name
let notifications = NSNotificationCenter.defaultCenter()
// Using block-based observer to avoid subclassing NSObject
memoryWarningObserver = notifications.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification,
object: nil,
queue: NSOperationQueue.mainQueue(),
usingBlock: { [unowned self] (notification : NSNotification!) -> Void in
self.onMemoryWarning()
}
)
let originalFormat = Format<T>(name: HanekeGlobals.Cache.OriginalFormatName)
self.addFormat(originalFormat)
}
deinit {
let notifications = NSNotificationCenter.defaultCenter()
notifications.removeObserver(memoryWarningObserver, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
public func set(value value: T, key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: ((T) -> ())? = nil) {
if let (format, memoryCache, diskCache) = self.formats[formatName] {
self.format(value: value, format: format) { formattedValue in
let wrapper = ObjectWrapper(value: formattedValue)
memoryCache.setObject(wrapper, forKey: key)
// Value data is sent as @autoclosure to be executed in the disk cache queue.
diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key)
succeed?(formattedValue)
}
} else {
assertionFailure("Can't set value before adding format")
}
}
public func fetch(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Cache.buildFetch(failure: fail, success: succeed)
if let (format, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper, let result = wrapper.value as? T {
fetch.succeed(result)
diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key)
return fetch
}
self.fetchFromDiskCache(diskCache, key: key, memoryCache: memoryCache, failure: { error in
fetch.fail(error)
}) { value in
fetch.succeed(value)
}
} else {
let localizedFormat = NSLocalizedString("Format %@ not found", comment: "Error description")
let description = String(format:localizedFormat, formatName)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue, description: description)
fetch.fail(error)
}
return fetch
}
public func fetch(fetcher fetcher : Fetcher<T>, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let key = fetcher.key
let fetch = Cache.buildFetch(failure: fail, success: succeed)
self.fetch(key: key, formatName: formatName, failure: { error in
if error?.code == HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue {
fetch.fail(error)
}
if let (format, _, _) = self.formats[formatName] {
self.fetchAndSet(fetcher, format: format, failure: {error in
fetch.fail(error)
}) {value in
fetch.succeed(value)
}
}
// Unreachable code. Formats can't be removed from Cache.
}) { value in
fetch.succeed(value)
}
return fetch
}
public func remove(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
memoryCache.removeObjectForKey(key)
diskCache.removeData(key)
}
}
public func removeAll(completion: (() -> ())? = nil) {
let group = dispatch_group_create();
for (_, (_, memoryCache, diskCache)) in self.formats {
memoryCache.removeAllObjects()
dispatch_group_enter(group)
diskCache.removeAllData {
dispatch_group_leave(group)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC))
if dispatch_group_wait(group, timeout) != 0 {
Log.error("removeAll timed out waiting for disk caches")
}
let path = self.cachePath
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {
Log.error("Failed to remove path \(path)", error as NSError)
}
if let completion = completion {
dispatch_async(dispatch_get_main_queue()) {
completion()
}
}
}
}
// MARK: Size
public var size: UInt64 {
var size: UInt64 = 0
for (_, (_, _, diskCache)) in self.formats {
dispatch_sync(diskCache.cacheQueue) { size += diskCache.size }
}
return size
}
// MARK: Notifications
func onMemoryWarning() {
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
}
// MARK: Formats
var formats : [String : (Format<T>, NSCache, DiskCache)] = [:]
public func addFormat(format : Format<T>) {
let name = format.name
let formatPath = self.formatPath(formatName: name)
let memoryCache = NSCache()
let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity)
self.formats[name] = (format, memoryCache, diskCache)
}
// MARK: Internal
lazy var cachePath: String = {
let basePath = DiskCache.basePath()
let cachePath = (basePath as NSString).stringByAppendingPathComponent(self.name)
return cachePath
}()
func formatPath(formatName formatName: String) -> String {
let formatPath = (self.cachePath as NSString).stringByAppendingPathComponent(formatName)
do {
try NSFileManager.defaultManager().createDirectoryAtPath(formatPath, withIntermediateDirectories: true, attributes: nil)
} catch {
Log.error("Failed to create directory \(formatPath)", error as NSError)
}
return formatPath
}
// MARK: Private
func dataFromValue(value : T, format : Format<T>) -> NSData? {
if let data = format.convertToData?(value) {
return data
}
return value.asData()
}
private func fetchFromDiskCache(diskCache : DiskCache, key: String, memoryCache : NSCache, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
diskCache.fetchData(key: key, failure: { error in
if let block = fail {
if (error?.code == NSFileReadNoSuchFileError) {
let localizedFormat = NSLocalizedString("Object not found for key %@", comment: "Error description")
let description = String(format:localizedFormat, key)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.ObjectNotFound.rawValue, description: description)
block(error)
} else {
block(error)
}
}
}) { data in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
dispatch_async(dispatch_get_main_queue(), {
succeed(descompressedValue)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
})
}
})
}
}
private func fetchAndSet(fetcher : Fetcher<T>, format : Format<T>, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
fetcher.fetch(failure: { error in
let _ = fail?(error)
}) { value in
self.set(value: value, key: fetcher.key, formatName: format.name, success: succeed)
}
}
private func format(value value : T, format : Format<T>, success succeed : (T) -> ()) {
// HACK: Ideally Cache shouldn't treat images differently but I can't think of any other way of doing this that doesn't complicate the API for other types.
if format.isIdentity && !(value is UIImage) {
succeed(value)
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var formatted = format.apply(value)
if let formattedImage = formatted as? UIImage {
let originalImage = value as? UIImage
if formattedImage === originalImage {
formatted = self.decompressedImageIfNeeded(formatted)
}
}
dispatch_async(dispatch_get_main_queue()) {
succeed(formatted)
}
}
}
}
private func decompressedImageIfNeeded(value : T) -> T {
if let image = value as? UIImage {
let decompressedImage = image.hnk_decompressedImage() as? T
return decompressedImage!
}
return value
}
private class func buildFetch(failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Fetch<T>()
if let succeed = succeed {
fetch.onSuccess(succeed)
}
if let fail = fail {
fetch.onFailure(fail)
}
return fetch
}
// MARK: Convenience fetch
// Ideally we would put each of these in the respective fetcher file as a Cache extension. Unfortunately, this fails to link when using the framework in a project as of Xcode 6.1.
public func fetch(key key: String, @autoclosure(escaping) value getValue : () -> T.Result, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = SimpleFetcher<T>(key: key, value: getValue)
return self.fetch(fetcher: fetcher, formatName: formatName, success: succeed)
}
public func fetch(path path: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = DiskFetcher<T>(path: path)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
public func fetch(URL URL : NSURL, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = NetworkFetcher<T>(URL: URL)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
}
|
apache-2.0
|
48e3b49e461cc597a9853642367c661e
| 39.305466 | 214 | 0.588911 | 4.815597 | false | false | false | false |
huonw/swift
|
test/SILGen/generic_tuples.swift
|
3
|
1615
|
// RUN: %target-swift-emit-silgen -module-name generic_tuples -parse-as-library -enable-sil-ownership %s | %FileCheck %s
func dup<T>(_ x: T) -> (T, T) { return (x,x) }
// CHECK-LABEL: sil hidden @$S14generic_tuples3dup{{[_0-9a-zA-Z]*}}F
// CHECK: ([[RESULT_0:%.*]] : @trivial $*T, [[RESULT_1:%.*]] : @trivial $*T, [[XVAR:%.*]] : @trivial $*T):
// CHECK-NEXT: debug_value_addr [[XVAR]] : $*T, let, name "x"
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_0]]
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_1]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]]
// <rdar://problem/13822463>
// Specializing a generic function on a tuple type changes the number of
// SIL parameters, which caused a failure in the ownership conventions code.
struct Blub {}
// CHECK-LABEL: sil hidden @$S14generic_tuples3foo{{[_0-9a-zA-Z]*}}F
func foo<T>(_ x: T) {}
// CHECK-LABEL: sil hidden @$S14generic_tuples3bar{{[_0-9a-zA-Z]*}}F
func bar(_ x: (Blub, Blub)) { foo(x) }
// rdar://26279628
// A type parameter constrained to be a concrete type must be handled
// as that concrete type throughout SILGen. That's especially true
// if it's constrained to be a tuple.
protocol HasAssoc {
associatedtype A
}
extension HasAssoc where A == (Int, Int) {
func returnTupleAlias() -> A {
return (0, 0)
}
}
// CHECK-LABEL: sil hidden @$S14generic_tuples8HasAssocPAASi_Sit1ARtzrlE16returnTupleAliasSi_SityF : $@convention(method) <Self where Self : HasAssoc, Self.A == (Int, Int)> (@in_guaranteed Self) -> (Int, Int) {
// CHECK: return {{.*}} : $(Int, Int)
|
apache-2.0
|
c70e4acd04a3d3caf9c6c292e8cd8088
| 40.410256 | 210 | 0.642105 | 3.070342 | false | false | false | false |
frankcjw/CJWUtilsS
|
CJWUtilsS/QPLib/Utils/QPVersionUtils.swift
|
1
|
2561
|
//
// QPVersionUtils.swift
// CJWUtilsS
//
// Created by Frank on 25/02/2017.
// Copyright © 2017 cen. All rights reserved.
//
import UIKit
import iRate
import iVersion
public class QPVersionUtils: NSObject {
class func isForceUpdate() {
if let bundleId = NSBundle.mainBundle().infoDictionary?["CFBundleIdentifier"] as? String {
print("\(bundleId)")
let checkUrl = "http://98.cenjiawen.com:666/service/appversion/check";
let lastUrl = "http://98.cenjiawen.com:666/service/appversion/latest";
let build = AppInfoManager.getBuild();
let version = AppInfoManager.getVersion();
let param = ["versionPackage": "\(bundleId)", "id": "6", "versionType": "1", "versionCode": "\(build)", "version": "\(version)"]
QPHttpUtils.sharedInstance.newHttpRequest(checkUrl, param: param, success: { (response) in
log.info("\(response)")
}, fail: {
//
})
QPHttpUtils.sharedInstance.newHttpRequest(checkUrl, param: param, success: { (response) in
log.info("\(response)")
}, fail: {
//
})
} else {
log.error("fail to get bundle id")
}
}
public class func setup() {
let version = iVersion.sharedInstance()
version.inThisVersionTitle = "版本更新"
version.updateAvailableTitle = "版本更新"
// version.versionLabelFormat = "什么鬼"
version.okButtonLabel = "立即更新"
version.downloadButtonLabel = "立即更新"
version.ignoreButtonLabel = "稍后提醒"
version.remindButtonLabel = "稍候提醒我"
version.remindPeriod = 1
version.checkPeriod = 1
version.viewedVersionDetails = true
// version.previewMode = true
// version.delegate = self
version.checkForNewVersion()
let rate = iRate.sharedInstance()
rate.daysUntilPrompt = 3
rate.usesUntilPrompt = 5
rate.usesPerWeekForPrompt = 2
rate.remindPeriod = 3
rate.promptForNewVersionIfUserRated = true
rate.messageTitle = "去AppStore给个5星吧!"
/*
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow(infoDictionary);
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
*/
var appName = "我们"
if let info = NSBundle.mainBundle().infoDictionary {
if let name = info["CFBundleDisplayName"] as? String {
appName = name
}
}
rate.message = "如果您喜欢\(appName),请给它一个评价吧。这不会占用您很多的时间,感谢您的支持!"
// rate.previewMode = true
rate.rateButtonLabel = "去评价"
rate.remindButtonLabel = "稍后提醒我"
rate.cancelButtonLabel = "下次"
}
}
|
mit
|
bce16bc4b13cfa85ac46476cf53a6124
| 28.975 | 131 | 0.696414 | 3.298487 | false | false | false | false |
mrlegowatch/RolePlayingCore
|
RolePlayingCore/RolePlayingCoreTests/CurrencyTests.swift
|
1
|
11592
|
//
// UnitCurrencyTests.swift
// RolePlayingCore
//
// Created by Brian Arnold on 2/5/17.
// Copyright © 2017 Brian Arnold. All rights reserved.
//
import XCTest
import RolePlayingCore
class UnitCurrencyTests: XCTestCase {
static var currencies: Currencies!
override class func setUp() {
super.setUp()
// Only load once. TODO: this has a side effect on other unit tests: currencies are already loaded.
let bundle = Bundle(for: UnitCurrencyTests.self)
let decoder = JSONDecoder()
let data = try! bundle.loadJSON("TestCurrencies")
currencies = try! decoder.decode(Currencies.self, from: data)
}
func testUnitCurrency() {
XCTAssertEqual(UnitCurrency.baseUnit(), Currencies.find("gp"), "base unit should be goldPieces")
let goldPieces = Money(value: 25, unit: Currencies.find("gp")!)
let silverPieces = Money(value: 12, unit: Currencies.find("sp")!)
let copperPieces = Money(value: 1, unit: Currencies.find("cp")!)
let electrumPieces = Money(value: 2, unit: Currencies.find("ep")!)
let platinumPieces = Money(value: 2, unit: Currencies.find("pp")!)
let totalPieces = goldPieces + silverPieces - copperPieces + electrumPieces - platinumPieces
// Should be 25 + 1.2 - 0.01 + 1 - 20
XCTAssertEqual(totalPieces.value, 7.19, accuracy: 0.0001, "adding coins")
let totalPiecesInCopper = totalPieces.converted(to: Currencies.find("cp")!)
XCTAssertEqual(totalPiecesInCopper.value, 719, accuracy: 0.01, "adding coins")
}
func testPrintingValues() {
let goldPieces = Money(value: 13.7, unit: .baseUnit())
let formatter = MeasurementFormatter()
// Test default
let gp = formatter.string(from: goldPieces)
XCTAssertEqual(gp, "13.7 gp", "gold pieces")
// Test provided unit
formatter.unitOptions = [.providedUnit]
let gpDefault = formatter.string(from: goldPieces)
XCTAssertEqual(gpDefault, "13.7 gp", "gold pieces")
let silverPieces = goldPieces.converted(to: Currencies.find("sp")!)
let sp = formatter.string(from: silverPieces)
XCTAssertEqual(sp, "137 sp", "silver pieces")
let platinumPieces = goldPieces.converted(to: Currencies.find("pp")!)
let ppProvided = formatter.string(from: platinumPieces)
XCTAssertEqual(ppProvided, "1.37 pp", "platinum pieces")
// Test natural scale
formatter.unitOptions = [.naturalScale]
let ppNatural = formatter.string(from: platinumPieces)
XCTAssertEqual(ppNatural, "13.7 gp", "gold pieces")
formatter.unitOptions = [.providedUnit]
// Test short
formatter.unitStyle = .short
let gpShort = formatter.string(from: goldPieces)
XCTAssertEqual(gpShort, "13.7gp", "gold pieces")
// Test long
formatter.unitStyle = .long
let gpLong = formatter.string(from: goldPieces)
XCTAssertEqual(gpLong, "13.7 gold pieces", "gold pieces")
let gpSingularLong = formatter.string(from: Money(value: 1.0, unit: .baseUnit()))
XCTAssertEqual(gpSingularLong, "1 gold piece", "gold piece")
}
func testMoney() {
do {
let gp = Money(value: 2.5, unit: .baseUnit())
XCTAssertEqual(gp.value, 2.5, "coinage as Double should be 2.5")
}
do {
let cp = "3.2 cp".parseMoney
XCTAssertNotNil(cp, "coinage as cp should not be nil")
if let cp = cp {
XCTAssertEqual(cp.value, 3.2, accuracy: 0.0001, "coinage as string cp should be 3.2")
XCTAssertEqual(cp.unit, Currencies.find("cp"), "coinage as string cp should be copper pieces")
XCTAssertNotEqual(cp.unit, Currencies.find("pp"), "coinage as string cp should not be platinum pieces")
}
}
do {
let gp = "hello".parseMoney
XCTAssertNil(gp, "coinage as string with hello should be nil")
}
}
func testMissingCurrenciesFile() {
do {
let bundle = Bundle(for: UnitCurrencyTests.self)
_ = try bundle.loadJSON("Blarg")
XCTFail("load should have thrown an error")
}
catch let error {
XCTAssertTrue(error is ServiceError, "should be a service error")
let description = "\(error)"
XCTAssertTrue(description.contains("Runtime error"), "should be a runtime error")
}
}
func testDuplicateCurrencies() {
// Try loading the default currencies file a second time.
// It should ignore the duplicate currencies.
do {
XCTAssertEqual(Currencies.allCurrencies.count, 5, "currencies count")
let bundle = Bundle(for: UnitCurrencyTests.self)
let decoder = JSONDecoder()
let data = try bundle.loadJSON("TestCurrencies")
_ = try decoder.decode(Currencies.self, from: data)
XCTAssertEqual(Currencies.allCurrencies.count, 5, "currencies count")
}
catch let error {
XCTFail("duplicate currency should not throw error: \(error)")
}
}
func testMissingCurrencyTraits() {
let decoder = JSONDecoder()
// Test missing symbol
do {
let traits = """
{
"currencies": [{"name": "Foo"}]
}
""".data(using: .utf8)!
let currency = try? decoder.decode(Currencies.self, from: traits)
XCTAssertNil(currency, "missing symbol")
}
// Test symbol with missing coefficient
do {
let traits = """
{
"currencies": [{"symbol": "Foo"}]
}
""".data(using: .utf8)!
let currency = try? decoder.decode(Currencies.self, from: traits)
XCTAssertNil(currency, "missing coefficient")
}
// Test list of items with missing required traits
do {
let traits = """
{
"currencies": [{"name": "Foo"}, {"name": "Bar"}]
}
""".data(using: .utf8)!
do {
_ = try decoder.decode(Currencies.self, from: traits)
XCTFail("should have thrown an error")
}
catch let error {
print("Successfully caught error decoding missing required traits for Currencies. Error: \(error)")
}
}
}
func testEncodingMoney() {
struct MoneyContainer: Encodable {
let money: Money
enum CodingKeys: String, CodingKey {
case money
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode("\(money)", forKey: .money)
}
}
do {
let moneyContainer = MoneyContainer(money: Money(value: 48.93, unit: Currencies.find("sp")!))
let encoder = JSONEncoder()
do {
let encoded = try encoder.encode(moneyContainer)
let deserialized = try JSONSerialization.jsonObject(with: encoded, options: []) as? [String: String]
XCTAssertEqual(deserialized?["money"], "48.93 sp", "encoded money failed to deserialize as string")
}
catch let error {
XCTFail("encoded dice failed, error: \(error)")
}
}
}
func testDecodingMoney() {
struct MoneyContainer: Decodable {
let money: Money
}
let decoder = JSONDecoder()
// Test parseable string
do {
let traits = """
{
"money": "72.17 ep"
}
""".data(using: .utf8)!
let moneyContainer = try decoder.decode(MoneyContainer.self, from: traits)
XCTAssertEqual("\(moneyContainer.money)", "72.17 ep", "Decoded money")
}
catch let error {
XCTFail("decoded dice failed, error: \(error)")
}
// Test raw number
do {
let traits = """
{
"money": 85
}
""".data(using: .utf8)!
let moneyContainer = try decoder.decode(MoneyContainer.self, from: traits)
XCTAssertEqual("\(moneyContainer.money)", "85.0 gp", "Decoded money")
}
catch let error {
XCTFail("decoded dice failed, error: \(error)")
}
// Test invalid value
do {
let traits = """
{
"money": "no money"
}
""".data(using: .utf8)!
_ = try decoder.decode(MoneyContainer.self, from: traits)
XCTFail("decoded dice should have failed")
}
catch let error {
print("Successfully failed to decode invalid dice string, error: \(error)")
}
}
func testDecodingMoneyIfPresent() {
struct MoneyContainer: Decodable {
let money: Money?
}
let decoder = JSONDecoder()
// Test parseable string
do {
let traits = """
{
"money": "72.17 ep"
}
""".data(using: .utf8)!
let moneyContainer = try decoder.decode(MoneyContainer.self, from: traits)
XCTAssertEqual("\(moneyContainer.money!)", "72.17 ep", "Decoded money")
}
catch let error {
XCTFail("decoded dice failed, error: \(error)")
}
// Test raw number
do {
let traits = """
{
"money": 85
}
""".data(using: .utf8)!
let moneyContainer = try decoder.decode(MoneyContainer.self, from: traits)
XCTAssertEqual("\(moneyContainer.money!)", "85.0 gp", "Decoded money")
}
catch let error {
XCTFail("decoded dice failed, error: \(error)")
}
// Test invalid value
do {
let traits = """
{
"money": "no money"
}
""".data(using: .utf8)!
let moneyContainer = try decoder.decode(MoneyContainer.self, from: traits)
XCTAssertNil(moneyContainer.money, "decoded dice should have failed")
}
catch let error {
XCTFail("Failed to decode optional invalid dice string as nil, error: \(error)")
}
}
func testEncodeCurrencies() {
let encoder = JSONEncoder()
do {
let encoded = try encoder.encode(UnitCurrencyTests.currencies)
let deserialized = try JSONSerialization.jsonObject(with: encoded, options: []) as? [String: Any]
XCTAssertNotNil(deserialized)
let currencies = deserialized?["currencies"] as? [[String:Any]]
XCTAssertNotNil(currencies)
XCTAssertEqual(currencies?.count, 5, "5 currencies")
}
catch let error {
XCTFail("Failed to encode currencies, error: \(error)")
}
}
}
|
mit
|
2e906ff3919b67ae79004e4293806e73
| 34.018127 | 119 | 0.537831 | 4.825562 | false | true | false | false |
buscarini/Collectionist
|
Example/Pods/Miscel/Miscel/Classes/Extensions/UIKit/UIFont+Utils.swift
|
1
|
1374
|
//
// UIFont.swift
// Miscel
//
// Created by Jose Manuel Sánchez Peñarroja on 30/10/15.
// Copyright © 2015 vitaminew. All rights reserved.
//
import UIKit
public extension UIFont {
public var monospacedDigitFont: UIFont {
let fontDescriptorFeatureSettings = [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]
let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings]
let oldFontDescriptor = fontDescriptor
let newFontDescriptor = oldFontDescriptor.addingAttributes(fontDescriptorAttributes)
return UIFont(descriptor: newFontDescriptor, size: 0)
}
public static func fontSize(_ toFit: CGRect, string: String, font: UIFont) -> CGFloat {
var thefont = font
while !self.fits(toFit, string: string, font: thefont) {
thefont = thefont.withSize(thefont.pointSize-1)
}
return thefont.pointSize
}
public static func fits(_ rect: CGRect, string: String, font: UIFont) -> Bool {
let nsstring = string as NSString
let maxSize = CGSize(width: rect.width, height: 1000)
let rect = nsstring.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [ NSFontAttributeName : font ], context: nil)
return rect.width <= rect.width && rect.height <= rect.height
}
}
|
mit
|
efb77748b3dba89ea958ecb3f29a4851
| 34.153846 | 162 | 0.738877 | 4.284375 | false | false | false | false |
LearningSwift2/LearningApps
|
SimpleMP3Player/SimpleMP3Player/NowPlayingViewController.swift
|
1
|
2945
|
//
// NowPlayingViewController.swift
// SimpleMP3Player
//
// Created by Phil Wright on 12/2/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
import AVFoundation
class NowPlayingViewController: UIViewController {
var mp3Player:MP3Player?
var timer:NSTimer?
@IBOutlet weak var songName: UILabel!
@IBOutlet weak var songTime: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var imageView : UIImageView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Add listenser
NSNotificationCenter.defaultCenter().addObserver(self, selector:"updateUI", name:"SongDidUpdate", object:nil)
mp3Player = MP3Player()
updateUI()
}
// MARK: - Action Methods
@IBAction func playPauseSong() {
if let player = mp3Player {
if player.isPlaying {
pauseSong()
} else {
playSong()
}
startTimer()
}
}
func playSong() {
if let player = mp3Player {
player.play()
playPauseButton.setImage(UIImage(named: "icon-play"), forState: .Normal)
updateUI()
timer?.invalidate()
}
}
func stopSong() {
if let player = mp3Player {
player.stop()
playPauseButton.setImage(UIImage(named: "icon-stop"), forState: .Normal)
updateUI()
timer?.invalidate()
}
}
func pauseSong() {
if let player = mp3Player {
player.pause()
playPauseButton.setImage(UIImage(named: "icon-pause"), forState: .Normal)
}
}
@IBAction func playNextSong(sender: UIButton) {
mp3Player?.nextSong(false)
startTimer()
}
@IBAction func setVolume(sender: UISlider) {
mp3Player?.setVolume(sender.value)
}
@IBAction func playPreviousSong(sender: UIButton) {
mp3Player?.previousSong()
startTimer()
}
func startTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateProgress"), userInfo: nil, repeats: true)
}
func updateProgress() {
songTime.text = mp3Player?.getCurrentTimeAsString()
if let progress = mp3Player?.getProgress() {
progressBar.progress = progress
}
}
func updateUI() {
if let player = mp3Player {
songName.text = player.getCurrentTitle()
if let imageString = player.getCurrentImageAsString() {
let image = UIImage(named: imageString)
imageView.image = image
}
}
}
}
|
apache-2.0
|
5ac2f9a00dd450d91a425ed91ebdd836
| 24.37931 | 141 | 0.558084 | 4.931323 | false | false | false | false |
cwaffles/Soulcast
|
Soulcast/PushHandler.swift
|
1
|
1579
|
//
// PushHandler.swift
// Soulcast
//
// Created by June Kim on 2016-11-19.
// Copyright © 2016 Soulcast-team. All rights reserved.
//
import Foundation
//singleton for now...
let pushHandler = PushHandler()
class PushHandler {
var bufferHash: [String:AnyObject]?
func handle(_ soulHash: [String:AnyObject]) {
guard let appDelegate = app.delegate as? AppDelegate else {
bufferHash = soulHash
return
}
guard app.applicationState == .active else {
bufferHash = soulHash
return
}
let coordinator = appDelegate.mainCoordinator
// at mainVC screen
let mainVC = coordinator.mainVC
let historyVC = coordinator.historyVC
if mainVC.view.window != nil && historyVC.view.window == nil{
mainVC.receiveRemoteNotification(soulHash)
return
}
// at historyVC screen
if historyVC.view.window != nil && mainVC.view.window == nil {
coordinator.scrollToMainVC() {
mainVC.receiveRemoteNotification(soulHash)
}
}
//DEBUG
// let soulObject = Soul.fromHash(soulHash)
// let alert = UIAlertController(title: "options", message: String(soulObject), preferredStyle: .Alert)
// self.window!.rootViewController!.presentViewController(alert, animated: true, completion: {
// //
// })
}
func activate() {
if let hash = bufferHash {
bufferHash = nil
handle(hash)
}
//TODO: check soloQueue?
/*
if !soloQueue.isEmpty {
delegate?.presentIncomingVC()
}
*/
}
}
|
mit
|
8235e4d8341af5c75829407bfdda84fb
| 24.047619 | 114 | 0.624842 | 4.174603 | false | false | false | false |
cfdrake/lobsters-reader
|
Source/UI/View Controllers/InfoViewController/InfoViewController.swift
|
1
|
2231
|
//
// InfoViewController.swift
// LobstersReader
//
// Created by Colin Drake on 5/28/17.
// Copyright © 2017 Colin Drake. All rights reserved.
//
import UIKit
/// Delegate protocol for Info view controller.
protocol InfoViewControllerDelegate {
func infoViewController(infoViewController: InfoViewController, selectedUrl url: URL)
}
/// Presents basic app information to the user.
final class InfoViewController: UITableViewController {
fileprivate static let cellIdentifier = "InfoCellIdentifier"
fileprivate let info: AppInfoViewModel
var delegate: InfoViewControllerDelegate?
init(info: AppInfoViewModel) {
self.info = info
super.init(style: .grouped)
title = "Info"
tabBarItem = UITabBarItem(title: "Info", image: UIImage.init(named: "InfoIcon"), selectedImage: UIImage.init(named: "InfoIconFilled"))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: InfoViewController.cellIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return info.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return info[section].links.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return info[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: InfoViewController.cellIdentifier, for: indexPath)
let (title, _) = info[indexPath.section].links[indexPath.row]
cell.textLabel?.text = title
cell.accessoryType = .disclosureIndicator
return cell
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let (_, link) = info[indexPath.section].links[indexPath.row]
delegate?.infoViewController(infoViewController: self, selectedUrl: link)
}
}
|
mit
|
72d921d398628e5a220db2ce71a67fd8
| 33.84375 | 142 | 0.713453 | 4.966592 | false | false | false | false |
wuwen1030/ViewControllerTransitionDemo
|
ViewControllerTransition/ModalInteractiveAnimation.swift
|
1
|
2255
|
//
// ModalInteractiveAnimation.swift
// ViewControllerTransition
//
// Created by Ben on 15/7/20.
// Copyright (c) 2015年 X-Team. All rights reserved.
//
import UIKit
enum InteractiveDirection: Int {
case horizental
case vertical
}
class ModalInteractiveAnimation: UIPercentDrivenInteractiveTransition {
var direction:InteractiveDirection
var interacting:Bool = false
private var shouldComplete:Bool = false
private var presentingViewController:UIViewController? = nil
override var percentComplete: CGFloat {
get {
return 1 - self.percentComplete
}
}
init(direction: InteractiveDirection) {
self.direction = direction
}
func wireToViewController(viewController:UIViewController) {
presentingViewController = viewController
prepareGestureRecognizeInView(viewController.view)
}
func prepareGestureRecognizeInView(view:UIView) {
let gesture = UIPanGestureRecognizer(target: self, action: "handleGesture:")
view.addGestureRecognizer(gesture)
}
func handleGesture(gestureRecoginizer:UIPanGestureRecognizer) {
let trainsiton = gestureRecoginizer.translationInView(gestureRecoginizer.view!.superview!)
switch gestureRecoginizer.state {
case UIGestureRecognizerState.Began:
interacting = true
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
case UIGestureRecognizerState.Changed:
var fraction = direction == InteractiveDirection.horizental ? trainsiton.x/320 : trainsiton.y/400
fraction = fmax(fraction, 0.0)
fraction = fmin(fraction, 1)
shouldComplete = fraction > 0.5
updateInteractiveTransition(fraction)
case UIGestureRecognizerState.Ended:
fallthrough
case UIGestureRecognizerState.Cancelled:
interacting = false
if !shouldComplete || gestureRecoginizer.state == UIGestureRecognizerState.Cancelled {
cancelInteractiveTransition()
}
else {
finishInteractiveTransition()
}
default:
break
}
}
}
|
mit
|
1917747ea6602f944190b00077ae252c
| 32.132353 | 109 | 0.671549 | 5.689394 | false | false | false | false |
Zewo/BasicAuthMiddleware
|
Source/BasicAuthMiddleware.swift
|
1
|
4206
|
// BasicAuthMiddleware.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
@_exported import Base64
@_exported import HTTP
public enum AuthenticationResult {
case accessDenied
case authenticated
case payload(key: String, value: Any)
}
enum AuthenticationType {
case server(realm: String?, authenticate: (username: String, password: String) throws -> AuthenticationResult)
case client(username: String, password: String)
}
public struct BasicAuthMiddleware: Middleware {
let type: AuthenticationType
public init(realm: String? = nil, authenticate: (username: String, password: String) throws -> AuthenticationResult) {
type = .server(realm: realm, authenticate: authenticate)
}
public init(username: String, password: String) {
type = .client(username: username, password: password)
}
public func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
switch type {
case .server(let realm, let authenticate):
return try serverRespond(request, chain: chain, realm: realm, authenticate: authenticate)
case .client(let username, let password):
return try clientRespond(request, chain: chain, username: username, password: password)
}
}
public func serverRespond(_ request: Request, chain: Responder, realm: String? = nil, authenticate: (username: String, password: String) throws -> AuthenticationResult) throws -> Response {
var deniedResponse : Response
if let realm = realm {
deniedResponse = Response(status: .unauthorized, headers: ["WWW-Authenticate": ["Basic realm=\"\(realm)\""]])
} else {
deniedResponse = Response(status: .unauthorized)
}
guard let authorization = request.authorization else {
return deniedResponse
}
let tokens = authorization.split(separator: " ")
guard tokens.count == 2 || tokens.first == "Basic" else {
return deniedResponse
}
let decodedData = try Base64.decode(tokens[1])
let decodedCredentials = try String(data: decodedData)
let credentials = decodedCredentials.split(separator: ":")
guard credentials.count == 2 else {
return deniedResponse
}
let username = credentials[0]
let password = credentials[1]
switch try authenticate(username: username, password: password) {
case .accessDenied:
return deniedResponse
case .authenticated:
return try chain.respond(to: request)
case .payload(let key, let value):
var request = request
request.storage[key] = value
return try chain.respond(to: request)
}
}
public func clientRespond(_ request: Request, chain: Responder, username: String, password: String) throws -> Response {
var request = request
let credentials = Base64.encode("\(username):\(password)")
request.authorization = "Basic \(credentials))"
return try chain.respond(to: request)
}
}
|
mit
|
3f12caf0dc80c70f13015426ae3bbe16
| 38.679245 | 193 | 0.680219 | 4.806857 | false | false | false | false |
wqhiOS/WeiBo
|
WeiBo/WeiBo/AppDelegate.swift
|
1
|
2871
|
//
// AppDelegate.swift
// WeiBo
//
// Created by wuqh on 2017/6/12.
// Copyright © 2017年 吴启晗. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultViewController: UIViewController {
let isLogin = UserAccountTool.shareInstance.isLogin
return isLogin ? WelcomeViewController() : UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// window = UIWindow(frame: UIScreen.main.bounds)
// window?.backgroundColor = UIColor.lightGray
// window?.rootViewController = MainViewController()
// window?.makeKeyAndVisible()
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = defaultViewController
window?.makeKeyAndVisible()
UINavigationBar.appearance().tintColor = UIColor.orange
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:.
}
}
|
mit
|
48ce08ccc0797ef3e34ca16f69ba31a4
| 45.16129 | 285 | 0.730608 | 5.689861 | false | false | false | false |
Kawoou/KWDrawerController
|
Example/LeftMotionViewController.swift
|
1
|
7004
|
//
// LeftMotionViewController.swift
// KWDrawerController
//
// Created by Kawoou on 2017. 2. 10..
// Copyright © 2017년 Kawoou. All rights reserved.
//
import UIKit
class LeftMotionViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var animator: UIPickerView!
@IBOutlet weak var transition: UIPickerView!
@IBOutlet weak var overflowTransition: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
animator.delegate = self
animator.dataSource = self
transition.delegate = self
transition.dataSource = self
overflowTransition.delegate = self
overflowTransition.dataSource = self
animator.selectRow(1, inComponent: 0, animated: false)
transition.selectRow(0, inComponent: 0, animated: false)
overflowTransition.selectRow(1, inComponent: 0, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch pickerView {
case self.animator:
return 13
default:
return 7
}
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch pickerView {
case self.animator:
switch row {
case 0: return "Linear"
case 1: return "Curve Ease"
case 2: return "Spring"
case 3: return "Quad Ease"
case 4: return "Cubic Ease"
case 5: return "Quart Ease"
case 6: return "Quint Ease"
case 7: return "Sine Ease"
case 8: return "Circ Ease"
case 9: return "Expo Ease"
case 10: return "Elastic Ease"
case 11: return "Back Ease"
case 12: return "Bounce Ease"
default: return ""
}
case self.transition:
switch row {
case 0: return "Slide"
case 1: return "Scale"
case 2: return "Float"
case 3: return "Fold"
case 4: return "Parallax"
case 5: return "Swing"
case 6: return "Zoom"
default: return ""
}
case self.overflowTransition:
switch row {
case 0: return "Slide"
case 1: return "Scale"
case 2: return "Float"
case 3: return "Fold"
case 4: return "Parallax"
case 5: return "Swing"
case 6: return "Zoom"
default: return ""
}
default:
return ""
}
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch pickerView {
case self.animator:
switch row {
case 0:
self.drawerController?.setAnimator(animator: DrawerLinearAnimator(), side: .left)
case 1:
self.drawerController?.setAnimator(animator: DrawerCurveEaseAnimator(), side: .left)
case 2:
self.drawerController?.setAnimator(animator: DrawerSpringAnimator(), side: .left)
case 3:
self.drawerController?.setAnimator(animator: DrawerQuadEaseAnimator(), side: .left)
case 4:
self.drawerController?.setAnimator(animator: DrawerCubicEaseAnimator(), side: .left)
case 5:
self.drawerController?.setAnimator(animator: DrawerQuartEaseAnimator(), side: .left)
case 6:
self.drawerController?.setAnimator(animator: DrawerQuintEaseAnimator(), side: .left)
case 7:
self.drawerController?.setAnimator(animator: DrawerSineEaseAnimator(), side: .left)
case 8:
self.drawerController?.setAnimator(animator: DrawerCircEaseAnimator(), side: .left)
case 9:
self.drawerController?.setAnimator(animator: DrawerExpoEaseAnimator(), side: .left)
case 10:
self.drawerController?.setAnimator(animator: DrawerElasticEaseAnimator(), side: .left)
case 11:
self.drawerController?.setAnimator(animator: DrawerBackEaseAnimator(), side: .left)
case 12:
self.drawerController?.setAnimator(animator: DrawerBounceEaseAnimator(), side: .left)
default: break
}
case self.transition:
self.overflowTransition.selectRow(row, inComponent: 0, animated: true)
self.pickerView(self.overflowTransition, didSelectRow: row, inComponent: 0)
switch row {
case 0:
self.drawerController?.setTransition(transition: DrawerSlideTransition(), side: .left)
case 1:
self.drawerController?.setTransition(transition: DrawerScaleTransition(), side: .left)
case 2:
self.drawerController?.setTransition(transition: DrawerFloatTransition(), side: .left)
case 3:
self.drawerController?.setTransition(transition: DrawerFoldTransition(), side: .left)
case 4:
self.drawerController?.setTransition(transition: DrawerParallaxTransition(), side: .left)
case 5:
self.drawerController?.setTransition(transition: DrawerSwingTransition(), side: .left)
case 6:
self.drawerController?.setTransition(transition: DrawerZoomTransition(), side: .left)
default: break
}
case self.overflowTransition:
switch row {
case 0:
self.drawerController?.setOverflowTransition(transition: DrawerSlideTransition(), side: .left)
case 1:
self.drawerController?.setOverflowTransition(transition: DrawerScaleTransition(), side: .left)
case 2:
self.drawerController?.setOverflowTransition(transition: DrawerFloatTransition(), side: .left)
case 3:
self.drawerController?.setOverflowTransition(transition: DrawerFoldTransition(), side: .left)
case 4:
self.drawerController?.setOverflowTransition(transition: DrawerParallaxTransition(), side: .left)
case 5:
self.drawerController?.setOverflowTransition(transition: DrawerSwingTransition(), side: .left)
case 6:
self.drawerController?.setOverflowTransition(transition: DrawerZoomTransition(), side: .left)
default: break
}
default: break
}
}
}
|
mit
|
60e7dfc113f4c317042e6e028fe71b74
| 38.331461 | 118 | 0.585345 | 5.228529 | false | false | false | false |
V3ronique/TailBook
|
TailBook/TailBook/FriendshipTableViewController.swift
|
1
|
1506
|
//
// FriendshipTableViewController.swift
// TailBook
//
// Created by Roni Beberoni on 2/6/16.
// Copyright © 2016 Veronica. All rights reserved.
//
import UIKit
class FriendshipTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let recognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeLeft:")
recognizer.direction = .Left
self.view .addGestureRecognizer(recognizer)
let secondRecognizer : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeRight:")
secondRecognizer.direction = .Right
self.view.addGestureRecognizer(secondRecognizer)
self.navigationController?.navigationBarHidden = true;
}
func swipeLeft(recognizer : UISwipeGestureRecognizer) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("requests") as! RequestTableViewController
self.presentViewController(vc, animated: true, completion: nil)
}
func swipeRight(recognizer : UISwipeGestureRecognizer) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("Album") as! AlbumPageContentTableViewController
self.presentViewController(vc, animated: true, completion: nil)
}
}
|
mit
|
97f53b6c84ac9017e50a4250d52707f0
| 37.589744 | 119 | 0.72691 | 5.299296 | false | false | false | false |
A-Kod/vkrypt
|
Pods/SwiftyVK/Library/Sources/Networking/Cookies/CookiesHolder.swift
|
2
|
1484
|
protocol CookiesHolder {
func replace(for session: String, url: URL)
func restore(for url: URL)
func save(for session: String, url: URL)
func remove(for sessionId: String)
}
final class CookiesHolderImpl: CookiesHolder {
private let vkStorage: CookiesStorage
private let sharedStorage: VKHTTPCookieStorage
private var originalCookies: [HTTPCookie]?
init(
vkStorage: CookiesStorage,
sharedStorage: VKHTTPCookieStorage
) {
self.vkStorage = vkStorage
self.sharedStorage = sharedStorage
}
func replace(for sessionId: String, url: URL) {
originalCookies = sharedStorage.cookies(for: url)
guard let cookies = vkStorage.getFor(sessionId: sessionId) else { return }
sharedStorage.setCookies(cookies, for: url, mainDocumentURL: nil)
}
func restore(for url: URL) {
guard let originalCookies = originalCookies else { return }
sharedStorage.setCookies(originalCookies, for: url, mainDocumentURL: nil)
}
func save(for sessionId: String, url: URL) {
guard let cookies = sharedStorage.cookies(for: url) else { return }
try? vkStorage.save(cookies, for: sessionId)
}
func remove(for sessionId: String) {
guard let cookies = vkStorage.getFor(sessionId: sessionId) else { return }
cookies.forEach { sharedStorage.deleteCookie($0) }
vkStorage.removeFor(sessionId: sessionId)
}
}
|
apache-2.0
|
72d5a06c263c4b581f4e320daf759686
| 32.727273 | 82 | 0.66779 | 4.456456 | false | false | false | false |
alex-heritier/jury_app
|
jury-ios/Jury/YourJuriesViewController.swift
|
1
|
3038
|
//
// YourJuriesViewController.swift
// Jury
//
// Created by Keegan Papakipos on 1/30/16.
// Copyright © 2016 kpapakipos. All rights reserved.
//
import UIKit
class YourJuriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let myAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var jurorCallback: JurorCallback!
@IBOutlet var tableView: UITableView!
var caseArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 90.0
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
jurorCallback = JurorCallback(owner: self)
myAppDelegate.networkingController.askForJurorCases(jurorCallback)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return caseArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CaseTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("caseCell")! as! CaseTableViewCell
cell.titleField.text = ((caseArray[indexPath.row] as! NSDictionary)["prosecutor"] as! String) + " v. " +
((caseArray[indexPath.row] as! NSDictionary)["defender"] as! String)
cell.descriptionField.text = (caseArray[indexPath.row] as! NSDictionary)["description"] as! String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("caseDetailSegue", sender: self)
}
func setDataForTable(data: NSArray) {
caseArray = data
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "caseDetailSegue" {
let indexRow = self.tableView.indexPathForSelectedRow!.row
let detailView = segue.destinationViewController as! CaseDetailViewController
detailView.prosecutorIn = (caseArray[indexRow] as! NSDictionary)["prosecutor"] as? String
detailView.defendantIn = (caseArray[indexRow] as! NSDictionary)["defender"] as? String
detailView.descriptionIn = (caseArray[indexRow] as! NSDictionary)["description"] as? String
detailView.voteID = Int(((caseArray[indexRow] as! NSDictionary)["vote_id"] as? String)!)
detailView.caseID = Int(((caseArray[indexRow] as! NSDictionary)["id"] as? String)!)
}
}
}
|
mit
|
c76cbe18f4e748d22767c24507486798
| 37.935897 | 121 | 0.672703 | 4.922204 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Features/Filter by definition expression or display filter/DefinitionExpressionDisplayFilterViewController.swift
|
1
|
4565
|
// Copyright 2022 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
import ArcGIS
class DefinitionExpressionDisplayFilterViewController: UIViewController {
@IBOutlet var mapView: AGSMapView! {
didSet {
// Assign the map to the map view's map.
mapView.map = makeMap()
}
}
/// The URL to the feature service, tracking incidents in San Francisco.
static let featureServiceURL = URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/SF_311_Incidents/FeatureServer/0")!
/// The feature layer made with the feature service URL.
let featureLayer = AGSFeatureLayer(featureTable: AGSServiceFeatureTable(url: featureServiceURL))
/// The display filter definition to apply to the feature layer.
var displayFilterDefinition: AGSDisplayFilterDefinition?
/// The definition expression to apply to the feature layer.
var definitionExpression: String = ""
/// Applies the definition expression.
@IBAction func applyDefinitionExpression() {
// Set the definition expression.
displayFilterDefinition = nil
definitionExpression = "req_Type = 'Tree Maintenance or Damage'"
showFeatureCount()
}
/// Applies the display filter
@IBAction func applyFilter() {
definitionExpression = ""
// Create a display filter with a name and an SQL expression.
guard let damagedTrees = AGSDisplayFilter(name: "Damaged Trees", whereClause: "req_type LIKE '%Tree Maintenance%'") else { return }
// Set the manual display filter definition using the display filter.
let manualDisplayFilterDefinition = AGSManualDisplayFilterDefinition(activeFilter: damagedTrees, availableFilters: [damagedTrees])
// Apply the display filter definition.
displayFilterDefinition = manualDisplayFilterDefinition
showFeatureCount()
}
/// Reset the definition expression.
@IBAction func resetDefinitionExpression() {
definitionExpression = ""
displayFilterDefinition = nil
showFeatureCount()
}
/// Create a map and set its attributes.
func makeMap() -> AGSMap {
// Initialize the map with the topographic basemap style.
let map = AGSMap(basemapStyle: .arcGISTopographic)
// Set the initial viewpoint.
let viewpoint = AGSViewpoint(latitude: 37.772296660953138, longitude: -122.44014487516885, scale: 100_000)
map.initialViewpoint = viewpoint
// Add the feature layer to the map's operational layers.
map.operationalLayers.add(featureLayer)
return map
}
/// Count the features according to the applied expressions.
func showFeatureCount() {
// Set the extent to the current view.
let extent = mapView.currentViewpoint(with: .boundingGeometry)?.targetGeometry.extent
// Create the query parameters and set its geometry.
let queryParameters = AGSQueryParameters()
queryParameters.geometry = extent
// Apply the expressions to the feature layer.
featureLayer.displayFilterDefinition = displayFilterDefinition
featureLayer.definitionExpression = definitionExpression
// Query the feature count using the parameters.
featureLayer.featureTable?.queryFeatureCount(with: queryParameters) { [weak self] count, error in
guard let self = self else { return }
if let error = error {
self.presentAlert(error: error)
} else {
// Present the current feature count.
self.presentAlert(title: "Current feature count", message: "\(count) features")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["DefinitionExpressionDisplayFilterViewController"]
}
}
|
apache-2.0
|
18f51ac096ccea1de8f718fa210418a4
| 43.754902 | 150 | 0.688061 | 4.924488 | false | false | false | false |
hanhailong/practice-swift
|
Views/PageViewController/PageViewControllerTutorial/PageViewControllerTutorial/ViewController.swift
|
2
|
3819
|
//
// ViewController.swift
// PageViewControllerTutorial
//
// Created by Domenico on 06/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageTitles = ["Title 1", "Title 2", "Title 3", "Title 4"]
var images = ["1","2","3","4"]
var count = 0
var pageViewController : UIPageViewController!
@IBAction func swipeLeft(sender: AnyObject) {
println("SWipe left")
}
@IBAction func swiped(sender: AnyObject) {
self.pageViewController.view .removeFromSuperview()
self.pageViewController.removeFromParentViewController()
reset()
}
func reset() {
/* Getting the page View controller */
pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let pageContentViewController = self.viewControllerAtIndex(0)
self.pageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
/* We are substracting 30 because we have a start again button whose height is 30*/
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height - 30)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
@IBAction func start(sender: AnyObject) {
let pageContentViewController = self.viewControllerAtIndex(0)
self.pageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
reset()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
index++
if(index >= self.images.count){
return nil
}
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
if(index <= 0){
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as! PageContentViewController
pageContentViewController.imageName = self.images[index]
pageContentViewController.titleText = self.pageTitles[index]
pageContentViewController.pageIndex = index
return pageContentViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
|
mit
|
1dea63b3926b3bd77ae0eb5dabe32b4c
| 36.811881 | 173 | 0.699921 | 5.893519 | false | false | false | false |
melling/ios_topics
|
ButtonsInStackView/ButtonsInStackView/ViewController.swift
|
1
|
3954
|
//
// ViewController.swift
// ButtonsInStackView
//
// Created by Michael Mellinger on 5/31/16.
//
import UIKit
class ViewController: UIViewController {
private let button1 = UIButton()
private let button2 = UIButton()
private let button3 = UIButton()
private let button4 = UIButton()
private let label = UILabel()
@objc private func buttonAction(_ button: UIButton) {
let tag = button.tag
label.text = "\(tag)"
}
// MARK: - Build View
private func customizeButtons() {
// Button 1
button1.setTitle("cornerRadius = 10", for: .normal)
button1.titleLabel?.font = UIFont.systemFont(ofSize: 24)
button1.backgroundColor = .blue
button1.layer.cornerRadius = 10
button1.setTitleColor(UIColor.white, for: .normal)
button1.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// Button 2
button2.setTitle("Border", for: .normal)
button2.backgroundColor = .gray
button2.layer.borderWidth = 3
button2.layer.borderColor = UIColor.black.cgColor
button2.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// Button 3
button3.backgroundColor = .gray
button3.setTitle("Custom Font", for: .normal)
button3.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
let fontSize:CGFloat = 20
let aFontName = "American Typewriter"
if let aFont = UIFont(name: aFontName, size: fontSize) {
button3.titleLabel?.font = aFont
}
// Button 4
button4.backgroundColor = .gray
button4.setTitle("Image", for: .normal)
button4.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
let imageName = "star"
if let image = UIImage(named: imageName) {
button4.setImage(image, for: .normal)
}
}
private func createLabel() {
let fontSize:CGFloat = 24
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: fontSize)
label.text = "0"
view.addSubview(label)
}
private func buildView() {
let allButtons = [button1, button2, button3, button4]
var i = 1
allButtons.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.tag = i
i += 1
view.addSubview($0)
}
customizeButtons()
createLabel()
let stackView = UIStackView(arrangedSubviews: allButtons)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 10 // Space between buttons
view.addSubview(stackView)
// Center vertically, iOS9 style
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 20),
stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -20),
// Label
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 50.0),
])
}
// MARK: - View Management
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(named: "AppleBookColor")
buildView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
cc0-1.0
|
0ce3573c6c3a42cbbdd5180e991b2b9e
| 28.507463 | 94 | 0.600152 | 4.986129 | false | false | false | false |
kello711/HackingWithSwift
|
project29/Project29/GameScene.swift
|
1
|
6539
|
//
// GameScene.swift
// Project29
//
// Created by Hudzilla on 17/09/2015.
// Copyright (c) 2015 Paul Hudson. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
weak var viewController: GameViewController!
var buildings = [BuildingNode]()
var player1: SKSpriteNode!
var player2: SKSpriteNode!
var banana: SKSpriteNode!
var currentPlayer = 1
override func didMoveToView(view: SKView) {
backgroundColor = UIColor(hue: 0.669, saturation: 0.99, brightness: 0.67, alpha: 1)
createBuildings()
createPlayers()
physicsWorld.contactDelegate = self
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func update(currentTime: CFTimeInterval) {
if banana != nil {
if banana.position.y < -1000 {
banana.removeFromParent()
banana = nil
changePlayer()
}
}
}
func createBuildings() {
var currentX: CGFloat = -15
while currentX < 1024 {
let size = CGSize(width: RandomInt(min: 2, max: 4) * 40, height: RandomInt(min: 300, max: 600))
currentX += size.width + 2
let building = BuildingNode(color: UIColor.redColor(), size: size)
building.position = CGPoint(x: currentX - (size.width / 2), y: size.height / 2)
building.setup()
addChild(building)
buildings.append(building)
}
}
func launch(angle angle: Int, velocity: Int) {
// 1
let speed = Double(velocity) / 10.0
// 2
let radians = deg2rad(angle)
// 3
if banana != nil {
banana.removeFromParent()
banana = nil
}
banana = SKSpriteNode(imageNamed: "banana")
banana.name = "banana"
banana.physicsBody = SKPhysicsBody(circleOfRadius: banana.size.width / 2)
banana.physicsBody!.categoryBitMask = CollisionTypes.Banana.rawValue
banana.physicsBody!.collisionBitMask = CollisionTypes.Building.rawValue | CollisionTypes.Player.rawValue
banana.physicsBody!.contactTestBitMask = CollisionTypes.Building.rawValue | CollisionTypes.Player.rawValue
banana.physicsBody!.usesPreciseCollisionDetection = true
addChild(banana)
if currentPlayer == 1 {
// 4
banana.position = CGPoint(x: player1.position.x - 30, y: player1.position.y + 40)
banana.physicsBody!.angularVelocity = -20
// 5
let raiseArm = SKAction.setTexture(SKTexture(imageNamed: "player1Throw"))
let lowerArm = SKAction.setTexture(SKTexture(imageNamed: "player"))
let pause = SKAction.waitForDuration(0.15)
let sequence = SKAction.sequence([raiseArm, pause, lowerArm])
player1.runAction(sequence)
// 6
let impulse = CGVector(dx: cos(radians) * speed, dy: sin(radians) * speed)
banana.physicsBody?.applyImpulse(impulse)
} else {
// 7
banana.position = CGPoint(x: player2.position.x + 30, y: player2.position.y + 40)
banana.physicsBody!.angularVelocity = 20
let raiseArm = SKAction.setTexture(SKTexture(imageNamed: "player2Throw"))
let lowerArm = SKAction.setTexture(SKTexture(imageNamed: "player"))
let pause = SKAction.waitForDuration(0.15)
let sequence = SKAction.sequence([raiseArm, pause, lowerArm])
player2.runAction(sequence)
let impulse = CGVector(dx: cos(radians) * -speed, dy: sin(radians) * speed)
banana.physicsBody?.applyImpulse(impulse)
}
}
func createPlayers() {
player1 = SKSpriteNode(imageNamed: "player")
player1.name = "player1"
player1.physicsBody = SKPhysicsBody(circleOfRadius: player1.size.width / 2)
player1.physicsBody!.categoryBitMask = CollisionTypes.Player.rawValue
player1.physicsBody!.collisionBitMask = CollisionTypes.Banana.rawValue
player1.physicsBody!.contactTestBitMask = CollisionTypes.Banana.rawValue
player1.physicsBody!.dynamic = false
let player1Building = buildings[1]
player1.position = CGPoint(x: player1Building.position.x, y: player1Building.position.y + ((player1Building.size.height + player1.size.height) / 2))
addChild(player1)
player2 = SKSpriteNode(imageNamed: "player")
player2.name = "player2"
player2.physicsBody = SKPhysicsBody(circleOfRadius: player2.size.width / 2)
player2.physicsBody!.categoryBitMask = CollisionTypes.Player.rawValue
player2.physicsBody!.collisionBitMask = CollisionTypes.Banana.rawValue
player2.physicsBody!.contactTestBitMask = CollisionTypes.Banana.rawValue
player2.physicsBody!.dynamic = false
let player2Building = buildings[buildings.count - 2]
player2.position = CGPoint(x: player2Building.position.x, y: player2Building.position.y + ((player2Building.size.height + player2.size.height) / 2))
addChild(player2)
}
func deg2rad(degrees: Int) -> Double {
return Double(degrees) * M_PI / 180.0
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if let firstNode = firstBody.node {
if let secondNode = secondBody.node {
if firstNode.name == "banana" && secondNode.name == "building" {
bananaHitBuilding(secondNode as! BuildingNode, atPoint: contact.contactPoint)
}
if firstNode.name == "banana" && secondNode.name == "player1" {
destroyPlayer(player1)
}
if firstNode.name == "banana" && secondNode.name == "player2" {
destroyPlayer(player2)
}
}
}
}
func destroyPlayer(player: SKSpriteNode) {
let explosion = SKEmitterNode(fileNamed: "hitPlayer")!
explosion.position = player.position
addChild(explosion)
player.removeFromParent()
banana?.removeFromParent()
RunAfterDelay(2) { [unowned self] in
let newGame = GameScene(size: self.size)
newGame.viewController = self.viewController
self.viewController.currentGame = newGame
self.changePlayer()
newGame.currentPlayer = self.currentPlayer
let transition = SKTransition.doorwayWithDuration(1.5)
self.view?.presentScene(newGame, transition: transition)
}
}
func changePlayer() {
if currentPlayer == 1 {
currentPlayer = 2
} else {
currentPlayer = 1
}
viewController.activatePlayerNumber(currentPlayer)
}
func bananaHitBuilding(building: BuildingNode, atPoint contactPoint: CGPoint) {
let buildingLocation = convertPoint(contactPoint, toNode: building)
building.hitAtPoint(buildingLocation)
let explosion = SKEmitterNode(fileNamed: "hitBuilding")!
explosion.position = contactPoint
addChild(explosion)
banana.name = ""
banana?.removeFromParent()
banana = nil
changePlayer()
}
}
|
unlicense
|
1af6c6fd4e7b7212ffc6a6fa1a1ba64c
| 28.722727 | 150 | 0.726564 | 3.706916 | false | false | false | false |
PFei-He/PFSwift
|
PFSwift/PFView.swift
|
1
|
5386
|
//
// PFView.swift
// PFSwift
//
// Created by PFei_He on 15/11/17.
// Copyright © 2015年 PF-Lib. All rights reserved.
//
// https://github.com/PFei-He/PFSwift
//
// 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.
//
// ***** UIView扩展 *****
//
import UIKit
extension UIView {
// MARK: - ORIGIN
///坐标
public var origin: CGPoint {
get {
return frame.origin
} set {
var frame = self.frame
frame.origin = newValue
self.frame = frame
}
}
///X坐标
public var x: CGFloat {
get {
return frame.origin.x
} set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
///Y坐标
public var y: CGFloat {
get {
return frame.origin.y
} set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
// MARK: - SIZE
///尺寸
public var size: CGSize {
get {
return frame.size
} set {
var frame = self.frame
frame.size = newValue
self.frame = frame
}
}
///宽
public var width: CGFloat {
get {
return frame.width
} set {
var frame = self.frame
frame.size.width = newValue
self.frame = frame
}
}
///高
public var height: CGFloat {
get {
return frame.height
} set {
var frame = self.frame
frame.size.height = newValue
self.frame = frame
}
}
//MARK: - POSITION
///方位
public var position: CGPoint {
get {
return frame.origin
} set {
var frame = self.frame
frame.origin = newValue
self.frame = frame
}
}
///上边缘
public var top: CGFloat {
get {
return frame.origin.y
} set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
///左边缘
public var left: CGFloat {
get {
return frame.origin.x
} set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
///下边缘
public var bottom: CGFloat {
get {
return frame.origin.y + frame.size.height
} set {
var frame = self.frame
frame.origin.y = newValue - frame.size.height
self.frame = frame
}
}
///右边缘
public var right: CGFloat {
get {
return frame.origin.x + frame.size.width
} set {
var frame = self.frame
frame.origin.x = newValue - frame.size.width
self.frame = frame
}
}
// MARK: - CENTER
///中心点
public var boundsCenter: CGPoint {
get {
return CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
}
}
///中心点的X坐标
public var centerX: CGFloat {
get {
return center.x
} set {
var center = self.center
center.x = newValue
self.center = center
}
}
///中心点的Y坐标
public var centerY: CGFloat {
get {
return center.y
} set {
var center = self.center
center.y = newValue
self.center = center
}
}
// MARK: - OFFSET
///位移
public var offset: CGPoint {
get {
var point = CGPointZero
var view = self
point.x += view.frame.origin.x
point.y += view.frame.origin.y
view = view.superview!
return point
} set {
var view = self
var point = newValue
point.x += view.superview!.frame.origin.x
point.y += view.superview!.frame.origin.y
view = view.superview!
var frame = self.frame
frame.origin = point
self.frame = frame
}
}
}
|
mit
|
845949bb6691e876d060c9aa4567b687
| 23.523148 | 81 | 0.511799 | 4.500425 | false | false | false | false |
Majirefy/BingPaper
|
BingPaper/StatusBarView.swift
|
1
|
1951
|
//
// StatusBarView.swift
// BingPaper
//
// Created by Peng Jingwen on 2015-03-13.
// Copyright (c) 2015 Peng Jingwen. All rights reserved.
//
import Cocoa
class StatusBarView: NSView {
private let image: NSImage
private let statusItem: NSStatusItem
private let popover: NSPopover
private var popoverTransiencyMonitor: AnyObject?
init(image: NSImage, statusItem: NSStatusItem, popover: NSPopover){
self.image = image
self.statusItem = statusItem
self.popover = popover
self.popoverTransiencyMonitor = nil
let thickness = NSStatusBar.systemStatusBar().thickness
let rect = CGRectMake(0, 0, thickness, thickness)
super.init(frame: rect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(dirtyRect: NSRect){
self.statusItem.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: false)
let size = self.image.size
let rect = CGRectMake(2, 2, size.width, size.height)
self.image.drawInRect(rect)
}
override func mouseDown(theEvent: NSEvent){
if (self.popoverTransiencyMonitor == nil) {
self.popover.showRelativeToRect(self.frame, ofView: self, preferredEdge: NSMinYEdge)
self.popoverTransiencyMonitor = NSEvent.addGlobalMonitorForEventsMatchingMask(
NSEventMask.LeftMouseUpMask, handler: { (event: NSEvent!) -> Void in
NSEvent.removeMonitor(self.popoverTransiencyMonitor!)
self.popoverTransiencyMonitor = nil
self.popover.close()
})
} else {
NSEvent.removeMonitor(self.popoverTransiencyMonitor!)
self.popoverTransiencyMonitor = nil
self.popover.close()
}
}
}
|
gpl-3.0
|
547d5d72d068e89c6db71999b333b128
| 29.030769 | 96 | 0.618657 | 4.865337 | false | false | false | false |
tapemaster/kswitcher
|
wm2/AppDelegate.swift
|
1
|
913
|
import Cocoa
import Carbon
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow?
@IBOutlet var parentView: NSView?
@IBOutlet var menu: NSMenu?
var statusItem: NSStatusItem?
@objc let keyHandler = KeyHandler()
override init() {
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
//WM2Helper.requestAccessibility()
WM2Helper.setupWindow(window)
keyHandler.setWindow(window!)
keyHandler.setupView(parentView!)
statusItem = NSStatusBar.system.statusItem(withLength: -1)
statusItem!.menu = menu
statusItem!.image = Bundle.main.image(forResource: "icon")
statusItem!.highlightMode = true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
|
mit
|
b0f09d48d17ed4d2d2af5a7fb9374b26
| 25.852941 | 71 | 0.659365 | 5.217143 | false | false | false | false |
apple/swift-lldb
|
packages/Python/lldbsuite/test/lang/swift/stepping/main.swift
|
2
|
5838
|
// main.swift
//
// 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
//
// -----------------------------------------------------------------------------
class ClassA
{
var x : Int
var y : Float
init (_ input : Int) // Here is the A constructor.
{
x = input // A init: x assignment.
y = Float(input) + 0.5 // A init: y assignment.
} // A init: end of function.
init (_ input : Float)
{
x = Int(input)
y = input
}
func do_something (_ input: Int) -> Int
{
if (input > 0) // A.do_something - step in should stop here
{
return x * input
}
else
{
return -x * input
}
}
}
class ClassB : ClassA
{
override init (_ input : Int) // At the first line of B constructor.
{
super.init (input) // In the B constructor about to call super.
}
override func do_something (_ input: Int) -> Int
{
var decider : Bool
decider = input % 2 == 0
if decider
{
return super.do_something(input) // B.do_something: Step into super from here
}
else
{
return 0
}
}
}
func call_overridden (_ class_a_object : ClassA, _ int_arg : Int) -> Int // call_overridden func def
{
return class_a_object.do_something(int_arg)
}
enum SomeValues : Equatable
{
case Five
case Six
case Eleven
case AnyValue
}
func == (lhs: SomeValues, rhs: SomeValues) -> Bool
{
switch (lhs, rhs)
{
case (.Five, .Five),
(.Six, .Six),
(.Eleven, .Eleven):
return true
case (_, _):
return false
}
}
extension Int
{
func toSomeValues() -> SomeValues
{
switch self
{
case 5:
return .Five
case 6:
return .Six
case 11:
return .Eleven
case _:
return .AnyValue
}
}
}
extension SomeValues
{
func toInt() -> Int
{
switch self
{
case .Five:
return 5
case .Six:
return 6
case .Eleven:
return 11
case .AnyValue:
return 46
}
}
}
protocol P
{
func protocol_func(_ arg : Int) -> Int
}
class ConformsDirectly : P
{
var m_value : Int
init()
{
m_value = 64
}
init (_ value : Int)
{
m_value = value
}
func protocol_func(_ actual_arg : Int) -> Int // We stopped at the protocol_func declaration instead.
{
print("protocol_func(Int) from A: \(actual_arg).") // This is where we will stop in the protocol dispatch
return m_value + actual_arg
}
}
class ConformsIndirectly : ConformsDirectly
{
override init ()
{
super.init(32)
}
}
func main () -> Void
{
var some_values : SomeValues = 5.toSomeValues() // Stop here first in main
var other_values : SomeValues = .Eleven
if some_values == other_values // Stop here to get into equality
{
print ("I should not get here.")
}
else
{
print ("I should get here.") // Step over the if should get here
} // Step over the print should get here.
var b_object = ClassB(20) // Stop here to step into B constructor.
var do_something_result = call_overridden (b_object, 30) // Stop here to step into call_overridden.
var point = (1, -1) // At point initializer.
func return_same (_ input : Int) -> Int
{
return input; // return_same gets called in both where statements
}
switch point // At the beginning of the switch.
{
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(point.0), 0) is on the x-axis")
case (0, _):
print("(0, \(point.1)) is on the y-axis")
case (let x, let y) where
return_same(x) == return_same(y): // First case with a where statement.
print("(\(x), \(y)) is on the line x == y")
case (let x, let y) where // Sometimes the line table steps to here after the body of the case.
return_same(x) == -return_same(y): // Second case with a where statement.
print("(\(x), \(y)) is on the line x == -y") // print in second case with where statement.
case (let x, let y):
print("Position is: (\(x), \(y))")
} // This is the end of the switch statement
var direct : P = ConformsDirectly() // Make a version of P that conforms directly
direct.protocol_func(10)
var indirect : P = ConformsIndirectly() // Make a version of P that conforms through a subclass
indirect.protocol_func(20)
var cd_maker =
{
(arg : Int) -> ConformsDirectly in // Step into cd_maker stops at closure decl instead.
return ConformsDirectly(arg) // Step into should stop here in closure.
}
func doSomethingWithFunction<Result : P> (_ f: (_ arg : Int)->Result, _ other_value : Int) -> Result // Stopped in doSomethingWithFunctionResult decl.
{
print("Calling doSomethingWithFunction with value \(other_value)")
let result = f(other_value)
result.protocol_func(other_value)
print ("Done calling doSomethingWithFunction.")
return result
}
doSomethingWithFunction(cd_maker, 10)
}
main()
|
apache-2.0
|
d621e8bd940412445d3b333d88856e33
| 24.831858 | 155 | 0.535115 | 4.059805 | false | false | false | false |
TinyDragonApps/Usages
|
Stats/AppDelegate.swift
|
1
|
3349
|
//
// AppDelegate.swift
// Stats
//
// Created by Joseph Pintozzi on 9/28/14.
// Copyright (c) 2014 Tiny Dragon Apps. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
|
gpl-2.0
|
4d3e1662c430b903923f9aa3effeb02b
| 52.15873 | 285 | 0.75097 | 6.248134 | false | false | false | false |
google/iosched-ios
|
Source/IOsched/Screens/Onboarding/OnboardingViewModel.swift
|
1
|
1935
|
//
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MaterialComponents
import FirebaseAuth
import GoogleSignIn
class OnboardingViewModel {
// MARK: - Dependencies
private var navigator: OnboardingNavigator?
private let notificationPermissions: NotificationPermissions
private let serviceLocator: ServiceLocator
init(serviceLocator: ServiceLocator,
navigator: OnboardingNavigator) {
self.navigator = navigator
self.serviceLocator = serviceLocator
self.notificationPermissions = NotificationPermissions(userState: serviceLocator.userState,
application: .shared)
}
// MARK: - Actions
func navigateToSchedule() {
navigator?.navigateToSchedule()
}
func signInSuccessful(user: GIDGoogleUser) {
serviceLocator.updateConferenceData { }
navigator?.showLoginSuccessfulMessage(user: user)
}
func signInFailed(withError error: Error) {
let nserror = error as NSError
let errorCode = GIDSignInErrorCode(rawValue: nserror.code)
if errorCode != .canceled {
navigator?.showLoginFailedMessage()
}
}
func finishOnboardingFlow() {
serviceLocator.userState.setOnboardingCompleted(true)
notificationPermissions.setNotificationsEnabled(true) { (_) in }
navigator?.navigateToMainNavigation()
navigator = nil
}
}
|
apache-2.0
|
b2fee2d6e44496f6845290e66f1ff1cf
| 29.234375 | 95 | 0.724548 | 4.8375 | false | false | false | false |
cikelengfeng/Jude
|
Jude/Antlr4/atn/LL1Analyzer.swift
|
2
|
10569
|
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
public class LL1Analyzer {
/// Special value added to the lookahead sets to indicate that we hit
/// a predicate during analysis if {@code seeThruPreds==false}.
public let HIT_PRED: Int = CommonToken.INVALID_TYPE
public let atn: ATN
public init(_ atn: ATN) {
self.atn = atn
}
/// Calculates the SLL(1) expected lookahead set for each outgoing transition
/// of an {@link org.antlr.v4.runtime.atn.ATNState}. The returned array has one element for each
/// outgoing transition in {@code s}. If the closure from transition
/// <em>i</em> leads to a semantic predicate before matching a symbol, the
/// element at index <em>i</em> of the result will be {@code null}.
///
/// - parameter s: the ATN state
/// - returns: the expected symbols for each outgoing transition of {@code s}.
public func getDecisionLookahead(_ s: ATNState?) throws -> [IntervalSet?]? {
// print("LOOK("+s.stateNumber+")");
guard let s = s else {
return nil
}
let length = s.getNumberOfTransitions()
var look: [IntervalSet?] = [IntervalSet?](repeating: nil, count: length)
//new IntervalSet[s.getNumberOfTransitions()];
for alt in 0..<length {
look[alt] = try IntervalSet()
var lookBusy: Set<ATNConfig> = Set<ATNConfig>()
let seeThruPreds: Bool = false // fail to get lookahead upon pred
try _LOOK(s.transition(alt).target, nil, PredictionContext.EMPTY,
look[alt]!, &lookBusy, BitSet(), seeThruPreds, false)
// Wipe out lookahead for this alternative if we found nothing
// or we had a predicate when we !seeThruPreds
if look[alt]!.size() == 0 || look[alt]!.contains(HIT_PRED) {
look[alt] = nil
}
}
return look
}
/// Compute set of tokens that can follow {@code s} in the ATN in the
/// specified {@code ctx}.
///
/// <p>If {@code ctx} is {@code null} and the end of the rule containing
/// {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
/// If {@code ctx} is not {@code null} and the end of the outermost rule is
/// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
///
/// - parameter s: the ATN state
/// - parameter ctx: the complete parser context, or {@code null} if the context
/// should be ignored
///
/// - returns: The set of tokens that can follow {@code s} in the ATN in the
/// specified {@code ctx}.
public func LOOK(_ s: ATNState, _ ctx: RuleContext?) throws -> IntervalSet {
return try LOOK(s, nil, ctx)
}
/// Compute set of tokens that can follow {@code s} in the ATN in the
/// specified {@code ctx}.
///
/// <p>If {@code ctx} is {@code null} and the end of the rule containing
/// {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
/// If {@code ctx} is not {@code null} and the end of the outermost rule is
/// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
///
/// - parameter s: the ATN state
/// - parameter stopState: the ATN state to stop at. This can be a
/// {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
/// - parameter ctx: the complete parser context, or {@code null} if the context
/// should be ignored
///
/// - returns: The set of tokens that can follow {@code s} in the ATN in the
/// specified {@code ctx}.
public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) throws -> IntervalSet {
let r: IntervalSet = try IntervalSet()
let seeThruPreds: Bool = true // ignore preds; get all lookahead
let lookContext: PredictionContext? = ctx != nil ? PredictionContext.fromRuleContext(s.atn!, ctx) : nil
var config = Set<ATNConfig>()
try _LOOK(s, stopState, lookContext,
r, &config, BitSet(), seeThruPreds, true)
return r
}
/// Compute set of tokens that can follow {@code s} in the ATN in the
/// specified {@code ctx}.
///
/// <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
/// rule containing {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to
/// the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
/// {@code true} and {@code stopState} or the end of the outermost rule is
/// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
///
/// - parameter s: the ATN state.
/// - parameter stopState: the ATN state to stop at. This can be a
/// {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
/// - parameter ctx: The outer context, or {@code null} if the outer context should
/// not be used.
/// - parameter look: The result lookahead set.
/// - parameter lookBusy: A set used for preventing epsilon closures in the ATN
/// from causing a stack overflow. Outside code should pass
/// {@code new HashSet<ATNConfig>} for this argument.
/// - parameter calledRuleStack: A set used for preventing left recursion in the
/// ATN from causing a stack overflow. Outside code should pass
/// {@code new BitSet()} for this argument.
/// - parameter seeThruPreds: {@code true} to true semantic predicates as
/// implicitly {@code true} and "see through them", otherwise {@code false}
/// to treat semantic predicates as opaque and add {@link #HIT_PRED} to the
/// result if one is encountered.
/// - parameter addEOF: Add {@link org.antlr.v4.runtime.Token#EOF} to the result if the end of the
/// outermost context is reached. This parameter has no effect if {@code ctx}
/// is {@code null}.
internal func _LOOK(_ s: ATNState,
_ stopState: ATNState?,
_ ctx: PredictionContext?,
_ look: IntervalSet,
_ lookBusy: inout Set<ATNConfig>,
_ calledRuleStack: BitSet,
_ seeThruPreds: Bool, _ addEOF: Bool) throws {
// print ("_LOOK(\(s.stateNumber), ctx=\(ctx)");
//TODO var c : ATNConfig = ATNConfig(s, 0, ctx);
if s.description == "273" {
var s = 0
}
var c: ATNConfig = ATNConfig(s, 0, ctx)
if lookBusy.contains(c) {
return
} else {
lookBusy.insert(c)
}
// if ( !lookBusy.insert (c) ) {
// return;
// }
if s == stopState {
guard let ctx = ctx else {
try look.add(CommonToken.EPSILON)
return
}
if ctx.isEmpty() && addEOF {
try look.add(CommonToken.EOF)
return
}
}
if s is RuleStopState {
guard let ctx = ctx else {
try look.add(CommonToken.EPSILON)
return
}
if ctx.isEmpty() && addEOF {
try look.add(CommonToken.EOF)
return
}
if ctx != PredictionContext.EMPTY {
// run thru all possible stack tops in ctx
let length = ctx.size()
for i in 0..<length {
var returnState: ATNState = atn.states[(ctx.getReturnState(i))]!
var removed: Bool = try calledRuleStack.get(returnState.ruleIndex!)
//TODO try
//try {
try calledRuleStack.clear(returnState.ruleIndex!)
try self._LOOK(returnState, stopState, ctx.getParent(i), look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
//}
defer {
if removed {
try! calledRuleStack.set(returnState.ruleIndex!)
}
}
}
return
}
}
var n: Int = s.getNumberOfTransitions()
for i in 0..<n {
var t: Transition = s.transition(i)
if type(of: t) === RuleTransition.self {
if try calledRuleStack.get((t as! RuleTransition).target.ruleIndex!) {
continue
}
var newContext: PredictionContext =
SingletonPredictionContext.create(ctx, (t as! RuleTransition).followState.stateNumber)
//TODO try
//try {
try calledRuleStack.set((t as! RuleTransition).target.ruleIndex!)
try _LOOK(t.target, stopState, newContext, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
//}
defer {
try! calledRuleStack.clear((t as! RuleTransition).target.ruleIndex!)
}
} else {
if t is AbstractPredicateTransition {
if seeThruPreds {
try _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else {
try look.add(HIT_PRED)
}
} else {
if t.isEpsilon() {
try _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else {
if type(of: t) === WildcardTransition.self {
try look.addAll(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType))
} else {
var set: IntervalSet? = try t.labelIntervalSet()
if set != nil {
if t is NotSetTransition {
set = try set!.complement(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType)) as? IntervalSet
}
try look.addAll(set)
}
}
}
}
}
}
}
}
|
mit
|
d7ea5436809b160e72f76775733e2b93
| 43.221757 | 144 | 0.549532 | 4.385477 | false | false | false | false |
wiruzx/PureFutures
|
PureFutures/Promise.swift
|
1
|
4339
|
//
// Promise.swift
// PureFutures
//
// Created by Victor Shamanov on 2/11/15.
// Copyright (c) 2015 Victor Shamanov. All rights reserved.
//
import enum Result.Result
import protocol Result.ResultProtocol
/**
A mutable container for the `Future`
Allows you complete `Future` that it holds
*/
public final class Promise<T, E: Error> {
// MARK:- Public properties
/// `Future` which Promise will complete
public let future = Future<T, E>()
/// Shows if its future is completed
public var isCompleted: Bool {
return future.isCompleted
}
// MARK:- Initialization
public init() {
}
// MARK:- PromiseType methods
/**
Completes Promise's future with given `value`
Should be called only once! Second and next calls will raise an exception
See also: `tryComplete`
- parameter value: value, that future will be completed with
*/
public func complete<R: ResultProtocol>(_ value: R) where R.Value == T, R.Error == E {
future.setValue(value)
}
/**
Completes Promise's future with given `future`
Should be called only once! Second and next calls will raise an exception
See also: `tryCompleteWith`
- parameter future: Value that conforms to `FutureType` protocol
*/
public func completeWith<F: FutureType>(_ future: F) where F.Value.Value == T, F.Value.Error == E {
future.onComplete(Pure) { self.complete($0) }
}
/**
Complete Promise's future with given success `value`
Should be called only once! Second and next calls will raise an exception
See also: `trySuccess`
- parameter value: value, that future will be succeed with
*/
public func success(_ value: T) {
complete(Result.success(value))
}
/**
Complete Promise's future with given `error`
Should be called only once! Second and next calls will raise an exception
See also: `tryError`
- parameter error: error, that future will be succeed with
*/
public func error(_ error: E) {
complete(Result.failure(error))
}
// MARK:- Other methods
/**
Tries to complete Promise's future with given `value`
If future has already completed returns `false`, otherwise returns `true`
See also: `complete`
- parameter value: result that future will be completed with
- returns: Bool which says if completing was successful or not
*/
@discardableResult
public func tryComplete<R: ResultProtocol>(_ value: R) -> Bool where R.Value == T, R.Error == E {
if isCompleted {
return false
} else {
complete(value)
return true
}
}
/**
Tries to complete Promise's future with given success `value`
If future has already completed returns `flase`, otherwise returns `true`
See also: `success`
- parameter value: a success value that future will be completed with
- returns: Bool which says if completing was successful or not
*/
@discardableResult
public func trySuccess(_ value: T) -> Bool {
return tryComplete(Result.success(value))
}
/**
Tries to complete Promise's future with given success `value`
If future has already completed returns `flase`, otherwise returns `true`
See also: `success`
- parameter error: an error that future will be completed with
- returns: Bool which says if completing was successful or not
*/
@discardableResult
public func tryError(_ error: E) -> Bool {
return tryComplete(Result.failure(error))
}
/**
Tries to complete Promise's future with given future
If future has already completed returns `flase`, otherwise returns `true`
See also: `completeWith`
- parameter future: a future value that future will be completed with
- returns: Bool which says if completing was successful or not
*/
@discardableResult
public func tryCompleteWith<F: FutureType>(_ future: F) where F.Value.Value == T, F.Value.Error == E {
future.onComplete(Pure) { self.tryComplete($0) }
}
}
|
mit
|
b00fff64187c07a9e81c53089e6bf625
| 23.794286 | 106 | 0.624337 | 4.66058 | false | false | false | false |
aschwaighofer/swift
|
test/stdlib/POSIX.swift
|
1
|
6937
|
// RUN: %target-run-simple-swift %t
// REQUIRES: executable_test
// UNSUPPORTED: OS=windows-msvc
import StdlibUnittest
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) || os(WASI)
import Glibc
#else
#error("Unsupported platform")
#endif
chdir(CommandLine.arguments[1])
var POSIXTests = TestSuite("POSIXTests")
let semaphoreName = "TestSem"
#if os(Android)
// In Android, the cwd is the root directory, which is not writable.
let fn: String = {
let capacity = Int(PATH_MAX)
let resolvedPath = UnsafeMutablePointer<Int8>.allocate(capacity: capacity)
resolvedPath.initialize(repeating: 0, count: capacity)
defer {
resolvedPath.deinitialize(count: capacity)
resolvedPath.deallocate()
}
guard let _ = realpath("/proc/self/exe", resolvedPath) else {
fatalError("Couldn't obtain executable path")
}
let length = strlen(resolvedPath)
precondition(length != 0, "Couldn't obtain valid executable path")
// Search backwards for the last /, and turn it into a null byte.
for idx in stride(from: length-1, through: 0, by: -1) {
if Unicode.Scalar(UInt8(resolvedPath[idx])) == Unicode.Scalar("/") {
resolvedPath[idx] = 0
break
}
precondition(idx != 0, "Couldn't obtain valid executable directory")
}
return String(cString: resolvedPath) + "/test.txt"
}()
#else
let fn = "test.txt"
#endif
POSIXTests.setUp {
sem_unlink(semaphoreName)
unlink(fn)
}
// Failed semaphore creation.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open fail") {
let sem = sem_open(semaphoreName, 0)
expectEqual(SEM_FAILED, sem)
expectEqual(ENOENT, errno)
}
#endif
// Successful semaphore creation.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open success") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Successful semaphore creation with O_EXCL.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open O_EXCL success") {
let sem = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Successful creation and re-obtaining of existing semaphore.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open existing") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let sem2 = sem_open(semaphoreName, 0)
// Here, we'd like to test that the semaphores are the same, but it's quite
// difficult.
expectNotEqual(SEM_FAILED, sem2)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Fail because the semaphore already exists.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open existing O_EXCL fail") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let sem2 = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1)
expectEqual(SEM_FAILED, sem2)
expectEqual(EEXIST, errno)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Fail because the file descriptor is invalid.
POSIXTests.test("ioctl(CInt, UInt, CInt): fail") {
let fd = open(fn, 0)
expectEqual(-1, fd)
expectEqual(ENOENT, errno)
// A simple check to verify that ioctl is available
let _ = ioctl(fd, 0, 0)
expectEqual(EBADF, errno)
}
#if os(Linux) || os(Android)
// Successful creation of a socket and listing interfaces
POSIXTests.test("ioctl(CInt, UInt, UnsafeMutableRawPointer): listing interfaces success") {
// Create a socket
let sock = socket(PF_INET, 1, 0)
expectGT(Int(sock), 0)
// List interfaces
var ic = ifconf()
let io = ioctl(sock, UInt(SIOCGIFCONF), &ic);
expectGE(io, 0)
//Cleanup
let res = close(sock)
expectEqual(0, res)
}
#endif
// Fail because file doesn't exist.
POSIXTests.test("fcntl(CInt, CInt): fail") {
let fd = open(fn, 0)
expectEqual(-1, fd)
expectEqual(ENOENT, errno)
let _ = fcntl(fd, F_GETFL)
expectEqual(EBADF, errno)
}
// Change modes on existing file.
POSIXTests.test("fcntl(CInt, CInt): F_GETFL/F_SETFL success with file") {
// Create and open file.
let fd = open(fn, O_CREAT, 0o666)
expectGT(Int(fd), 0)
var flags = fcntl(fd, F_GETFL)
expectGE(Int(flags), 0)
// Change to APPEND mode...
var rc = fcntl(fd, F_SETFL, O_APPEND)
expectEqual(0, rc)
flags = fcntl(fd, F_GETFL)
expectEqual(flags | O_APPEND, flags)
// Change back...
rc = fcntl(fd, F_SETFL, 0)
expectEqual(0, rc)
flags = fcntl(fd, F_GETFL)
expectGE(Int(flags), 0)
// Clean up...
rc = close(fd)
expectEqual(0, rc)
rc = unlink(fn)
expectEqual(0, rc)
}
POSIXTests.test("fcntl(CInt, CInt, CInt): block and unblocking sockets success") {
// Create socket, note: socket created by default in blocking mode...
let sock = socket(PF_INET, 1, 0)
expectGT(Int(sock), 0)
var flags = fcntl(sock, F_GETFL)
expectGE(Int(flags), 0)
// Change mode of socket to non-blocking...
var rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK)
expectEqual(0, rc)
flags = fcntl(sock, F_GETFL)
expectEqual((flags | O_NONBLOCK), flags)
// Change back to blocking...
rc = fcntl(sock, F_SETFL, flags & ~O_NONBLOCK)
expectEqual(0, rc)
flags = fcntl(sock, F_GETFL)
expectGE(Int(flags), 0)
// Clean up...
rc = close(sock)
expectEqual(0, rc)
}
POSIXTests.test("fcntl(CInt, CInt, UnsafeMutableRawPointer): locking and unlocking success") {
// Create the file and add data to it...
var fd = open(fn, O_CREAT | O_WRONLY, 0o666)
expectGT(Int(fd), 0)
let data = "Testing 1 2 3"
let bytesWritten = write(fd, data, data.utf8.count)
expectEqual(data.utf8.count, bytesWritten)
var rc = close(fd)
expectEqual(0, rc)
// Re-open the file...
fd = open(fn, 0)
expectGT(Int(fd), 0)
// Lock for reading...
var flck = flock()
flck.l_type = Int16(F_RDLCK)
#if os(Android)
// In Android l_len is __kernel_off_t which is not the same size as off_t in
// 64 bits.
flck.l_len = __kernel_off_t(data.utf8.count)
#else
flck.l_len = off_t(data.utf8.count)
#endif
rc = fcntl(fd, F_SETLK, &flck)
expectEqual(0, rc)
// Unlock for reading...
flck = flock()
flck.l_type = Int16(F_UNLCK)
rc = fcntl(fd, F_SETLK, &flck)
expectEqual(0, rc)
// Clean up...
rc = close(fd)
expectEqual(0, rc)
rc = unlink(fn)
expectEqual(0, rc)
}
runAllTests()
|
apache-2.0
|
ff92d051401015f4c68d7791faf105a1
| 24.560886 | 97 | 0.678504 | 3.264373 | false | true | false | false |
omaarr90/BarCodeReaderView
|
BarCodeReader/BarCodeReaderView.swift
|
1
|
10670
|
//
// BarCodeReaderView.swift
// BarCodeReader
//
// Created by Omar Alshammari on 2/18/16.
// Copyright © 2016 ___OALSHAMMARI___. All rights reserved.
//
import UIKit
import AVFoundation
private let queueName = "sa.com.elm.AbhserLite.MetadataOutput"
/// The barcode reader view delegates.
public protocol BarcodeReaderViewDelegate {
/**
This method is called upon a success reading of barcodes.
- Parameters:
- barcodeReader: The bar code reader view instance which read the barcode.
- info: the string representations of the barcode.
*/
func barcodeReader(barcodeReader: BarcodeReaderView, didFinishReadingString info: String)
/**
This method is called upon a failure.
- Parameters:
- barcodeReader: The bar code reader view instance which failed.
- error: NSError which describes the failaure.
- possible error codes:
- AccessRestriction: 7000
- DeviceNotSupported: 7001
- OutputNotSuppoted: 7002
*/
func barcodeReader(barcodeReader: BarcodeReaderView, didFailReadingWithError error: NSError)
}
/**
Barcode types.
- Aztec: AVMetadataObjectTypeAztecCode
- Code128: AVMetadataObjectTypeCode128Code
- PDF417Barcode: AVMetadataObjectTypePDF417Code
- QR: AVMetadataObjectTypeQRCode
- UPCECode: AVMetadataObjectTypeUPCECode
- Code39Code: AVMetadataObjectTypeCode39Code
- Code39Mod43Code: AVMetadataObjectTypeCode39Mod43Code
- EAN13Code: AVMetadataObjectTypeEAN13Code
- EAN8Code: AVMetadataObjectTypeEAN8Code
- Interleaved2of5Code: AVMetadataObjectTypeInterleaved2of5Code
- ITF14Code: AVMetadataObjectTypeITF14Code
- DataMatrixCode: AVMetadataObjectTypeDataMatrixCode
*/
public enum BarCodeType: String, CustomStringConvertible {
case Aztec
case Code128
case PDF417Barcode
case QR
case UPCECode
case Code39Code
case Code39Mod43Code
case EAN13Code
case EAN8Code
case Interleaved2of5Code
case ITF14Code
case DataMatrixCode
/// string representations of the bar code type.
public var description: String {
get{
switch self {
case .Aztec: return AVMetadataObjectTypeAztecCode
case .Code128: return AVMetadataObjectTypeCode128Code
case .PDF417Barcode: return AVMetadataObjectTypePDF417Code
case .QR: return AVMetadataObjectTypeQRCode
case .UPCECode: return AVMetadataObjectTypeUPCECode
case .Code39Code: return AVMetadataObjectTypeCode39Code
case .Code39Mod43Code: return AVMetadataObjectTypeCode39Mod43Code
case .EAN13Code: return AVMetadataObjectTypeEAN13Code
case .EAN8Code: return AVMetadataObjectTypeEAN8Code
case .Interleaved2of5Code: return AVMetadataObjectTypeInterleaved2of5Code
case .ITF14Code: return AVMetadataObjectTypeITF14Code
case .DataMatrixCode: return AVMetadataObjectTypeDataMatrixCode
}
}
}
}
/// a UIView subclass which can reads barcodes. :)
public class BarcodeReaderView: UIView {
/* public Variables */
///the delegate which must conform to `BarcodeReaderViewDelegate` protocol
public var delegate: BarcodeReaderViewDelegate?
/// barcodes type you would like to scan with this instance
public var barCodeTypes: [BarCodeType]? {
didSet {
if nil != self.captureSession {
self.addMetadataOutputToSession(self.captureSession)
}
}
}
/* Private Variables */
private var captureSession: AVCaptureSession!
private var previewLayer: AVCaptureVideoPreviewLayer!
private var view: UIView?
private var deviceDoesNotSupportVideo: Bool!
//MARK: - initalizers
/**
initlaize bar code reader view with the specified frame.
- Parameters:
- frame: CGRect instance to represent the bar code frame.
Returns: a new instance of bar code reader view.
*/
override public init(frame: CGRect) {
super.init(frame: frame)
self.setupInitializers()
}
/**
initlaize bar code reader view with the specified decoder. this is for IB
- Parameters:
- coder: NSCoder instance to decode the view.
Returns: a new instance of bar code reader view.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupInitializers()
}
/**
overriden methods from UIView
*/
public override func didMoveToSuperview() {
super.didMoveToSuperview()
self.barcodeWillMoveToSuperView()
}
//MARK: - public functions
/**
start looking for barcodes. call this method when you are ready to capture some codes
*/
public func startCapturing() {
if nil != self.captureSession{
self.captureSession.startRunning()
}
}
/**
stop looking for barcodes. call this method when you want to stop capturing barcodes
*/
public func stopCapturing() {
if nil != self.captureSession{
self.captureSession.stopRunning()
}
}
public func addView(view: UIView) {
if self.view != nil {
self.view!.layer.removeFromSuperlayer()
self.view = nil
}
view.layer.frame = self.bounds
self.layer.addSublayer(view.layer)
self.view = view
}
}
extension BarcodeReaderView: AVCaptureMetadataOutputObjectsDelegate {
/**
this method is the delegate mthode of AVCaptureMetadataOutputObjectsDelegate
*/
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
let firstObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if let readedObject = firstObject, let stringValue = readedObject.stringValue{
self.delegate?.barcodeReader(self, didFinishReadingString: stringValue)
}
}
}
}
//MARK: - Private functions
private extension BarcodeReaderView {
private func addLabelToViewWithText(text: String) {
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4)
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.text = text
label.numberOfLines = 0
label.font = UIFont.systemFontOfSize(24.0)
label.translatesAutoresizingMaskIntoConstraints = false
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.textAlignment = .Center
self.addSubview(label)
/* Configure Label AutoLayout */
let centerYConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
let leadingConstraint = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0.0)
let trailingConstraint = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 8.0)
self.addConstraints([centerYConstraint, leadingConstraint, trailingConstraint])
}
private func setupInitializers() {
if let captureSession = newVideoCaptureSession() {
self.captureSession = captureSession
}
}
private func newVideoCaptureSession() -> AVCaptureSession? {
/* set up a capture input for the default video camera */
let videoCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let videoInput: AVCaptureDeviceInput?
do {
videoInput = try AVCaptureDeviceInput(device: videoCamera)
} catch {
deviceDoesNotSupportVideo = true
return nil
}
/* attach the input to capture session */
let captureSession = AVCaptureSession()
if (!captureSession.canAddInput(videoInput)) {
return nil
}
deviceDoesNotSupportVideo = false
captureSession.addInput(videoInput)
return captureSession
}
private func addPreviewLayerForSession(session: AVCaptureSession) {
let layer = AVCaptureVideoPreviewLayer(session: session)
let rootLayer = self.layer
layer.frame = rootLayer.bounds
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
rootLayer.addSublayer(layer)
layer.cornerRadius = 5.0;
previewLayer = layer
}
private func addMetadataOutputToSession(session: AVCaptureSession) {
let metadataOutput = AVCaptureMetadataOutput()
if (!session.canAddOutput(metadataOutput)) {
self.delegate?.barcodeReader(self, didFailReadingWithError: NSError.outputNotSupportedError())
return
}
session.addOutput(metadataOutput)
let queue = dispatch_queue_create(queueName, DISPATCH_QUEUE_SERIAL)
metadataOutput.setMetadataObjectsDelegate(self, queue: queue)
if let allowedTypes = self.barCodeTypes where allowedTypes.count > 0{
metadataOutput.metadataObjectTypes = self.allowedTypes(allowedTypes)
} else {
metadataOutput.metadataObjectTypes = nil
}
}
private func allowedTypes(allowed: [BarCodeType]) -> [String] {
var types = [String]()
for type in allowed {
types.append(type.description)
}
return types
}
private func barcodeWillMoveToSuperView() {
if nil != self.captureSession && !deviceDoesNotSupportVideo {
addPreviewLayerForSession(captureSession)
} else if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == .Denied {
addLabelToViewWithText(NSLocalizedString("You did not allow access to your camera, please allow it to read barcodes.", comment: ""))
self.delegate?.barcodeReader(self, didFailReadingWithError: NSError.accessRestrictionError())
} else if deviceDoesNotSupportVideo == true {
addLabelToViewWithText(NSLocalizedString("Sorry, Your device does not support camera", comment: ""))
self.delegate?.barcodeReader(self, didFailReadingWithError: NSError.deviceNotSupportedError())
}
}
}
|
mit
|
bdb67f534c9eefe0eb7a8cd04f8ac586
| 35.043919 | 173 | 0.672134 | 5.18668 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples
|
snippets/MapsSnippets/MapsSnippets/Swift/MapStyling.swift
|
1
|
2274
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START maps_ios_map_styling_json_file]
import GoogleMaps
class MapStyling: UIViewController {
// Set the status bar style to complement night-mode.
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
do {
// Set the map style by passing the URL of the local file.
if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
self.view = mapView
}
}
// [END maps_ios_map_styling_json_file]
// [START maps_ios_map_styling_string_resource]
class MapStylingStringResource: UIViewController {
let MapStyle = "JSON_STYLE_GOES_HERE"
// Set the status bar style to complement night-mode.
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
do {
// Set the map style by passing a valid JSON string.
mapView.mapStyle = try GMSMapStyle(jsonString: MapStyle)
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
self.view = mapView
}
}
// [END maps_ios_map_styling_string_resource]
|
apache-2.0
|
489ac125066f952323c5c1b0524aeb44
| 31.956522 | 94 | 0.701847 | 4.003521 | false | false | false | false |
SwiftyMagic/Magic
|
MagicExample/MagicExample/MasterTableViewController.swift
|
1
|
1522
|
//
// MasterTableViewController.swift
// MagicExample
//
// Created by Broccoli on 2016/9/27.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import UIKit
import Magic
class MasterTableViewController: UITableViewController {
let demoArray = ["TableViewDemo", "TextViewDemo"]
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: - Table view data source
extension MasterTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "MasterTableViewCell")
cell.textLabel?.text = demoArray[indexPath.row]
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let tableViewController = storyboard?.instantiateViewController(viewController: TableViewController.self)
navigationController?.pushViewController(tableViewController!, animated: true)
} else if indexPath.row == 1 {
let textViewController = storyboard?.instantiateViewController(viewController: TextViewViewController.self)
navigationController?.pushViewController(textViewController!, animated: true)
}
}
}
|
mit
|
c65563412a2a8f9b96e1e74b706ba3ea
| 34.325581 | 120 | 0.702436 | 5.386525 | false | false | false | false |
zhuxietong/Eelay
|
Sources/Eelay/object/NSArray+nodes.swift
|
1
|
4373
|
//
// Collection+nodesswift
// MESwiftExtention
//
// Created by 朱撷潼 on 15/3/12.
// Copyright (c) 2015年 zhuxietong. All rights reserved.
//
import Foundation
public protocol NodeGetSetSupport {
subscript(obj node:String,value:Any?) -> Any?{get}
subscript(node:String,value:String?) -> String {get}
func get<T>(node:String,defaultV:T) -> T
func set(node:String,obj:Any)
}
extension NSMutableArray:NodeGetSetSupport{
public subscript(obj node:String,value:Any?) -> Any? {
get {
if let obj = self.value(obj: node)
{
return obj
}
return value
}
}
public subscript(node:String,value:String?) -> String {
get {
if let obj = self.value(obj: node)
{
return "\(obj)"
}
if let rValue = value
{
return rValue
}
else
{
return ""
}
}
}
public func get<T>(node: String, defaultV: T) -> T {
let _v = self.value(obj: node)
if let v = _v as? T
{
return v
}
return TPConvert.convert(obj: _v, devfaultV: defaultV)
}
public func set(node: String, obj: Any) {
// print("\(#file)\(#line)")
}
}
extension NSMutableArray
{
func value(obj node:String) -> AnyObject?
{
var newNode = node
return self.getValueWithNodes(nodes: &newNode)
}
func getValueWithNodes(nodes:inout String) -> AnyObject?
{
let paths = nodes.components(separatedBy:".")
var newPaths = [String]()
for (index,value) in paths.enumerated()
{
if index != 0
{
newPaths.append(value)
}
}
nodes = newPaths.joined(separator: ".")
if paths.count > 0
{
let value0 = paths[0]
if let index = Int(value0)
{
if self.count > index
{
if let obj = self.object(at: index) as? NSMutableArray
{
if paths.count > 1
{
return obj.getValueWithNodes(nodes: &nodes)
}
else
{
return self.object(at: index) as AnyObject
}
}
else if let obj = self.object(at: index) as? NSMutableDictionary
{
if paths.count > 1
{
return obj.getValueWithNodes(nodes: &nodes) as AnyObject
}
else
{
return self.object(at: index) as AnyObject
}
}
else
{
if paths.count < 2
{
return self.object(at: index) as AnyObject
}
else
{
return nil
}
}
}
}
}
return nil
}
}
extension NSMutableArray
{
public func findItemForInfo(value:String, key:String) ->NSMutableDictionary?
{
var dict :NSMutableDictionary? = nil
for aitem in self
{
if let item = aitem as? NSMutableDictionary
{
if let temp = item.findItemForInfo(value: value, key: key)
{
dict = temp
}
}
if let item = aitem as? NSMutableArray
{
if let temp = item.findItemForInfo(value: value, key: key)
{
dict = temp
}
}
}
return dict
}
}
|
mit
|
8b83ac3b5eb604c53ae9c713bbbce753
| 23.801136 | 84 | 0.384422 | 5.316687 | false | false | false | false |
Eccelor/material-components-ios
|
components/Buttons/examples/supplemental/ButtonsTypicalUseSupplemental.swift
|
3
|
1983
|
/*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class ButtonsTypicalUseSupplemental: NSObject {
static let floatingButtonPlusDimension = CGFloat(24)
static func plusShapePath() -> UIBezierPath {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 19, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 13))
bezierPath.close()
return bezierPath
}
static func createPlusShapeLayer(_ floatingButton: MDCFloatingButton) -> CAShapeLayer {
let plusShape = CAShapeLayer()
plusShape.path = ButtonsTypicalUseSupplemental.plusShapePath().cgPath
plusShape.fillColor = UIColor.white.cgColor
plusShape.position =
CGPoint(x: (floatingButton.frame.size.width - floatingButtonPlusDimension) / 2,
y: (floatingButton.frame.size.height - floatingButtonPlusDimension) / 2)
return plusShape
}
}
|
apache-2.0
|
24a00ec9b5f92bbd19960e4180b71de5
| 38.66 | 90 | 0.7176 | 3.918972 | false | false | false | false |
folse/Member_iOS
|
member/QRCode.swift
|
1
|
2757
|
//
// ViewController.swift
// TwoD_Code_Demo
//
// Created by Techsun on 14-7-28.
// Copyright (c) 2014年 techsun. All rights reserved.
//
import UIKit
import Foundation
import AVFoundation
class QRCode: UIViewController ,AVCaptureMetadataOutputObjectsDelegate {
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let session = AVCaptureSession()
var layer: AVCaptureVideoPreviewLayer?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.setupCamera()
self.session.startRunning()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGrayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupCamera(){
self.session.sessionPreset = AVCaptureSessionPresetHigh
var error : NSError?
let input = AVCaptureDeviceInput(device: device, error: &error)
if (error != nil) {
println(error!.description)
return
}
if session.canAddInput(input) {
session.addInput(input)
}
layer = AVCaptureVideoPreviewLayer(session: session)
layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
layer!.frame = CGRectMake(20,150,280,280);
self.view.layer.insertSublayer(self.layer, atIndex: 0)
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
if session.canAddOutput(output) {
session.addOutput(output)
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode];
}
session.startRunning()
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
var stringValue:String!
if metadataObjects.count > 0 {
var metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
stringValue = metadataObject.stringValue
}
self.session.stopRunning()
println("code is \(stringValue)")
self.navigationController?.popViewControllerAnimated(true)
NSNotificationCenter.defaultCenter().postNotificationName("afterScanCustomer", object: stringValue)
// var alertView = UIAlertView()
// alertView.delegate=self
// alertView.title = ""
// alertView.message = "\(stringValue)"
// alertView.addButtonWithTitle("确认")
// alertView.show()
}
}
|
mit
|
a96f1f5b220afb19cab8281cc09d84d3
| 31.376471 | 161 | 0.659033 | 5.580122 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.