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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
firebase/quickstart-ios | database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Views/LoginView.swift | 1 | 4053 | //
// Copyright (c) 2021 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 SwiftUI
struct LoginView: View {
@StateObject var user = UserViewModel()
@State private var signUpViewPresented = false
var body: some View {
let loginView = VStack {
// Login title
Text("Login".uppercased())
.font(.title)
Spacer()
.frame(idealHeight: 0.1 * ScreenDimensions.height)
.fixedSize()
// Email textfield
let emailInputField = HStack {
Image("user-icon")
.resizable()
.scaledToFit()
.frame(width: 30.0, height: 30.0)
.opacity(0.5)
let emailTextField = TextField("Email", text: $user.email)
#if os(iOS)
emailTextField
.keyboardType(.emailAddress)
.autocapitalization(UITextAutocapitalizationType.none)
#elseif os(macOS) || os(tvOS)
emailTextField
#endif
}
.padding(0.02 * ScreenDimensions.height)
#if os(iOS)
emailInputField
.background(RoundedRectangle(cornerRadius: 10).fill(Color(.systemGray5)))
.frame(width: ScreenDimensions.width * 0.8)
#elseif os(macOS) || os(tvOS)
emailInputField
#endif
// Password textfield
let passwordInputField = HStack {
Image("lock-icon")
.resizable()
.scaledToFit()
.frame(width: 30.0, height: 30.0)
.opacity(0.5)
SecureField("Password", text: $user.password)
}
.padding(0.02 * ScreenDimensions.height)
#if os(iOS)
passwordInputField
.background(RoundedRectangle(cornerRadius: 10).fill(Color(.systemGray5)))
.frame(width: ScreenDimensions.width * 0.8)
#elseif os(macOS) || os(tvOS)
passwordInputField
#endif
Spacer()
.frame(idealHeight: 0.05 * ScreenDimensions.height)
.fixedSize()
// Login button
let loginButton = Button(action: user.login) {
Text("Login".uppercased())
.foregroundColor(.white)
.font(.title2)
.bold()
}
.padding(0.025 * ScreenDimensions.height)
.background(Capsule().fill(Color(.systemTeal)))
#if os(iOS) || os(macOS)
loginButton
.buttonStyle(BorderlessButtonStyle())
#elseif os(tvOS)
loginButton
#endif
Spacer()
.frame(idealHeight: 0.05 * ScreenDimensions.height)
.fixedSize()
// Navigation text
HStack {
Text("Don't have an account?")
let signUpButton = Button(action: {
signUpViewPresented = true
}) {
Text("Sign up".uppercased())
.bold()
}
.sheet(isPresented: $signUpViewPresented) {
SignUpView(user: user, isPresented: $signUpViewPresented)
}
#if os(iOS) || os(macOS)
signUpButton
.buttonStyle(BorderlessButtonStyle())
#elseif os(tvOS)
signUpButton
#endif
}
}
.alert(isPresented: $user.alert, content: {
Alert(
title: Text("Message"),
message: Text(user.alertMessage),
dismissButton: .destructive(Text("OK"))
)
})
#if os(iOS) || os(tvOS)
loginView
#elseif os(macOS)
loginView
.frame(minWidth: 400, idealWidth: 400, minHeight: 700, idealHeight: 700)
#endif
}
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView(user: user)
}
}
| apache-2.0 | 769505340dd4de9a981821a90ad7fa73 | 27.342657 | 83 | 0.594868 | 4.288889 | false | false | false | false |
lemonkey/iOS | WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Lister WatchKit Extension/ListInterfaceController.swift | 1 | 7984 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListInterfaceController` interface controller that presents a single list managed by a `ListPresenterType` object.
*/
import WatchKit
import ListerKit
/**
The interface controller that presents a list. The interface controller listens for changes to how the list
should be presented by the list presenter.
*/
class ListInterfaceController: WKInterfaceController, ListPresenterDelegate {
// MARK: Types
struct Storyboard {
static let interfaceControllerName = "ListInterfaceController"
struct RowTypes {
static let item = "ListControllerItemRowType"
static let noItems = "ListControllerNoItemsRowType"
}
}
// MARK: Properties
@IBOutlet weak var interfaceTable: WKInterfaceTable!
var listDocument: ListDocument!
var listPresenter: IncompleteListItemsPresenter! {
return listDocument?.listPresenter as? IncompleteListItemsPresenter
}
// MARK: Interface Table Selection
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
let listItem = listPresenter.presentedListItems[rowIndex]
listPresenter.toggleListItem(listItem)
}
// MARK: Actions
@IBAction func markAllListItemsAsComplete() {
listPresenter.updatePresentedListItemsToCompletionState(true)
}
@IBAction func markAllListItemsAsIncomplete() {
listPresenter.updatePresentedListItemsToCompletionState(false)
}
func refreshAllData() {
let listItemCount = listPresenter.count
if listItemCount > 0 {
interfaceTable.setNumberOfRows(listItemCount, withRowType: Storyboard.RowTypes.item)
for idx in 0..<listItemCount {
configureRowControllerAtIndex(idx)
}
}
else {
let indexSet = NSIndexSet(index: 0)
interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems)
}
}
// MARK: ListPresenterDelegate
func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) {
refreshAllData()
}
func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
// `WKInterfaceTable` objects do not need to be notified of changes to the table, so this is a no op.
}
func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) {
let indexSet = NSIndexSet(index: index)
// The list presenter was previously empty. Remove the "no items" row.
if index == 0 && listPresenter!.count == 1 {
interfaceTable.removeRowsAtIndexes(indexSet)
}
interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.item)
}
func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) {
let indexSet = NSIndexSet(index: index)
interfaceTable.removeRowsAtIndexes(indexSet)
// The list presenter is now empty. Add the "no items" row.
if index == 0 && listPresenter!.isEmpty {
interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems)
}
}
func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) {
configureRowControllerAtIndex(index)
}
func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) {
// Remove the item from the fromIndex straight away.
let fromIndexSet = NSIndexSet(index: fromIndex)
interfaceTable.removeRowsAtIndexes(fromIndexSet)
/*
Determine where to insert the moved item. If the `toIndex` was beyond the `fromIndex`, normalize
its value.
*/
var toIndexSet: NSIndexSet
if toIndex > fromIndex {
toIndexSet = NSIndexSet(index: toIndex - 1)
}
else {
toIndexSet = NSIndexSet(index: toIndex)
}
interfaceTable.insertRowsAtIndexes(toIndexSet, withRowType: Storyboard.RowTypes.item)
}
func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) {
for idx in 0..<listPresenter.count {
configureRowControllerAtIndex(idx)
}
}
func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
if isInitialLayout {
// Display all of the list items on the first layout.
refreshAllData()
}
else {
/*
The underlying document changed because of user interaction (this event only occurs if the
list presenter's underlying list presentation changes based on user interaction).
*/
listDocument.updateChangeCount(.Done)
}
}
// MARK: Convenience
func setupInterfaceTable() {
listDocument.listPresenter = IncompleteListItemsPresenter()
listPresenter.delegate = self
listDocument.openWithCompletionHandler { success in
if !success {
println("Couldn't open document: \(self.listDocument?.fileURL).")
return
}
/*
Once the document for the list has been found and opened, update the user activity with its URL path
to enable the container iOS app to start directly in this list document. A URL path
is passed instead of a URL because the `userInfo` dictionary of a WatchKit app's user activity
does not allow NSURL values.
*/
let userInfo: [NSObject: AnyObject] = [
AppConfiguration.UserActivity.listURLPathUserInfoKey: self.listDocument.fileURL.path!,
AppConfiguration.UserActivity.listColorUserInfoKey: self.listDocument.listPresenter!.color.rawValue
]
/*
Lister uses a specific user activity name registered in the Info.plist and defined as a constant to
separate this action from the built-in UIDocument handoff support.
*/
self.updateUserActivity(AppConfiguration.UserActivity.watch, userInfo: userInfo, webpageURL: nil)
}
}
func configureRowControllerAtIndex(index: Int) {
let listItemRowController = interfaceTable.rowControllerAtIndex(index) as! ListItemRowController
let listItem = listPresenter.presentedListItems[index]
listItemRowController.setText(listItem.text)
let textColor = listItem.isComplete ? UIColor.grayColor() : UIColor.whiteColor()
listItemRowController.setTextColor(textColor)
// Update the checkbox image.
let state = listItem.isComplete ? "checked" : "unchecked"
let imageName = "checkbox-\(listPresenter.color.name.lowercaseString)-\(state)"
listItemRowController.setCheckBoxImageNamed(imageName)
}
// MARK: Interface Life Cycle
override func awakeWithContext(context: AnyObject?) {
precondition(context is ListInfo, "Expected class of `context` to be ListInfo.")
let listInfo = context as! ListInfo
listDocument = ListDocument(fileURL: listInfo.URL)
// Set the title of the interface controller based on the list's name.
setTitle(listInfo.name)
// Fill the interface table with the current list items.
setupInterfaceTable()
}
override func didDeactivate() {
listDocument.closeWithCompletionHandler(nil)
}
}
| mit | c37b05e93ea6d37a802d1893e9b78d94 | 36.299065 | 123 | 0.648584 | 5.834795 | false | false | false | false |
benlangmuir/swift | test/IDE/print_omit_needless_words_appkit.swift | 19 | 3497 | // RUN: %empty-directory(%t)
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=AppKit -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.AppKit.txt
// RUN: %FileCheck %s -check-prefix=CHECK-APPKIT -strict-whitespace < %t.AppKit.txt
// Note: class method name stripping context type.
// CHECK-APPKIT: class func red() -> NSColor
// Note: instance method name stripping context type.
// CHECK-APPKIT: func same() -> Self
// Note: Unsafe(Mutable)Pointers don't get defaulted to 'nil'
// CHECK-APPKIT: func getRGBAComponents(_: UnsafeMutablePointer<CChar>?)
// Note: Skipping over "3D"
// CHECK-APPKIT: func drawInAir(at: Point3D)
// Note: with<something> -> <something>
// CHECK-APPKIT: func draw(at: Point3D, withAttributes: [String : Any]? = nil)
// Note: Don't strip names that aren't preceded by a verb or preposition.
// CHECK-APPKIT: func setTextColor(_: NSColor?)
// Note: Splitting with default arguments.
// CHECK-APPKIT: func draw(in: NSView?)
// Note: NSDictionary default arguments for "options"
// CHECK-APPKIT: func drawAnywhere(in: NSView?, options: [AnyHashable : Any] = [:])
// CHECK-APPKIT: func drawAnywhere(options: [AnyHashable : Any] = [:])
// CHECK-APPKIT: func drawAnywhere(optionalOptions: [AnyHashable : Any]? = nil)
// Make sure we're removing redundant context type info at both the
// beginning and the end.
// CHECK-APPKIT: func reversing() -> NSBezierPath
// Make sure we're dealing with 'instancetype' properly.
// CHECK-APPKIT: func inventing() -> Self
// Make sure we're removing redundant context type info at both the
// beginning and the end of a property.
// CHECK-APPKIT: var flattened: NSBezierPath { get }
// CHECK-APPKIT: func dismiss(animated: Bool)
// CHECK-APPKIT: func shouldCollapseAutoExpandedItems(forDeposited: Bool) -> Bool
// Introducing argument labels and pruning the base name.
// CHECK-APPKIT: func rectForCancelButton(whenCentered: Bool)
// CHECK-APPKIT: func openUntitledDocumentAndDisplay(_: Bool)
// Don't strip due to weak type information.
// CHECK-APPKIT: func setContentHuggingPriority(_: NSLayoutPriority)
// Look through typedefs of pointers.
// CHECK-APPKIT: func layout(at: NSPointPointer!)
// The presence of a property prevents us from stripping redundant
// type information from the base name.
// CHECK-APPKIT: func addGestureRecognizer(_: NSGestureRecognizer)
// CHECK-APPKIT: func removeGestureRecognizer(_: NSGestureRecognizer)
// CHECK-APPKIT: func favoriteView(for: NSGestureRecognizer) -> NSView?
// CHECK-APPKIT: func addLayoutConstraints(_: Set<NSLayoutConstraint>)
// CHECK-APPKIT: func add(_: NSRect)
// CHECK-APPKIT: class func conjureRect(_: NSRect)
| apache-2.0 | cf4ec5a71a2b5f3b4a1477fcd62faaa3 | 46.90411 | 232 | 0.736917 | 3.518109 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/XCUITests/IntegrationTests.swift | 2 | 12202 | // 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 XCTest
private let testingURL = "example.com"
private let userName = "iosmztest"
private let userPassword = "test15mz"
private let historyItemSavedOnDesktop = "http://www.example.com/"
private let loginEntry = "https://accounts.google.com"
private let tabOpenInDesktop = "http://example.com/"
class IntegrationTests: BaseTestCase {
let testWithDB = ["testFxASyncHistory"]
let testFxAChinaServer = ["testFxASyncPageUsingChinaFxA"]
// This DB contains 1 entry example.com
let historyDB = "exampleURLHistoryBookmark.db"
override func setUp() {
// Test name looks like: "[Class testFunc]", parse out the function name
let parts = name.replacingOccurrences(of: "]", with: "").split(separator: " ")
let key = String(parts[1])
if testWithDB.contains(key) {
// for the current test name, add the db fixture used
launchArguments = [LaunchArguments.SkipIntro,
LaunchArguments.StageServer,
LaunchArguments.SkipWhatsNew,
LaunchArguments.SkipETPCoverSheet,
LaunchArguments.LoadDatabasePrefix + historyDB,
LaunchArguments.SkipContextualHints,
LaunchArguments.TurnOffTabGroupsInUserPreferences]
} else if testFxAChinaServer.contains(key) {
launchArguments = [LaunchArguments.SkipIntro,
LaunchArguments.FxAChinaServer,
LaunchArguments.SkipWhatsNew,
LaunchArguments.SkipETPCoverSheet,
LaunchArguments.SkipContextualHints,
LaunchArguments.TurnOffTabGroupsInUserPreferences]
}
super.setUp()
}
func allowNotifications () {
addUIInterruptionMonitor(withDescription: "notifications") { (alert) -> Bool in
alert.buttons["Allow"].tap()
return true
}
app.swipeDown()
}
private func signInFxAccounts() {
navigator.goto(Intro_FxASignin)
navigator.performAction(Action.OpenEmailToSignIn)
sleep(5)
waitForExistence(app.navigationBars[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaNavigationBar], timeout: 20)
userState.fxaUsername = ProcessInfo.processInfo.environment["FXA_EMAIL"]!
userState.fxaPassword = ProcessInfo.processInfo.environment["FXA_PASSWORD"]!
navigator.performAction(Action.FxATypeEmail)
navigator.performAction(Action.FxATapOnContinueButton)
navigator.performAction(Action.FxATypePassword)
navigator.performAction(Action.FxATapOnSignInButton)
sleep(3)
allowNotifications()
}
private func waitForInitialSyncComplete() {
navigator.nowAt(BrowserTab)
navigator.goto(SettingsScreen)
waitForExistence(app.tables.staticTexts["Sync Now"], timeout: 25)
}
func testFxASyncHistory () {
// History is generated using the DB so go directly to Sign in
// Sign into Firefox Accounts
app.buttons["urlBar-cancel"].tap()
navigator.goto(BrowserTabMenu)
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncPageUsingChinaFxA () {
// History is generated using the DB so go directly to Sign in
// Sign into Firefox Accounts
app.buttons["urlBar-cancel"].tap()
navigator.goto(BrowserTabMenu)
navigator.goto(Intro_FxASignin)
navigator.performAction(Action.OpenEmailToSignIn)
waitForExistence(app.navigationBars[AccessibilityIdentifiers.Settings.FirefoxAccount.fxaNavigationBar], timeout: 20)
waitForExistence(app.webViews.textFields[AccessibilityIdentifiers.Settings.FirefoxAccount.emailTextFieldChinaFxA], timeout: 20)
// Wait for element not present on FxA sign in page China FxA server
waitForNoExistence(app.webViews.otherElements.staticTexts["Firefox Monitor"])
XCTAssertFalse(app.webViews.otherElements.staticTexts["Firefox Monitor"].exists)
}
func testFxASyncBookmark () {
// Bookmark is added by the DB
// Sign into Firefox Accounts
app.buttons["urlBar-cancel"].tap()
navigator.openURL("example.com")
waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.trackingProtection], timeout: 5)
navigator.goto(BrowserTabMenu)
waitForExistence(app.tables.otherElements[ImageIdentifiers.addToBookmark], timeout: 15)
app.tables.otherElements[ImageIdentifiers.addToBookmark].tap()
navigator.nowAt(BrowserTab)
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncBookmarkDesktop () {
// Sign into Firefox Accounts
app.buttons["urlBar-cancel"].tap()
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
navigator.goto(LibraryPanel_Bookmarks)
waitForExistence(app.tables["Bookmarks List"].cells.staticTexts["Example Domain"], timeout: 5)
}
func testFxASyncTabs () {
navigator.openURL(testingURL)
waitUntilPageLoad()
navigator.goto(BrowserTabMenu)
signInFxAccounts()
// Wait for initial sync to complete
navigator.nowAt(BrowserTab)
// This is only to check that the device's name changed
navigator.goto(SettingsScreen)
waitForExistence(app.tables.cells.element(boundBy: 1), timeout: 10)
app.tables.cells.element(boundBy: 1).tap()
waitForExistence(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"], timeout: 10)
XCTAssertEqual(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"].value! as! String, "Fennec (administrator) on iOS")
// Sync again just to make sure to sync after new name is shown
app.buttons["Settings"].tap()
app.tables.cells.element(boundBy: 2).tap()
waitForExistence(app.tables.staticTexts["Sync Now"], timeout: 15)
}
func testFxASyncLogins () {
navigator.openURL("gmail.com")
waitUntilPageLoad()
// Log in in order to save it
waitForExistence(app.webViews.textFields["Email or phone"])
app.webViews.textFields["Email or phone"].tap()
app.webViews.textFields["Email or phone"].typeText(userName)
app.webViews.buttons["Next"].tap()
waitForExistence(app.webViews.secureTextFields["Password"])
app.webViews.secureTextFields["Password"].tap()
app.webViews.secureTextFields["Password"].typeText(userPassword)
app.webViews.buttons["Sign in"].tap()
// Save the login
waitForExistence(app.buttons["SaveLoginPrompt.saveLoginButton"])
app.buttons["SaveLoginPrompt.saveLoginButton"].tap()
// Sign in with FxAccount
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncHistoryDesktop () {
app.buttons["urlBar-cancel"].tap()
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced History
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables.cells.staticTexts[historyItemSavedOnDesktop], timeout: 5)
}
func testFxASyncPasswordDesktop () {
app.buttons["urlBar-cancel"].tap()
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced Logins
navigator.nowAt(SettingsScreen)
navigator.goto(LoginsSettings)
waitForExistence(app.buttons.firstMatch)
app.buttons["Continue"].tap()
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let passcodeInput = springboard.secureTextFields["Passcode field"]
passcodeInput.tap()
passcodeInput.typeText("foo\n")
navigator.goto(LoginsSettings)
waitForExistence(app.tables["Login List"], timeout: 5)
XCTAssertTrue(app.tables.cells.staticTexts[loginEntry].exists, "The login saved on desktop is not synced")
}
func testFxASyncTabsDesktop () {
app.buttons["urlBar-cancel"].tap()
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced Tabs
app.buttons["Done"].tap()
navigator.nowAt(HomePanelsScreen)
navigator.goto(TabTray)
navigator.performAction(Action.ToggleSyncMode)
// Need to swipe to get the data on the screen on focus
app.swipeDown()
waitForExistence(app.tables.otherElements["profile1"], timeout: 10)
XCTAssertTrue(app.tables.staticTexts[tabOpenInDesktop].exists, "The tab is not synced")
}
func testFxADisconnectConnect() {
app.buttons["urlBar-cancel"].tap()
// Sign into Firefox Accounts
signInFxAccounts()
sleep(3)
// Wait for initial sync to complete
waitForInitialSyncComplete()
navigator.nowAt(SettingsScreen)
// Check Bookmarks
navigator.goto(LibraryPanel_Bookmarks)
waitForExistence(app.tables["Bookmarks List"], timeout: 3)
waitForExistence(app.tables["Bookmarks List"].cells.staticTexts["Example Domain"], timeout: 5)
// Check Login
navigator.performAction(Action.CloseBookmarkPanel)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(SettingsScreen)
navigator.nowAt(SettingsScreen)
navigator.goto(LoginsSettings)
waitForExistence(app.buttons.firstMatch)
app.buttons["Continue"].tap()
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let passcodeInput = springboard.secureTextFields["Passcode field"]
passcodeInput.tap()
passcodeInput.typeText("foo\n")
waitForExistence(app.tables["Login List"], timeout: 3)
// Verify the login
waitForExistence(app.staticTexts["https://accounts.google.com"])
// Disconnect account
navigator.goto(SettingsScreen)
app.tables.cells.element(boundBy: 1).tap()
waitForExistence(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"], timeout: 10)
app.cells["SignOut"].tap()
waitForExistence(app.buttons["Disconnect"], timeout: 5)
app.buttons["Disconnect"].tap()
sleep(3)
// Connect same account again
navigator.nowAt(SettingsScreen)
app.tables.cells["SignInToSync"].tap()
app.buttons["EmailSignIn.button"].tap()
waitForExistence(app.secureTextFields.element(boundBy: 0), timeout: 10)
app.secureTextFields.element(boundBy: 0).tap()
app.secureTextFields.element(boundBy: 0).typeText(userState.fxaPassword!)
waitForExistence(app.webViews.buttons.element(boundBy: 0), timeout: 5)
app.webViews.buttons.element(boundBy: 0).tap()
navigator.nowAt(SettingsScreen)
waitForExistence(app.tables.staticTexts["Sync Now"], timeout: 35)
// Check Bookmarks
navigator.goto(LibraryPanel_Bookmarks)
waitForExistence(app.tables["Bookmarks List"].cells.staticTexts["Example Domain"], timeout: 5)
// Check Logins
navigator.performAction(Action.CloseBookmarkPanel)
navigator.nowAt(NewTabScreen)
navigator.goto(BrowserTabMenu)
navigator.goto(SettingsScreen)
navigator.goto(LoginsSettings)
passcodeInput.tap()
passcodeInput.typeText("foo\n")
waitForExistence(app.tables["Login List"], timeout: 10)
waitForExistence(app.staticTexts["https://accounts.google.com"], timeout: 10)
}
}
| mpl-2.0 | f65d93de5b3c10dcaed4b37818a9d9b1 | 38.616883 | 146 | 0.672841 | 4.996724 | false | true | false | false |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/Chula Expo 2017/Main_LoginAndRegistration/RegisterViewController.swift | 1 | 30713 | //
// RegisterViewController.swift
// Chula Expo 2017
//
// Created by Pakpoom on 2/5/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
import CoreData
import Alamofire
class RegisterViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
var isFrameMove = false
var activeField = UITextField()
var userType: String!
var name: String!
var firstName: String!
var lastName: String!
var email: String!
var fbId: String!
var fbToken: String!
var fbImageProfileUrl: String?
var fbImage: UIImage!
var managedObjectContext: NSManagedObjectContext?
var userToken: String?
let gender = ["-", "ชาย", "หญิง", "อื่น ๆ"]
let education = ["มัธยมต้น", "มัธยมปลาย", "ปริญญาตรี", "ปริญญาโท", "ปริญญาเอก", "อื่น ๆ"]
let educationYear = ["มัธยมต้น": ["ม.1", "ม.2", "ม.3"],
"มัธยมปลาย": ["ม.4", "ม.5", "ม.6"],
"ปริญญาตรี": ["ปี 1", "ปี 2", "ปี 3", "ปี 4", "ปี 5", "ปี 6", "ปี 7", "ปี 8"],
"ปริญญาโท": ["ปี 1", "ปี 2", "ปี 3", "ปี 4"],
"ปริญญาเอก": ["ปี 1", "ปี 2", "ปี 3", "ปี 4"],
"อื่น ๆ": ["ปี 1", "ปี 2", "ปี 3", "ปี 4", "ปี 5", "ปี6"]]
let career = ["เกษตรกร",
"เจ้าหน้าที่รัฐบาล",
"เภสัชกร",
"แพทย์",
"โฆษก",
"โปรแกรมเมอร์",
"กวี",
"การประมง",
"การฝีมือ",
"การส่งเสริมอาชีพ",
"ข้าราชการ",
"คนขับรถแท็กซี่",
"ครู",
"คอลัมนิสต์",
"จิตรกร",
"ช่างทำเครื่องดนตรี",
"ช่างทำผม",
"ตำรวจ",
"ตุลาการ",
"ทนายความ",
"ทหาร",
"ธุรกิจส่วนตัว",
"นักเขียน",
"นักเขียนบทภาพยนตร์",
"นักเคลื่อนไหว",
"นักเศรษฐศาสตร์",
"นักแต่งเพลง",
"นักแปล",
"นักแสดง",
"นักโบราณคดี",
"นักโภชนาการ",
"นักกฎหมาย",
"นักการเมือง",
"นักการกุศล",
"นักการทูต",
"นักการธนาคาร",
"นักการศึกษา",
"นักกีฬา",
"นักข่าว",
"นักคณิตศาสตร์",
"นักจัดรายการวิทยุ",
"นักจิตวิทยา",
"นักชีววิทยา",
"นักดนตรี",
"นักดาราศาสตร์",
"นักถ่ายภาพ",
"นักธุรกิจ",
"นักบวช",
"นักบัญชี",
"นักบิน",
"นักบินอวกาศ",
"นักประชาสัมพันธ์",
"นักประดิษฐ์",
"นักประวัติศาสตร์",
"นักประวัติศาสตร์ศิลป์",
"นักปรัชญา",
"นักปีนเขา",
"นักผจญภัย",
"นักพากย์",
"นักภาษาศาสตร์",
"นักมายากล",
"นักร้อง",
"นักวาดการ์ตูน",
"นักวิจารณ์ภาพยนตร์",
"นักวิทยาศาสตร์",
"นักสะสมศิลปะ",
"นักสังคมวิทยา",
"นักสังคมศาสตร์",
"นักสัตววิทยา",
"นักสำรวจ",
"นักสืบ",
"นักหนังสือพิมพ์",
"นักอนุรักษ์ธรรมชาติ",
"นักออกแบบ",
"นักออกแบบเสื้อผ้า",
"นักออกแบบกราฟิก",
"นางแบบ",
"นางงาม",
"นายแบบ",
"บรรณาธิการ",
"บุคคลในวงการคอมพิวเตอร์",
"บุคคลในวงการพลศึกษา",
"บุคคลในวงการวรรณกรรม",
"บุคคลด้านสื่อ",
"ผู้เชี่ยวชาญด้านศาสนาพุทธ",
"ผู้กำกับ",
"ผู้กำกับภาพยนตร์",
"ผู้กำกับละครโทรทัศน์",
"ผู้จัดพิมพ์ (บุคคล)",
"ผู้ประกาศข่าว",
"ผู้พิพากษาไทย",
"ผู้มีชื่อเสียง",
"ผู้อำนวยการสร้างภาพยนตร์",
"พยาบาล",
"พิธีกร",
"ฟรีแลนซ์",
"ภูมิสถาปนิก",
"รัฐวิสาหกิจ",
"ว่างงาน",
"วาทยกร",
"วิชาชีพทางด้านสาธารณสุข",
"วิศวกร",
"วีเจ",
"ศิลปิน",
"สถาปนิก",
"อัยการ",
"อาจารย์",
"อาชีพการเดินเรือ",
"อาชีพการบันเทิง",
"อาชีพด้านอาหาร",
"อื่น ๆ"]
let agePicker = UIPickerView()
let genderPicker = UIPickerView()
let educationPicker = UIPickerView()
let educationYearPicker = UIPickerView()
let careerPicker = UIPickerView()
@IBOutlet var numberLabel: UILabel!
@IBOutlet var profileImage: UIImageView!
@IBOutlet var educationView: UIView!
@IBOutlet var educationYearView: UIView!
@IBOutlet var schoolView: UIView!
@IBOutlet var careerView: UIView!
@IBOutlet var firstNameField: UITextField!
@IBOutlet var lastNameField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var ageField: UITextField!
@IBOutlet var genderField: UITextField!
@IBOutlet var educationField: UITextField!
@IBOutlet var educationYearField: UITextField!
@IBOutlet var schoolField: UITextField!
@IBOutlet var careerField: UITextField!
var toEdit = false
var userData: UserData?
@IBOutlet weak var cancelEdit: UIButton!
@IBOutlet weak var saveEdit: UIButton!
@IBOutlet weak var nextButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if toEdit {
nextButton.isHidden = true
cancelEdit.isHidden = false
saveEdit.isHidden = false
}
// addChangeProfileImageGesture()
initialValue()
initialField()
initialPicker()
NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
override func viewDidLayoutSubviews() {
numberLabel.layer.cornerRadius = numberLabel.frame.height / 2
profileImage.layer.borderColor = UIColor(red: 0.1725, green: 0.1922, blue: 0.2471, alpha: 1).cgColor
profileImage.layer.borderWidth = 3
profileImage.layer.cornerRadius = profileImage.frame.height / 2
profileImage.layer.masksToBounds = true
// cameraIconView.layer.cornerRadius = cameraIconView.frame.height / 2
// cameraIconView.layer.masksToBounds = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toInterested" {
let destination = segue.destination as! interestViewController
destination.userType = self.userType
destination.name = "\(firstNameField.text!) \(lastNameField.text!)"
destination.email = emailField.text
destination.age = ageField.text
destination.gender = genderField.text
destination.fbId = self.fbId
destination.fbToken = self.fbToken
destination.fbImageProfileUrl = self.fbImageProfileUrl!
destination.fbImage = self.fbImage!
destination.managedObjectContext = self.managedObjectContext
if self.userType == "Academic" {
destination.education = educationField.text
destination.educationYear = educationYearField.text
destination.school = schoolField.text
destination.career = ""
} else {
destination.education = ""
destination.educationYear = ""
destination.school = ""
destination.career = careerField.text
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.tag == 5 && userType == "Worker" {
let nextField = self.view.viewWithTag(10) as! UITextField
nextField.becomeFirstResponder()
} else if let nextField = self.view.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
return false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification) {
if !isFrameMove {
let heightToDecrease = self.view.bounds.height * 0.15
isFrameMove = true
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.1, animations: {
self.view.transform = CGAffineTransform(translationX: 0, y: -(keyboardSize.height - heightToDecrease))
})
}
}
}
func keyboardWillHide(notification: NSNotification) {
if isFrameMove {
isFrameMove = false
UIView.animate(withDuration: 0.5, animations: {
self.view.transform = CGAffineTransform(translationX: 0, y: 0)
})
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
profileImage.image = image
} else {
print("error while access photo library")
}
self.dismiss(animated: true, completion: nil)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == agePicker {
//age
return 100
} else if pickerView == genderPicker {
return gender.count
} else if pickerView == educationPicker {
return education.count
} else if pickerView == educationYearPicker {
return educationYear[educationField.text!]!.count
} else {
return career.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == agePicker {
if row == 0 {
return "-"
} else {
return "\(row + 10)"
}
} else if pickerView == genderPicker {
return gender[row]
} else if pickerView == educationPicker {
return education[row]
} else if pickerView == educationYearPicker {
return educationYear[educationField.text!]?[row]
} else {
return career[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == agePicker {
if row == 0 {
ageField.text = "-"
} else {
ageField.text = "\(row + 10)"
}
} else if pickerView == genderPicker {
genderField.text = gender[row]
} else if pickerView == educationPicker {
educationField.text = education[row]
educationYearField.text = educationYear[educationField.text!]?[0]
educationYearPicker.selectRow(0, inComponent: 0, animated: false)
} else if pickerView == educationYearPicker {
educationYearField.text = educationYear[educationField.text!]?[row]
} else {
careerField.text = career[row]
}
}
// private func addChangeProfileImageGesture() {
//
// let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.changeProfilePicture))
// tapGestureRecognizer.numberOfTapsRequired = 1
// profileImage.isUserInteractionEnabled = true
// profileImage.addGestureRecognizer(tapGestureRecognizer)
//
// }
// func changeProfilePicture() {
//
// let imagePickerController = UIImagePickerController()
//
// imagePickerController.delegate = self
//
// imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
//
// imagePickerController.allowsEditing = false
//
// self.present(imagePickerController, animated: true, completion: nil)
//
// }
private func initialValue() {
if self.fbImage != nil {
profileImage.image = self.fbImage
}
if toEdit {
if let facebookProfileUrl = URL(string: (userData?.profile)!) {
if let data = NSData(contentsOf: facebookProfileUrl) {
profileImage.image = UIImage(data: data as Data)
}
}
if let name = userData?.name?.components(separatedBy: " ") {
if name.count > 1 {
self.firstNameField.text = name[0]
self.lastNameField.text = name[1]
} else {
self.firstNameField.text = name[0]
}
}
if let gender = userData?.gender {
if gender == "Male" {
self.genderField.text = "ชาย"
} else if gender == "Female" {
self.genderField.text = "หญิง"
} else {
self.genderField.text = "อื่น ๆ"
}
}
self.emailField.text = userData?.email
self.ageField.text = String(Int((userData?.age)!))
self.careerField.text = userData?.job
self.educationYearField.text = userData?.year
self.educationField.text = userData?.level
self.schoolField.text = userData?.school
} else {
firstNameField.text = self.firstName
lastNameField.text = self.lastName
emailField.text = self.email
}
}
private func initialField() {
// if let UT: String = userType {
if userType == "Worker" {
educationView.alpha = 0
educationYearView.alpha = 0
schoolView.alpha = 0
careerView.alpha = 1
}
// }
}
private func initialPicker() {
let toolbar = UIToolbar()
toolbar.barStyle = UIBarStyle.default
toolbar.isTranslucent = true
toolbar.sizeToFit()
let nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.done, target: self, action: #selector(RegisterViewController.pickerNext))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
toolbar.setItems([spaceButton, nextButton], animated: true)
toolbar.isUserInteractionEnabled = true
agePicker.delegate = self
agePicker.dataSource = self
ageField.inputView = agePicker
ageField.inputAccessoryView = toolbar
genderPicker.delegate = self
genderPicker.dataSource = self
genderField.inputView = genderPicker
genderField.inputAccessoryView = toolbar
educationPicker.delegate = self
educationPicker.dataSource = self
educationField.inputView = educationPicker
educationField.inputAccessoryView = toolbar
educationYearPicker.delegate = self
educationYearPicker.dataSource = self
educationYearField.inputView = educationYearPicker
educationYearField.inputAccessoryView = toolbar
careerPicker.delegate = self
careerPicker.dataSource = self
careerField.inputView = careerPicker
careerField.inputAccessoryView = toolbar
}
func pickerNext() {
if activeField.tag == 5 && userType == "Worker" {
let nextField = self.view.viewWithTag(10) as! UITextField
nextField.becomeFirstResponder()
} else if let nextField = self.view.viewWithTag(activeField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
activeField.resignFirstResponder()
}
}
@IBAction func next(_ sender: UIButton) {
if userType == "Academic" {
if firstNameField.text == "" || lastNameField.text == "" || emailField.text == "" || ageField.text == "" || genderField.text == "" || educationField.text == "" || educationYearField.text == "" || schoolField.text == "" {
let confirm = UIAlertController(title: "เกิดข้อผิดพลาด", message: "กรุณากรอกข้อมูลให้ครบถ้วน", preferredStyle: UIAlertControllerStyle.alert)
confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(confirm, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "toInterested", sender: self)
}
} else {
if firstNameField.text == "" || lastNameField.text == "" || emailField.text == "" || ageField.text == "" || genderField.text == "" || careerField.text == "" {
let confirm = UIAlertController(title: "เกิดข้อผิดพลาด", message: "กรุณากรอกข้อมูลให้ครบถ้วน", preferredStyle: UIAlertControllerStyle.alert)
confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(confirm, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "toInterested", sender: self)
}
}
}
@IBAction func save(_ sender: UIButton) {
if self.genderField.text == "ชาย" {
self.genderField.text = "Male"
} else if self.genderField.text == "หญิง" {
self.genderField.text = "Female"
} else {
self.genderField.text = "Other"
}
if self.ageField.text == "-" {
self.ageField.text = "0"
}
var parameters = [String: Any]()
if self.userType == "Academic" {
if let academicLevel = self.educationField.text,
let academicYear = self.educationYearField.text,
let academicSchool = self.schoolField.text,
let gender = self.genderField.text
{
parameters = [
"type": "Academic",
"name": "\(self.firstNameField.text!) \(self.lastNameField.text!)",
"email": self.emailField.text!,
"age": Int(self.ageField.text!) ?? 0,
"academicLevel": academicLevel,
"academicYear": academicYear,
"academicSchool": academicSchool,
"gender": gender
]
}
} else {
if let career = self.careerField.text,
let gender = self.genderField.text
{
parameters = [
"type": "Worker",
"name": "\(self.firstNameField.text!) \(self.lastNameField.text!)",
"email": self.emailField.text!,
"age": Int(self.ageField.text!) ?? 0,
"workerJob": career,
"gender": gender
]
}
}
let header: HTTPHeaders = ["Authorization": "JWT \((userData?.token)!)"]
Alamofire.request("https://staff.chulaexpo.com/api/me", method: .put, parameters: parameters, headers: header).responseJSON { response in
if response.result.isSuccess {
Alamofire.request("https://staff.chulaexpo.com/api/me", headers: header).responseJSON { response in
if response.result.isSuccess {
let JSON = response.result.value as! NSDictionary
if let results = JSON["results"] as? NSDictionary{
let academic = results["academic"] as? [String: String]
let worker = results["worker"] as? [String: String]
let managedObjectContext: NSManagedObjectContext? =
(UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
managedObjectContext?.performAndWait {
_ = UserData.addUser(id: results["_id"] as! String,
token: "",
type: results["type"] as! String,
name: results["name"] as! String,
email: results["email"] as! String,
age: results["age"] as! Int,
gender: results["gender"] as! String,
school: academic?["school"] ?? "",
level: academic?["level"] ?? "",
year: academic?["year"] ?? "",
job: worker?["job"] ?? "",
profile: results["profile"] as? String ?? "",
inManageobjectcontext: managedObjectContext!
)
}
do {
try managedObjectContext?.save()
print("saved user")
} catch let error {
print("saveUserError with \(error)")
}
}
self.performSegue(withIdentifier: "endEdit", sender: self)
} else {
let confirm = UIAlertController(title: "Error", message: "Can't connect to the server, please try again.", preferredStyle: UIAlertControllerStyle.alert)
confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(confirm, animated: true, completion: nil)
}
}
} else {
let confirm = UIAlertController(title: "Error", message: "Can't connect to the server, please try again.", preferredStyle: UIAlertControllerStyle.alert)
confirm.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(confirm, animated: true, completion: nil)
}
}
}
@IBAction func cancel(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| mit | 53a5dc7c0678dba681de99667ccdc9c1 | 32.823961 | 232 | 0.448677 | 4.765415 | false | false | false | false |
Atelier-Shiori/anitomy-for-cocoa | anitomy-swift-demo/anitomy-swift-demo/AppDelegate.swift | 1 | 1270 | //
// AppDelegate.swift
// anitomy-swift-demo
//
// Created by 桐間紗路 on 2016/12/24.
// Copyright © 2016年 Atelier Shiori. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var output: NSTextView!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@objc func windowWillClose(_ aNotification: Notification) {
// Close Application if window is closed
NSApplication.shared.terminate(nil)
}
@IBAction func recognize(sender : NSButton){
let op = NSOpenPanel()
op.allowedFileTypes = Array(arrayLiteral: "mkv","mp4", "avi","ogm")
op.title = "Select Media File"
op.message = "Select a media file to test."
let result = op.runModal()
if result.rawValue == NSFileHandlingPanelCancelButton{
return;
}
let d = anitomy_bridge().tokenize(op.url?.lastPathComponent)
output.string = String(format: "%@", d!)
}
}
| mpl-2.0 | 2e41e39163e0eeca302360e2dc72868b | 26.977778 | 75 | 0.658459 | 4.480427 | false | false | false | false |
adrfer/swift | test/SILGen/struct_resilience.swift | 1 | 7094 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s
import resilient_struct
// Resilient structs are always address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@out Size, @in Size, @owned @callee_owned (@out Size, @in Size) -> ()) -> ()
// CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@out Size, @in Size) -> ()):
func functionWithResilientTypes(s: Size, f: Size -> Size) -> Size {
// Stored properties of resilient structs from outside our resilience
// domain are accessed through accessors
// CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size
var s2 = s
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> ()
// CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]])
s2.w = s.w
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// Fixed-layout structs may be trivial or loadable
// CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point
// CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point):
func functionWithFixedLayoutTypes(p: Point, f: Point -> Point) -> Point {
// Stored properties of fixed layout structs are accessed directly
var p2 = p
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x
// CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x
// CHECK: assign [[RESULT]] to [[DEST]] : $*Int
p2.x = p.x
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y
_ = p.y
// CHECK: [[NEW_POINT:%.*]] = apply %1(%0)
// CHECK: return [[NEW_POINT]]
return f(p)
}
// Fixed-layout struct with resilient stored properties is still address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@out Rectangle, @in Rectangle, @owned @callee_owned (@out Rectangle, @in Rectangle) -> ()) -> ()
// CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@out Rectangle, @in Rectangle) -> ()):
func functionWithFixedLayoutOfResilientTypes(r: Rectangle, f: Rectangle -> Rectangle) -> Rectangle {
return f(r)
}
// Make sure we generate getters and setters for stored properties of
// resilient structs
public struct MySize {
// Static computed property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(thin) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(thin) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>)
public static var expiration: Int {
get { return copyright + 70 }
set { copyright = newValue - 70 }
}
// Instance computed property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>)
public var d: Int {
get { return 0 }
set { }
}
// Instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>)
public var w: Int
// Read-only instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int
public let h: Int
// Static stored property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(thin) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(thin) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>)
public static var copyright: Int = 0
}
// CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@out MySize, @in MySize, @owned @callee_owned (@out MySize, @in MySize) -> ()) -> ()
public func functionWithMyResilientTypes(s: MySize, f: MySize -> MySize) -> MySize {
// Stored properties of resilient structs from inside our resilience
// domain are accessed directly
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize
var s2 = s
// CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w
// CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int
// CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w
// CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int
s2.w = s.w
// CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h
// CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
| apache-2.0 | f2ef24ede1bcd796ec9c89fd3f609430 | 52.338346 | 319 | 0.661545 | 3.520596 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/ContractsPresenter.swift | 2 | 2379 | //
// ContractsPresenter.swift
// Neocom
//
// Created by Artem Shimanski on 11/12/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import TreeController
class ContractsPresenter: TreePresenter {
typealias View = ContractsViewController
typealias Interactor = ContractsInteractor
typealias Presentation = [Tree.Item.RoutableRow<Tree.Content.Contract>]
weak var view: View?
lazy var interactor: Interactor! = Interactor(presenter: self)
var content: Interactor.Content?
var presentation: Presentation?
var loading: Future<Presentation>?
required init(view: View) {
self.view = view
}
func configure() {
view?.tableView.register([Prototype.ContractCell.default])
interactor.configure()
applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in
self?.applicationWillEnterForeground()
}
}
private var applicationWillEnterForegroundObserver: NotificationObserver?
func presentation(for content: Interactor.Content) -> Future<Presentation> {
guard let characterID = Services.storage.viewContext.currentAccount?.characterID else {return .init(.failure(NCError.authenticationRequired))}
var contracts = content.value.contracts.map { contract -> Tree.Content.Contract in
let endDate: Date = contract.dateCompleted ?? {
guard let date = contract.dateAccepted, let duration = contract.daysToComplete else {return nil}
return date.addingTimeInterval(TimeInterval(duration) * 24 * 3600)
}() ?? contract.dateExpired
return Tree.Content.Contract(prototype: Prototype.ContractCell.default,
contract: contract,
issuer: content.value.contacts?[Int64(contract.issuerID)],
location: (contract.startLocationID).flatMap{content.value.locations?[$0]} ?? EVELocation.unknown,
endDate: endDate,
characterID: characterID)
}
let i = contracts.partition{$0.contract.isOpen}
let open = contracts[i...]
let closed = contracts[..<i]
let rows = open.sorted {$0.contract.dateExpired < $1.contract.dateExpired} +
closed.sorted{$0.endDate > $1.endDate}
return .init(rows.map { Tree.Item.RoutableRow($0, route: Router.Business.contractInfo($0.contract)) })
}
}
| lgpl-2.1 | 3026b291e93f80fcbfabf413d48177cd | 35.030303 | 200 | 0.746005 | 4.157343 | false | false | false | false |
seanoshea/computer-science-in-swift | computer-science-in-swift/BinarySearch.swift | 1 | 1755 | // Copyright (c) 2015-2016 Sean O'Shea. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class BinarySearch {
func binarySearch(_ items: [Int], value: Int) -> Int? {
var startIndex = 0
var stopIndex = items.count - 1
var middle = startIndex + ((stopIndex - startIndex) / 2)
while items[middle] != value && startIndex < stopIndex {
if value < items[middle] {
stopIndex = middle - 1
} else if value > items[middle] {
startIndex = middle + 1
}
middle = Int(floor(CDouble((stopIndex + startIndex) / 2)))
}
return (items[middle] == value) ? middle : nil
}
}
| mit | 0d11b41c6b08364d7a6df50e397c1346 | 44 | 80 | 0.683191 | 4.558442 | false | false | false | false |
mcjg/MGAUIKit | MGAUIKit/MGAUIKit/MGATextField.swift | 1 | 2028 | //
// MGATextField.swift
// MGUIKit
//
// Created by matt on 21/09/2015.
// Copyright © 2015 Matthew Green Associates. All rights reserved.
//
import UIKit
@IBDesignable public class MGATextField: UITextField {
// BORDER COLOR
// ------------
@IBInspectable public var borderColor:UIColor = UIColor.grayColor() {
didSet { self.layer.borderColor = borderColor.CGColor }
}
// BORDER WIDTH
// ------------
@IBInspectable public var borderWidth:CGFloat = 0.0 {
didSet { self.layer.borderWidth = borderWidth }
}
// CORNER RADIUS
// -------------
@IBInspectable public var cornerRadius:CGFloat = 0.0 {
didSet { self.layer.cornerRadius = cornerRadius }
}
// PLACEHOLDER COLOR
// -----------------
@IBInspectable public var placeholderColor:UIColor = UIColor.grayColor() {
didSet {
if let placeholderText = placeholder {
self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName:placeholderColor])
}
}
}
// PADDING
// -------
@IBInspectable public var paddingHorizontal:CGFloat = 0.0
@IBInspectable public var paddingVertical:CGFloat = 0.0
override public func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectMake(bounds.origin.x + paddingHorizontal, bounds.origin.y + paddingVertical, bounds.size.width - (paddingHorizontal * 2), bounds.size.height - (paddingVertical * 2))
}
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
// MAKE DEFAULT BORDER STYLE NONE
// ------------------------------
override init(frame: CGRect) {
super.init(frame: frame)
self.borderStyle = .None
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.borderStyle = .None
}
}
| mit | 5e1f1dce13026f503fe803c3d5fe3b3b | 27.152778 | 186 | 0.606315 | 4.919903 | false | false | false | false |
somedev/animations-in-ios | Animations-in-iOS/Animations-in-iOS/Classes/TransformTableViewController.swift | 1 | 2401 | //
// TransformTableViewController.swift
// Animations-in-iOS
//
// Created by Eduard Panasiuk on 1/2/15.
// Copyright (c) 2015 Eduard Panasiuk. All rights reserved.
//
import UIKit
//implementation is based on this article: http://www.thinkandbuild.it/animating-uitableview-cells
class TransformTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
clearsSelectionOnViewWillAppear = false
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TitleCell", forIndexPath: indexPath) as? UITableViewCell
if let cell = cell {
cell.textLabel?.text = "Table cell #\(indexPath.row)"
return cell
}
else {
return UITableViewCell()
}
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//1. Setup the CATransform3D structure
let angle = CGFloat(90*M_PI/180)
var rotation = CATransform3DMakeRotation(angle, 0.0, 0.7, 0.4)
rotation.m34 = 1.0 / -600;
//2. Define the initial state (Before the animation)
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOffset = CGSizeMake(10, 10);
cell.alpha = 0;
cell.layer.transform = rotation;
cell.layer.anchorPoint = CGPointMake(0, 0.5);
if(cell.layer.position.x != 0){
cell.layer.position = CGPointMake(0, cell.layer.position.y);
}
//3. Define the final state (After the animation) and commit the animation
UIView.beginAnimations("some animation", context: nil)
UIView.setAnimationDuration(0.5)
cell.layer.transform = CATransform3DIdentity;
cell.alpha = 1;
cell.layer.shadowOffset = CGSizeMake(0, 0);
UIView.commitAnimations()
}
}
| mit | 8a0a53e8ebbee5a9921400f82c56a5b2 | 30.181818 | 134 | 0.640983 | 4.830986 | false | false | false | false |
Magnat12/MGExtraSwift | MGExtraSwift/Classes/UIView+MGExtra.swift | 1 | 2039 | //
// UIView+MGExtra.swift
// Worktender
//
// Created by Vitaliy Gozhenko on 14/02/16.
// Copyright © 2016 Appstructors. All rights reserved.
//
import UIKit
extension UIView {
public var centerOfView:CGPoint {
return CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable public var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
} else {
return nil
}
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
public var x:CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame.origin.x = newValue
}
}
public var y:CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame.origin.y = newValue
}
}
public var width:CGFloat {
get {
return self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
public var height:CGFloat {
get {
return self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
public var bottomYPoint:CGFloat {
get {
return self.frame.origin.y + self.frame.size.height
}
}
public var rightXPoint:CGFloat {
get {
return self.frame.origin.x + self.frame.size.width
}
}
public var viewController: UIViewController? {
var responder: UIResponder? = self
while responder != nil {
if let responder = responder as? UIViewController {
return responder
}
responder = responder?.next
}
return nil
}
public func findViewsOfClass<T:UIView>(viewClass: T.Type) -> [T] {
var views: [T] = []
for subview in subviews {
if subview is T {
views.append(subview as! T)
}
views.append(contentsOf: subview.findViewsOfClass(viewClass: T.self))
}
return views
}
}
| mit | 4ae4c96879ac2739e4e509202baf6ad6 | 16.12605 | 72 | 0.656035 | 3.083207 | false | false | false | false |
easyui/Alamofire | Source/MultipartUpload.swift | 2 | 3389 | //
// MultipartUpload.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Internal type which encapsulates a `MultipartFormData` upload.
final class MultipartUpload {
lazy var result = Result { try build() }
@Protected
private(set) var multipartFormData: MultipartFormData
let encodingMemoryThreshold: UInt64
let request: URLRequestConvertible
let fileManager: FileManager
init(encodingMemoryThreshold: UInt64,
request: URLRequestConvertible,
multipartFormData: MultipartFormData) {
self.encodingMemoryThreshold = encodingMemoryThreshold
self.request = request
fileManager = multipartFormData.fileManager
self.multipartFormData = multipartFormData
}
func build() throws -> UploadRequest.Uploadable {
let uploadable: UploadRequest.Uploadable
if multipartFormData.contentLength < encodingMemoryThreshold {
let data = try multipartFormData.encode()
uploadable = .data(data)
} else {
let tempDirectoryURL = fileManager.temporaryDirectory
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
do {
try multipartFormData.writeEncodedData(to: fileURL)
} catch {
// Cleanup after attempted write if it fails.
try? fileManager.removeItem(at: fileURL)
throw error
}
uploadable = .file(fileURL, shouldRemove: true)
}
return uploadable
}
}
extension MultipartUpload: UploadConvertible {
func asURLRequest() throws -> URLRequest {
var urlRequest = try request.asURLRequest()
$multipartFormData.read { multipartFormData in
urlRequest.headers.add(.contentType(multipartFormData.contentType))
}
return urlRequest
}
func createUploadable() throws -> UploadRequest.Uploadable {
try result.get()
}
}
| mit | 67fb572d16ce968dfcd96fa9b00b720c | 37.078652 | 115 | 0.697551 | 5.362342 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Maps/Display a map SwiftUI/SwiftUIMapView.swift | 1 | 2666 | // Copyright 2021 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
//
// https://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 SwiftUI
import ArcGIS
struct SwiftUIMapView {
let map: AGSMap
let graphicsOverlays: [AGSGraphicsOverlay]
init(
map: AGSMap,
graphicsOverlays: [AGSGraphicsOverlay] = []
) {
self.map = map
self.graphicsOverlays = graphicsOverlays
}
private var onSingleTapAction: ((CGPoint, AGSPoint) -> Void)?
}
extension SwiftUIMapView {
/// Sets a closure to perform when a single tap occurs on the map view.
/// - Parameter action: The closure to perform upon single tap.
func onSingleTap(perform action: @escaping (CGPoint, AGSPoint) -> Void) -> Self {
var copy = self
copy.onSingleTapAction = action
return copy
}
}
extension SwiftUIMapView: UIViewRepresentable {
typealias UIViewType = AGSMapView
func makeCoordinator() -> Coordinator {
Coordinator(
onSingleTapAction: onSingleTapAction
)
}
func makeUIView(context: Context) -> AGSMapView {
let uiView = AGSMapView()
uiView.map = map
uiView.graphicsOverlays.setArray(graphicsOverlays)
uiView.touchDelegate = context.coordinator
return uiView
}
func updateUIView(_ uiView: AGSMapView, context: Context) {
if map != uiView.map {
uiView.map = map
}
if graphicsOverlays != uiView.graphicsOverlays as? [AGSGraphicsOverlay] {
uiView.graphicsOverlays.setArray(graphicsOverlays)
}
context.coordinator.onSingleTapAction = onSingleTapAction
}
}
extension SwiftUIMapView {
class Coordinator: NSObject {
var onSingleTapAction: ((CGPoint, AGSPoint) -> Void)?
init(
onSingleTapAction: ((CGPoint, AGSPoint) -> Void)?
) {
self.onSingleTapAction = onSingleTapAction
}
}
}
extension SwiftUIMapView.Coordinator: AGSGeoViewTouchDelegate {
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
onSingleTapAction?(screenPoint, mapPoint)
}
}
| apache-2.0 | a264d913bac403dd58fca2f17ba49355 | 29.643678 | 103 | 0.665791 | 4.735346 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/Tree/101_SymmetricTree.swift | 1 | 2673 | //
// 101_SymmetricTree.swift
// HRSwift
//
// Created by yansong li on 2016-08-06.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Title:101 Symmetric Tree
URL: https://leetcode.com/problems/symmetric-tree/
Space: O(n)
Time: O(n)
*/
class SymmetricTree_Solution {
/// Bonus points: Iterative
func isSymmetric(_ root: TreeNode?) -> Bool {
guard let root = root else {
return true
}
let original = self.treeToArray(root)
let switchedRoot = self.switchSubTree(root)
let switched = self.treeToArray(switchedRoot)
let comparison = zip(original, switched).map {
return $0 == $1
}.reduce(true) {
$0 && $1
}
return comparison
}
fileprivate func switchSubTree(_ root: TreeNode) -> TreeNode {
var switchedLeft: TreeNode?
var switchedRight: TreeNode?
if let left = root.left {
switchedLeft = switchSubTree(left)
}
if let right = root.right {
switchedRight = switchSubTree(right)
}
root.left = switchedRight
root.right = switchedLeft
return root
}
/// Use a queue to convert a tree to an array.
fileprivate func treeToArray(_ root: TreeNode?) -> [TreeValue] {
guard let root = root else {
return [TreeValue.empty]
}
var traversalQueue = Queue<TreeNode>()
var retVal: [TreeValue] = [.valid(root.val)]
traversalQueue.enqueue(root)
while !traversalQueue.isEmpty() {
let currentNode = traversalQueue.dequeue()!
if let left = currentNode.left {
retVal.append(.valid(left.val))
traversalQueue.enqueue(left)
} else {
retVal.append(.empty)
}
if let right = currentNode.right {
retVal.append(.valid(right.val))
traversalQueue.enqueue(right)
} else {
retVal.append(.empty)
}
}
return retVal
}
/// A simpler solution, recursive
func solutionTwo(_ root: TreeNode?) -> Bool {
guard let root = root else {
return true
}
return symmetricHelper(root.left, q: root.right)
}
fileprivate func symmetricHelper(_ p: TreeNode?, q: TreeNode?) -> Bool {
if p == nil && q == nil {
return true
}
if p == nil || q == nil || p?.val != q?.val {
return false
}
return symmetricHelper(p?.left, q: q?.right) && symmetricHelper(p?.right, q: q?.left)
}
}
enum TreeValue {
case valid(Int)
case empty
}
extension TreeValue: Equatable { }
func ==(lhs: TreeValue, rhs: TreeValue) -> Bool {
switch (lhs, rhs) {
case (.valid(let lval), .valid(let rval)):
return lval == rval
case (.empty, .empty):
return true
default:
return false
}
}
| mit | 9c88945ffdeb21f7a1d97d20f403f515 | 23.290909 | 89 | 0.619012 | 3.726639 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/MerchantPayment.swift | 1 | 1800 | //
// MerchantPayment.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 31/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class MerchantPayment : NSObject {
public var cardIssuerId : NSNumber = 0
public var cardToken : String!
public var campaignId : Int = 0
public var installments : Int = 0
public var item : Item!
public var merchantAccessToken : String!
public var paymentMethodId : String!
public override init() {
super.init()
}
public init(item: Item, installments: Int, cardIssuerId: NSNumber, token: String, paymentMethodId: String, campaignId: Int, merchantAccessToken: String) {
self.item = item
self.installments = installments
self.cardIssuerId = cardIssuerId
self.cardToken = token
self.paymentMethodId = paymentMethodId
self.campaignId = campaignId
self.merchantAccessToken = merchantAccessToken
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"card_issuer_id": self.cardIssuerId == 0 ? JSON.null : self.cardIssuerId,
"card_token": self.cardToken == nil ? JSON.null : self.cardToken!,
"campaign_id": self.campaignId == 0 ? JSON.null : String(self.campaignId),
"item": self.item == nil ? JSON.null : JSON.parse(self.item!.toJSONString()).mutableCopyOfTheObject(),
"installments" : self.installments == 0 ? JSON.null : self.installments,
"merchant_access_token" : self.merchantAccessToken == nil ? JSON.null : self.merchantAccessToken!,
"payment_method_id" : self.paymentMethodId == nil ? JSON.null : self.paymentMethodId!
]
return JSON(obj).toString()
}
} | mit | 634e79ae2911b062c3d2682062baf95a | 37.319149 | 158 | 0.648333 | 4.316547 | false | false | false | false |
tbkka/swift-protobuf | Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift | 3 | 14839 | // Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift - A helper that generates SwiftProtobuf names.
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// A helper that can generate SwiftProtobuf names from types.
///
// -----------------------------------------------------------------------------
import Foundation
public final class SwiftProtobufNamer {
var filePrefixCache = [String:String]()
var enumValueRelativeNameCache = [String:String]()
var mappings: ProtoFileToModuleMappings
var targetModule: String
public var swiftProtobufModuleName: String { return mappings.swiftProtobufModuleName }
/// Initializes a a new namer, assuming everything will be in the same Swift module.
public convenience init() {
self.init(protoFileToModuleMappings: ProtoFileToModuleMappings(), targetModule: "")
}
/// Initializes a a new namer. All names will be generated as from the pov of the
/// given file using the provided file to module mapper.
public convenience init(
currentFile file: FileDescriptor,
protoFileToModuleMappings mappings: ProtoFileToModuleMappings
) {
let targetModule = mappings.moduleName(forFile: file) ?? ""
self.init(protoFileToModuleMappings: mappings, targetModule: targetModule)
}
/// Internal initializer.
init(
protoFileToModuleMappings mappings: ProtoFileToModuleMappings,
targetModule: String
) {
self.mappings = mappings
self.targetModule = targetModule
}
/// Calculate the relative name for the given message.
public func relativeName(message: Descriptor) -> String {
if message.containingType != nil {
return NamingUtils.sanitize(messageName: message.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
} else {
let prefix = typePrefix(forFile: message.file)
return NamingUtils.sanitize(messageName: prefix + message.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
}
}
/// Calculate the full name for the given message.
public func fullName(message: Descriptor) -> String {
let relativeName = self.relativeName(message: message)
guard let containingType = message.containingType else {
return modulePrefix(file: message.file) + relativeName
}
return fullName(message:containingType) + "." + relativeName
}
/// Calculate the relative name for the given enum.
public func relativeName(enum e: EnumDescriptor) -> String {
if e.containingType != nil {
return NamingUtils.sanitize(enumName: e.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
} else {
let prefix = typePrefix(forFile: e.file)
return NamingUtils.sanitize(enumName: prefix + e.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
}
}
/// Calculate the full name for the given enum.
public func fullName(enum e: EnumDescriptor) -> String {
let relativeName = self.relativeName(enum: e)
guard let containingType = e.containingType else {
return modulePrefix(file: e.file) + relativeName
}
return fullName(message: containingType) + "." + relativeName
}
/// Compute the short names to use for the values of this enum.
private func computeRelativeNames(enum e: EnumDescriptor) {
let stripper = NamingUtils.PrefixStripper(prefix: e.name)
/// Determine the initial candidate name for the name before
/// doing duplicate checks.
func candidateName(_ enumValue: EnumValueDescriptor) -> String {
let baseName = enumValue.name
if let stripped = stripper.strip(from: baseName) {
return NamingUtils.toLowerCamelCase(stripped)
}
return NamingUtils.toLowerCamelCase(baseName)
}
// Bucketed based on candidate names to check for duplicates.
let candidates :[String:[EnumValueDescriptor]] = e.values.reduce(into: [:]) {
$0[candidateName($1), default:[]].append($1)
}
for (camelCased, enumValues) in candidates {
// If there is only one, sanitize and cache it.
guard enumValues.count > 1 else {
enumValueRelativeNameCache[enumValues.first!.fullName] =
NamingUtils.sanitize(enumCaseName: camelCased)
continue
}
// There are two possible cases:
// 1. There is the main entry and then all aliases for it that
// happen to be the same after the prefix was stripped.
// 2. There are atleast two values (there could also be aliases).
//
// For the first case, there's no need to do anything, we'll go
// with just one Swift version. For the second, append "_#" to
// the names to help make the different Swift versions clear
// which they are.
let firstValue = enumValues.first!.number
let hasMultipleValues = enumValues.contains(where: { return $0.number != firstValue })
guard hasMultipleValues else {
// Was the first case, all one value, just aliases that mapped
// to the same name.
let name = NamingUtils.sanitize(enumCaseName: camelCased)
for e in enumValues {
enumValueRelativeNameCache[e.fullName] = name
}
continue
}
for e in enumValues {
// Can't put a negative size, so use "n" and make the number
// positive.
let suffix = e.number >= 0 ? "_\(e.number)" : "_n\(-e.number)"
enumValueRelativeNameCache[e.fullName] =
NamingUtils.sanitize(enumCaseName: camelCased + suffix)
}
}
}
/// Calculate the relative name for the given enum value.
public func relativeName(enumValue: EnumValueDescriptor) -> String {
if let name = enumValueRelativeNameCache[enumValue.fullName] {
return name
}
computeRelativeNames(enum: enumValue.enumType)
return enumValueRelativeNameCache[enumValue.fullName]!
}
/// Calculate the full name for the given enum value.
public func fullName(enumValue: EnumValueDescriptor) -> String {
return fullName(enum: enumValue.enumType) + "." + relativeName(enumValue: enumValue)
}
/// The relative name with a leading dot so it can be used where
/// the type is known.
public func dottedRelativeName(enumValue: EnumValueDescriptor) -> String {
let relativeName = self.relativeName(enumValue: enumValue)
return "." + NamingUtils.trimBackticks(relativeName)
}
/// Filters the Enum's values to those that will have unique Swift
/// names. Only poorly named proto enum alias values get filtered
/// away, so the assumption is they aren't really needed from an
/// api pov.
public func uniquelyNamedValues(enum e: EnumDescriptor) -> [EnumValueDescriptor] {
return e.values.filter {
// Original are kept as is. The computations for relative
// name already adds values for collisions with different
// values.
guard let aliasOf = $0.aliasOf else { return true }
let relativeName = self.relativeName(enumValue: $0)
let aliasOfRelativeName = self.relativeName(enumValue: aliasOf)
// If the relative name matches for the alias and original, drop
// the alias.
guard relativeName != aliasOfRelativeName else { return false }
// Only include this alias if it is the first one with this name.
// (handles alias with different cases in their names that get
// mangled to a single Swift name.)
let firstAlias = aliasOf.aliases.firstIndex {
let otherRelativeName = self.relativeName(enumValue: $0)
return relativeName == otherRelativeName
}
return aliasOf.aliases[firstAlias!] === $0
}
}
/// Calculate the relative name for the given oneof.
public func relativeName(oneof: OneofDescriptor) -> String {
let camelCase = NamingUtils.toUpperCamelCase(oneof.name)
return NamingUtils.sanitize(oneofName: "OneOf_\(camelCase)", forbiddenTypeNames: [self.swiftProtobufModuleName])
}
/// Calculate the full name for the given oneof.
public func fullName(oneof: OneofDescriptor) -> String {
return fullName(message: oneof.containingType) + "." + relativeName(oneof: oneof)
}
/// Calculate the relative name for the given entension.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func relativeName(extensionField field: FieldDescriptor) -> String {
precondition(field.isExtension)
if field.extensionScope != nil {
return NamingUtils.sanitize(messageScopedExtensionName: field.namingBase)
} else {
let swiftPrefix = typePrefix(forFile: field.file)
return swiftPrefix + "Extensions_" + field.namingBase
}
}
/// Calculate the full name for the given extension.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func fullName(extensionField field: FieldDescriptor) -> String {
precondition(field.isExtension)
let relativeName = self.relativeName(extensionField: field)
guard let extensionScope = field.extensionScope else {
return modulePrefix(file: field.file) + relativeName
}
let extensionScopeSwiftFullName = fullName(message: extensionScope)
let relativeNameNoBackticks = NamingUtils.trimBackticks(relativeName)
return extensionScopeSwiftFullName + ".Extensions." + relativeNameNoBackticks
}
public typealias MessageFieldNames = (name: String, prefixed: String, has: String, clear: String)
/// Calculate the names to use for the Swift fields on the message.
///
/// If `prefixed` is not empty, the name prefixed with that will also be included.
///
/// If `includeHasAndClear` is False, the has:, clear: values in the result will
/// be the empty string.
///
/// - Precondition: `field` must be FieldDescriptor that's isn't for an extension.
public func messagePropertyNames(field: FieldDescriptor,
prefixed: String,
includeHasAndClear: Bool) -> MessageFieldNames {
precondition(!field.isExtension)
let lowerName = NamingUtils.toLowerCamelCase(field.namingBase)
let fieldName = NamingUtils.sanitize(fieldName: lowerName)
let prefixedFieldName =
prefixed.isEmpty ? "" : NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName)
if !includeHasAndClear {
return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: "", clear: "")
}
let upperName = NamingUtils.toUpperCamelCase(field.namingBase)
let hasName = NamingUtils.sanitize(fieldName: "has\(upperName)", basedOn: lowerName)
let clearName = NamingUtils.sanitize(fieldName: "clear\(upperName)", basedOn: lowerName)
return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: hasName, clear: clearName)
}
public typealias OneofFieldNames = (name: String, prefixed: String)
/// Calculate the name to use for the Swift field on the message.
public func messagePropertyName(oneof: OneofDescriptor, prefixed: String = "_") -> OneofFieldNames {
let lowerName = NamingUtils.toLowerCamelCase(oneof.name)
let fieldName = NamingUtils.sanitize(fieldName: lowerName)
let prefixedFieldName = NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName)
return OneofFieldNames(name: fieldName, prefixed: prefixedFieldName)
}
public typealias MessageExtensionNames = (value: String, has: String, clear: String)
/// Calculate the names to use for the Swift Extension on the extended
/// message.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func messagePropertyNames(extensionField field: FieldDescriptor) -> MessageExtensionNames {
precondition(field.isExtension)
let fieldBaseName = NamingUtils.toLowerCamelCase(field.namingBase)
let fieldName: String
let hasName: String
let clearName: String
if let extensionScope = field.extensionScope {
let extensionScopeSwiftFullName = fullName(message: extensionScope)
// Don't worry about any sanitize api on these names; since there is a
// Message name on the front, it should never hit a reserved word.
//
// fieldBaseName is the lowerCase name even though we put more on the
// front, this seems to help make the field name stick out a little
// compared to the message name scoping it on the front.
fieldName = NamingUtils.periodsToUnderscores(extensionScopeSwiftFullName + "_" + fieldBaseName)
let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName)
hasName = "has" + fieldNameFirstUp
clearName = "clear" + fieldNameFirstUp
} else {
// If there was no package and no prefix, fieldBaseName could be a reserved
// word, so sanitize. These's also the slim chance the prefix plus the
// extension name resulted in a reserved word, so the sanitize is always
// needed.
let swiftPrefix = typePrefix(forFile: field.file)
fieldName = NamingUtils.sanitize(fieldName: swiftPrefix + fieldBaseName)
if swiftPrefix.isEmpty {
// No prefix, so got back to UpperCamelCasing the extension name, and then
// sanitize it like we did for the lower form.
let upperCleaned = NamingUtils.sanitize(fieldName: NamingUtils.toUpperCamelCase(field.namingBase),
basedOn: fieldBaseName)
hasName = "has" + upperCleaned
clearName = "clear" + upperCleaned
} else {
// Since there was a prefix, just add has/clear and ensure the first letter
// was capitalized.
let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName)
hasName = "has" + fieldNameFirstUp
clearName = "clear" + fieldNameFirstUp
}
}
return MessageExtensionNames(value: fieldName, has: hasName, clear: clearName)
}
/// Calculate the prefix to use for this file, it is derived from the
/// proto package or swift_prefix file option.
public func typePrefix(forFile file: FileDescriptor) -> String {
if let result = filePrefixCache[file.name] {
return result
}
let result = NamingUtils.typePrefix(protoPackage: file.package,
fileOptions: file.fileOptions)
filePrefixCache[file.name] = result
return result
}
/// Internal helper to find the module prefix for a symbol given a file.
func modulePrefix(file: FileDescriptor) -> String {
guard let prefix = mappings.moduleName(forFile: file) else {
return String()
}
if prefix == targetModule {
return String()
}
return "\(prefix)."
}
}
| apache-2.0 | 45c543ecb091ba76e36fb99c4ff00507 | 41.15625 | 121 | 0.695397 | 4.882856 | false | false | false | false |
lockerfish/mini-hacks | ios-share-extension/Playgrounds/REST_GET_channels.playground/Contents.swift | 3 | 947 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
// Let asynchronous code run
XCPSetExecutionShouldContinueIndefinitely()
var url = NSURL(string: "http://localhost:4984/db/_session")!
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
var json: Dictionary<String, AnyObject> = (NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil) as? Dictionary<String, AnyObject>)!
if let userCtx = json["userCtx"] as? Dictionary<String, AnyObject> {
if let channels = userCtx["channels"] as? Dictionary<String, AnyObject> {
var array: [String] = []
for (item, _) in channels {
if item != "!" {
array.append(item)
}
}
}
}
})
task.resume()
| mit | a1b823b461a064d3d7eb7a5701e6660b | 29.548387 | 159 | 0.601901 | 4.597087 | false | false | false | false |
yagiz/Bagel | mac/Bagel/Workers/BagelController/Controllers/BagelProjectController.swift | 1 | 1441 | //
// BagelProjectController.swift
// Bagel
//
// Created by Yagiz Gurgul on 24/09/2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
class BagelProjectController: NSObject {
var projectName: String?
var deviceControllers: [BagelDeviceController] = []
var selectedDeviceController: BagelDeviceController? {
didSet {
NotificationCenter.default.post(name: BagelNotifications.didSelectDevice, object: nil)
}
}
@discardableResult
func addPacket(newPacket: BagelPacket) -> Bool {
for deviceController in self.deviceControllers {
if deviceController.deviceId == newPacket.device?.deviceId {
return deviceController.addPacket(newPacket: newPacket)
}
}
let deviceController = BagelDeviceController()
deviceController.deviceId = newPacket.device?.deviceId
deviceController.deviceName = newPacket.device?.deviceName
deviceController.deviceDescription = newPacket.device?.deviceDescription
deviceController.addPacket(newPacket: newPacket)
self.deviceControllers.append(deviceController)
if self.deviceControllers.count == 1 {
self.selectedDeviceController = self.deviceControllers.first
}
return true
}
}
| apache-2.0 | 974205db2e8fe1b625074471a15e6c21 | 27.8 | 98 | 0.633333 | 5.236364 | false | false | false | false |
yageek/SwiftOAuth1a | Sources/Serializer.swift | 1 | 5858 | //
// OAuth1RequestSerializer.swift
// SwiftOAuth1a
//
// Created by Yannick Heinrich on 17/06/15.
// Copyright (c) 2015 yageek. All rights reserved.
//
import Foundation
import HMAC
import Base32
public class Serializer {
enum SignatureMethod: String {
case HMAC = "HMAC-SHA1"
case RSA = "RSA-SHA1"
}
/// The consumerKey provided by the API
let consumerKey: String
/// The consumerSecrte provided by the API
let consumerSecret: String
/// The accessToken provided by the API
public var accessToken: String?
/// The tokenSecretProvided by the API
public var tokenSecret: String?
let version = "1.0"
let signatureMethod = SignatureMethod.HMAC
public var userAgent = "SwiftOAuth1a"
public var timeout = 10.0
var hmacSignKey: String {
get {
return String(format: "%@&%@", arguments: [self.consumerSecret, self.tokenSecret ?? ""])
}
}
internal func OAuthParameters(nonce: String? = nil, timeStamp: String? = nil) -> [String:String] {
var baseArray: [String:String] = [
"oauth_version" : self.version,
"oauth_nonce" : nonce ?? Serializer.nonce(),
"oauth_signature_method" : self.signatureMethod.rawValue,
"oauth_timestamp" : timeStamp ?? Serializer.timeStamp(),
"oauth_consumer_key" : self.consumerKey
]
if let token = accessToken {
baseArray["oauth_token"] = token
}
return baseArray
}
internal class func nonce() -> String {
return NSUUID().UUIDString
}
internal class func timeStamp() -> String {
var t: time_t = time_t()
time(&t)
mktime(gmtime(&t))
return String(format: "%i", arguments: [Int(t)])
}
/**
Initialize a new OAuth1A Serializer
- parameter consumerKey: The consumer key
- parameter consumerSecret: The consumer secret
- parameter accessToken: The access token if available
- parameter tokenSecret: The token secret if available
- returns: A new OAuth1A serializer
*/
public init(consumerKey key: String, consumerSecret secret: String, accessToken token: String? = nil, tokenSecret: String? = nil) {
self.consumerKey = key
self.consumerSecret = secret
self.accessToken = token
self.tokenSecret = tokenSecret
}
/**
Serailize a request
- parameter method: The HTTP Method
- parameter url: The URL
- parameter parameters: The parameters of the request
- returns: A NSMutableURLRequest instance
*/
public func URLRequest(method: String, url: NSURL, parameters: [String: String]) -> NSMutableURLRequest? {
let oauthParams = self.OAuthParameters()
let params = ParameterList()
params.addParameters(oauthParams)
params.addParameter("oauth_signature", value: self.Signature(method, url: url, requestParams: parameters, oauthParams:oauthParams))
let authorizationHeader = "OAuth " + params.normalizedParameters(",", escapeValues: true)
//Build request
let finalURL: NSURL
let requestParameters = ParameterList()
requestParameters.addParameters(parameters)
if method == "GET" {
let urlString = String(format: "%@?%@", arguments: [url.absoluteString, requestParameters.normalizedParameters()])
finalURL = NSURL(string: urlString)!
} else {
finalURL = url
}
let request = NSMutableURLRequest(URL: finalURL, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: self.timeout)
if method != "GET" {
let query = requestParameters.normalizedParameters("=")
let data = query.dataUsingEncoding(NSUTF8StringEncoding)!
let length = String(data.length)
request.HTTPBody = data
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue(length, forHTTPHeaderField: "Content-Length")
}
request.setValue(self.userAgent, forHTTPHeaderField: "User-Agent")
request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")
request.setValue(authorizationHeader, forHTTPHeaderField: "Authorization")
request.HTTPMethod = method
return request
}
internal func Signature(method: String, url: NSURL, requestParams: [String:String], oauthParams oparams: [String:String]) -> String {
var oauthParams = oparams
if let token = self.accessToken {
oauthParams["oauth_access_token"] = token
}
let baseSignature = Serializer.SignatureBaseString(method, url: url, requestParams: requestParams, oauthParams:oauthParams)
let base = baseSignature.dataUsingEncoding(NSUTF8StringEncoding)!
let secret = self.hmacSignKey.dataUsingEncoding(NSUTF8StringEncoding)!
let hmacRawSignature = HMAC(algorithm: .SHA1, key: secret).update(base).final()
let data = NSData(bytes: hmacRawSignature, length: hmacRawSignature.count)
let oauthSignature = data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return oauthSignature
}
internal class func SignatureBaseString(method: String, url: NSURL, requestParams: [String:String], oauthParams: [String:String]) -> String {
let params = ParameterList()
params.addParameters(requestParams)
params.addParameters(oauthParams)
//Signature
var signature = method
signature += "&"
signature += url.baseStringURI().pcen()
signature += "&"
signature += params.normalizedParameters().pcen()
return signature
}
}
| mit | 66eab8bc18e26a2b4a77233edfe3c295 | 31.910112 | 145 | 0.644418 | 4.801639 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/WalletPayload/Tests/WalletPayloadKitTests/WalletLogicTests.swift | 1 | 12957 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import MetadataKit
@testable import MetadataKitMock
@testable import WalletPayloadDataKit
@testable import WalletPayloadKit
@testable import WalletPayloadKitMock
import Combine
import TestKit
import ToolKit
import XCTest
// swiftlint:disable line_length
class WalletLogicTests: XCTestCase {
private let jsonV4 = Fixtures.loadJSONData(filename: "wallet.v4", in: .module)!
private let jsonV3 = Fixtures.loadJSONData(filename: "wallet.v3", in: .module)!
private var cancellables: Set<AnyCancellable>!
override func setUp() {
super.setUp()
cancellables = []
}
func test_wallet_logic_can_initialize_a_wallet() {
let walletHolder = WalletHolder()
var decoderWalletCalled = false
let decoder: WalletDecoding = { payload, data -> AnyPublisher<Wrapper, WalletError> in
decoderWalletCalled = true
return WalletDecoder().createWallet(from: payload, decryptedData: data)
}
let metadataService = MetadataServiceMock()
let walletSyncMock = WalletSyncMock()
let upgrader = WalletUpgrader(workflows: [])
var checkAndSaveWalletCredentialsCalled = false
let checkAndSaveWalletCredentialsMock: CheckAndSaveWalletCredentials = { _, _, _
-> AnyPublisher<EmptyValue, Never> in
checkAndSaveWalletCredentialsCalled = true
return .just(.noValue)
}
let walletLogic = WalletLogic(
holder: walletHolder,
decoder: decoder,
upgrader: upgrader,
metadata: metadataService,
walletSync: walletSyncMock,
notificationCenter: .default,
logger: NoopNativeWalletLogging(),
payloadHealthChecker: { .just($0) },
checkAndSaveWalletCredentials: checkAndSaveWalletCredentialsMock
)
let walletPayload = WalletPayload(
guid: "guid",
authType: 0,
language: "en",
shouldSyncPubKeys: false,
time: Date(),
payloadChecksum: "",
payload: WalletPayloadWrapper(pbkdf2IterationCount: 5000, version: 4, payload: "") // we don't use this
)
metadataService.initializeValue = .just(MetadataState.mock)
let expectation = expectation(description: "wallet-fetching-expectation")
walletLogic.initialize(with: "password", payload: walletPayload, decryptedWallet: jsonV4)
.sink { _ in
//
} receiveValue: { _ in
XCTAssertTrue(decoderWalletCalled)
XCTAssertTrue(checkAndSaveWalletCredentialsCalled)
expectation.fulfill()
}
.store(in: &cancellables)
wait(for: [expectation], timeout: 10)
XCTAssertTrue(walletHolder.walletState.value!.isInitialised)
}
func test_wallet_that_requires_upgrades_is_upgraded_and_synced() {
let walletHolder = WalletHolder()
var decoderWalletCalled = false
let decoder: WalletDecoding = { payload, data -> AnyPublisher<Wrapper, WalletError> in
decoderWalletCalled = true
return WalletDecoder().createWallet(from: payload, decryptedData: data)
}
let metadataService = MetadataServiceMock()
let walletSyncMock = WalletSyncMock()
let upgraderSpy = WalletUpgraderSpy(
realUpgrader: WalletUpgrader(
workflows: [Version4Workflow(logger: NoopNativeWalletLogging())]
)
)
let walletLogic = WalletLogic(
holder: walletHolder,
decoder: decoder,
upgrader: upgraderSpy,
metadata: metadataService,
walletSync: walletSyncMock,
notificationCenter: .default,
logger: NoopNativeWalletLogging(),
payloadHealthChecker: { .just($0) },
checkAndSaveWalletCredentials: { _, _, _ in .just(.noValue) }
)
let walletPayload = WalletPayload(
guid: "guid",
authType: 0,
language: "en",
shouldSyncPubKeys: false,
time: Date(),
payloadChecksum: "",
payload: WalletPayloadWrapper(pbkdf2IterationCount: 5000, version: 3, payload: "") // we don't use this
)
metadataService.initializeValue = .just(MetadataState.mock)
walletSyncMock.syncResult = .success(.noValue)
let expectation = expectation(description: "wallet-fetching-expectation")
walletLogic.initialize(with: "password", payload: walletPayload, decryptedWallet: jsonV3)
.sink(
receiveCompletion: { completion in
guard case .failure = completion else {
return
}
XCTFail("should provide correct value")
},
receiveValue: { walletState in
XCTAssertTrue(decoderWalletCalled)
// Upgrade should be called
XCTAssertTrue(upgraderSpy.upgradedNeededCalled)
XCTAssertTrue(upgraderSpy.performUpgradeCalled)
// Sync should be called
XCTAssertTrue(walletSyncMock.syncCalled)
XCTAssertTrue(walletState.isInitialised)
expectation.fulfill()
}
)
.store(in: &cancellables)
wait(for: [expectation], timeout: 10)
XCTAssertTrue(walletHolder.walletState.value!.isInitialised)
}
func test_wallet_that_requires_upgrades_is_upgraded_but_fails_on_sync_failure() {
let walletHolder = WalletHolder()
var decoderWalletCalled = false
let decoder: WalletDecoding = { payload, data -> AnyPublisher<Wrapper, WalletError> in
decoderWalletCalled = true
return WalletDecoder().createWallet(from: payload, decryptedData: data)
}
let metadataService = MetadataServiceMock()
let walletSyncMock = WalletSyncMock()
let upgraderSpy = WalletUpgraderSpy(
realUpgrader: WalletUpgrader(
workflows: [Version4Workflow(logger: NoopNativeWalletLogging())]
)
)
let walletLogic = WalletLogic(
holder: walletHolder,
decoder: decoder,
upgrader: upgraderSpy,
metadata: metadataService,
walletSync: walletSyncMock,
notificationCenter: .default,
logger: NoopNativeWalletLogging(),
payloadHealthChecker: { .just($0) },
checkAndSaveWalletCredentials: { _, _, _ in .just(.noValue) }
)
let walletPayload = WalletPayload(
guid: "guid",
authType: 0,
language: "en",
shouldSyncPubKeys: false,
time: Date(),
payloadChecksum: "",
payload: WalletPayloadWrapper(pbkdf2IterationCount: 5000, version: 3, payload: "") // we don't use this
)
metadataService.initializeValue = .just(MetadataState.mock)
walletSyncMock.syncResult = .failure(.unknown)
let expectation = expectation(description: "wallet-fetching-expectation")
walletLogic.initialize(with: "password", payload: walletPayload, decryptedWallet: jsonV3)
.sink(
receiveCompletion: { completion in
guard case .failure = completion else {
return
}
XCTAssertTrue(decoderWalletCalled)
// Upgrade should be called
XCTAssertTrue(upgraderSpy.upgradedNeededCalled)
XCTAssertTrue(upgraderSpy.performUpgradeCalled)
// Sync should be called
XCTAssertTrue(walletSyncMock.syncCalled)
// we shouldn't have a wallet state
XCTAssertNil(walletHolder.provideWalletState())
expectation.fulfill()
},
receiveValue: { _ in
XCTFail("should fail because on syncResult")
}
)
.store(in: &cancellables)
wait(for: [expectation], timeout: 10)
}
func test_metadata_input_is_valid() {
let entropyHex = "00000000000000000000000000000011"
let hdWallet = HDWallet(
seedHex: entropyHex,
passphrase: "",
mnemonicVerified: false,
defaultAccountIndex: 0,
accounts: []
)
let wallet = NativeWallet(
guid: "802e3bb0-5a4b-4068-bc64-cebb6c3a1917",
sharedKey: "c5ba92ae-80c8-480b-9347-fc2de641bf68",
doubleEncrypted: false,
doublePasswordHash: nil,
metadataHDNode: nil,
options: .default,
hdWallets: [hdWallet],
addresses: [],
txNotes: nil,
addressBook: nil
)
let masterNode = getMasterNode(from: wallet).success!
let expectedMasterKey = MasterKey.from(masterNode: masterNode).success!
provideMetadataInput(
password: "password",
wallet: wallet
)
.sink { input in
XCTAssertEqual(
input.credentials,
Credentials(guid: wallet.guid, sharedKey: wallet.sharedKey, password: "password")
)
XCTAssertEqual(
input.masterKey,
expectedMasterKey
)
}
.store(in: &cancellables)
}
func test_integration_generate_nodes_for_new_account() {
let expectedRootAddress = "1Bz8SGpLXrMf12q6atKFoSrkuwCCevvabL"
var fetchCalled = false
let fetchMock: FetchMetadataEntry = { address in
XCTAssertEqual(address, expectedRootAddress)
fetchCalled = true
return .just(
MetadataPayload(
version: 1,
payload: "",
signature: "",
prevMagicHash: nil,
typeId: -1,
createdAt: 0,
updatedAt: 0,
address: address
)
)
}
var putCalled = false
let putMock: PutMetadataEntry = { address, _ in
putCalled = true
XCTAssertEqual(address, expectedRootAddress)
return .just(())
}
let entropyHex = "00000000000000000000000000000000"
let hdWallet = HDWallet(
seedHex: entropyHex,
passphrase: "",
mnemonicVerified: false,
defaultAccountIndex: 0,
accounts: []
)
let wallet = NativeWallet(
guid: "802e3bb0-5a4b-4068-bc64-cebb6c3a1917",
sharedKey: "c5ba92ae-80c8-480b-9347-fc2de641bf68",
doubleEncrypted: false,
doublePasswordHash: nil,
metadataHDNode: nil,
options: .default,
hdWallets: [hdWallet],
addresses: [],
txNotes: nil,
addressBook: nil
)
let generateNodes = provideGenerateNodes(
fetch: fetchMock,
put: putMock
)
provideMetadataInput(
password: "Misura12!",
wallet: wallet
)
.eraseError()
.flatMap { input -> AnyPublisher<(MetadataState, MetadataInput), Error> in
deriveSecondPasswordNode(credentials: input.credentials)
.publisher
.eraseError()
.eraseToAnyPublisher()
.flatMap { secondPasswordNode -> AnyPublisher<MetadataState, Error> in
generateNodes(input.masterKey, secondPasswordNode)
.eraseError()
.eraseToAnyPublisher()
}
.map { ($0, input) }
.eraseToAnyPublisher()
}
.sink { state, input in
// This is the BIP32 Root Key for the given entropy
XCTAssertTrue(fetchCalled)
XCTAssertTrue(putCalled)
XCTAssertEqual(
input.masterKey.privateKey.xpriv,
"xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu"
)
// This should be the root PrivateKey for metadata derivation
// m/{purpose}' where {purpose} is defined in `MetadataDerivation` on `MetadataKit`
XCTAssertEqual(
state.metadataNodes.metadataNode.xpriv,
"xprv9ukW2UsuzBb5WY6LimMwFSSaTNBQAZVhsdeWNshKUH1FXxoiAVE9HHKbk5Ppu8C3Ns8eDT8mF5xhjmBrYLF6NHgguXTrxXTXe66FeYPKBCy"
)
}
.store(in: &cancellables)
}
}
| lgpl-3.0 | f183e7cad18893157318b6a0dd9222ce | 34.49589 | 129 | 0.576027 | 4.863363 | false | false | false | false |
ashfurrow/eidolon | Kiosk/Admin/AuctionWebViewController.swift | 2 | 837 | import UIKit
class AuctionWebViewController: WebViewController {
override func viewDidLoad() {
super.viewDidLoad()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let exitImage = UIImage(named: "toolbar_close")
let backwardBarItem = UIBarButtonItem(image: exitImage, style: .plain, target: self, action: #selector(exit));
let allItems = self.toolbarItems! + [flexibleSpace, backwardBarItem]
toolbarItems = allItems
}
@objc func exit() {
let passwordVC = PasswordAlertViewController.alertView { [weak self] in
_ = self?.navigationController?.popViewController(animated: true)
return
}
self.present(passwordVC, animated: true) {}
}
}
| mit | 84cf0036d76ca0ecee50d4fa37282a67 | 35.391304 | 127 | 0.665472 | 5.166667 | false | false | false | false |
ppoh71/motoRoutes | motoRoutes/showRouteController.swift | 1 | 33452 | //
// showRouteController.swift
// motoRoutes
//
// Created by Peter Pohlmann on 01.02.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import UIKit
import CoreLocation
import Foundation
import RealmSwift
import Mapbox
import Crashlytics
import pop
//import SwiftKeychainWrapper
class showRouteController: UIViewController {
//MARK: Outles
//Outlets
@IBOutlet weak var cancelButton:UIButton!
@IBOutlet weak var flyButton:UIButton!
//@IBOutlet var SpeedLabel:UILabel!
@IBOutlet weak var DistanceLabel:UILabel!
@IBOutlet weak var TimeLabel:UILabel!
@IBOutlet weak var AltitudeLabel:UILabel!
@IBOutlet weak var followCameraButton: UIButton!
@IBOutlet weak var googleImage: UIImageView!
@IBOutlet weak var routeSlider:RouteSlider!{
didSet{
routeSlider.setLabel("0.000", timeText: "00:00")
}
}
@IBOutlet weak var routeImageView:UIImageView!
@IBOutlet weak var mapViewShow: MGLMapView!
@IBOutlet weak var debugLabel: UILabel!
@IBOutlet weak var optionsButton: UIButton!
//MARK: Vars
//add gesture
var toggleImageViewGesture = UISwipeGestureRecognizer()
// Get the default Realm
let realm = try! Realm()
// realm object list
var motoRoute: Route!
let _RouteMaster = RouteMaster()
var RouteList = [LocationMaster]()
// var markersSet = [MarkerAnnotation]()
//media stuff
var markerImageName:String = ""
//slider route value
var sliderRouteValue = 0
var sliceStart = 0
var sliceAmount = 1
var key = 0
var count:Int = 0
var countGoogle:Int = 0
var timer = Timer()
var timeIntervalMarker = 0.01
var performanceTime:Double = 0
var tmpRoutePos = 0
var followCamera = false
//Debug Label
var debugTimer = Timer()
var debugSeconds = 0
//init custom speedometer
var speedoMeter = Speedometer()
let speedoWidth:Int = 6
var cameraCustomSlider = CameraSliderCustom()
let frameSizeCameraSlider = 40 //extra space for slidethumb image
//make screenshot
var funcType = FuncTypes.Default
var msgOverlay: MsgOverlay!
var countReuse = 0
//Custom Views
var routeInfos: RouteInfos!
// var chartSpeed: MotoChart!
// var chartAlt: MotoChart!
//Display Vars
var screenSize: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
var screenWidth: CGFloat = 0.0
var screenHeight: CGFloat = 0.0
//MARK: viewDidLoad, didAppear
override func viewDidLoad() {
super.viewDidLoad()
//let x = CFAbsoluteTimeGetCurrent()
//Set screensize
screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
// MODEL: set max on route slider
routeSlider.maximumValue = Float(motoRoute!.locationsList.count-1)
//MODEL: covert Realm LocationList to Location Master Object
_RouteMaster.associateRoute(motoRoute!)
RouteList = _RouteMaster._RouteList
//center mapview to route coords
mapViewShow.zoomLevel = 9
mapViewShow.camera.heading = globalHeading.gHeading
mapViewShow.setCenter(CLLocationCoordinate2D(latitude: RouteList[0].latitude, longitude: RouteList[0].longitude), animated: false)
// Toggle Camera recognizer
toggleImageViewGesture.direction = .right
toggleImageViewGesture.addTarget(self, action: #selector(showRouteController.togglePhotoView))
routeImageView.addGestureRecognizer(toggleImageViewGesture)
routeImageView.isUserInteractionEnabled = true
//slider drag end of route slider
routeSlider.addTarget(self, action: #selector(showRouteController.touchUpRouteSlide), for: UIControlEvents.touchUpInside)
routeSlider.addTarget(self, action: #selector(showRouteController.touchUpRouteSlide), for: UIControlEvents.touchUpOutside)
routeSlider.addTarget(self, action: #selector(showRouteController.touchDowntRouteSlide), for: UIControlEvents.touchDown)
//init RouteInfos
routeInfos = Bundle.main.loadNibNamed("RouteInfos", owner: self, options: nil)?[0] as? RouteInfos
routeInfos.setInfos(_RouteMaster)
AnimationEngine.hideViewBottomLeft(routeInfos) //move view to bottom ad off screen to the left for now
self.view.addSubview(routeInfos)
//init Charts
/*
chartSpeed = Bundle.main.loadNibNamed("MotoChart", owner: self, options: nil)?[0] as? MotoChart
chartSpeed.setupChart(_RouteMaster, type: "")
AnimationEngine.hideViewBottomLeft(chartSpeed) //move view to bottom ad off screen to the left for now
self.view.addSubview(chartSpeed)
//init Charts Alt
chartAlt = Bundle.main.loadNibNamed("MotoChart", owner: self, options: nil)?[0] as? MotoChart
chartAlt.setupChart(_RouteMaster, type: "alt")
AnimationEngine.hideViewBottomLeft(chartAlt) //move view to bottom ad off screen to the left for now
self.view.addSubview(chartAlt)
*/
cameraCustomSlider.addTarget(self, action: #selector(showRouteController.cameraSliderValueChanged), for: .valueChanged)
setupCustomUI()
hideAllBottomController()
//showRouteInfos()
}
override func viewDidAppear(_ animated: Bool) {
//write to firebase test
//if let keychain = KeychainWrapper.defaultKeychainWrapper().stringForKey(KEY_UID){
// FirebaseData.dataService.addRouteToFIR(_RouteMaster, keychain: keychain)
// print("MR: try to add to firebase")
//} else{
// print("MR: not logged in")
//}
//Listen from FlyoverRoutes if Markers are set
NotificationCenter.default.addObserver(self, selector: #selector(showRouteController.switchFromFly2PrintMarker), name: NSNotification.Name(rawValue: markerNotSetNotificationKey), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showRouteController.saveLocationString), name: NSNotification.Name(rawValue: getLocationSetNotificationKey), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showRouteController.keyFromChart), name: NSNotification.Name(rawValue: chartSetNotificationKey), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showRouteController._GoogleImage), name: NSNotification.Name(rawValue: googleGetImagesNotificationKey), object: nil)
//get locationString if emtpy and set start/end marker
checkLocationStartEnd(motoRoute!)
//print the route in 1 color
MapUtils.printRouteOneColor(RouteList, mapView: mapViewShow)
//printCricleRoute()
//define camera and set it to startpoint
let camera = MapUtils.cameraDestination(RouteList[0].latitude, longitude:RouteList[0].longitude, fromDistance:globalCamDistance.gCamDistance, pitch: globalCamPitch.gCamPitch, heading: RouteList[0].course + globalHeading.gHeading)
mapViewShow.setCamera(camera, withDuration: globalCamDuration.gCamDuration, animationTimingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear))
}
func _GoogleImage(_ notification: Notification){
if let notifyObj = notification.object as? [UIImage] {
for image in notifyObj{
print("back from google \(image)")
displayGoogleImage(image)
}
}
}
func getGoogleImageCache(_ id: String, key: Int){
let imageFile = Utils.getDocumentsDirectory().appendingPathComponent("/\(id)/\(key).jpeg")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: imageFile) {
print("GOOGLE IMAGE AVAILABLE )")
let image = ImageUtils.loadImageFromPath(imageFile as NSString)
displayGoogleImage(image!)
} else {
print("LOAD IMAGE FROm GOOGLE")
GoogleData.dataService.getGoogleImages(self._RouteMaster._RouteList[key].latitude, longitude: self._RouteMaster._RouteList[key].longitude, heading: self._RouteMaster._RouteList[key].course, id: id, key: key )
}
}
func displayGoogleImage(_ image: UIImage){
googleImage.image = image
}
//
// view will disappear, stop everythink
//
override func viewWillDisappear(_ animated:Bool) {
stopAll()
NotificationCenter.default.removeObserver(self)
super.viewWillDisappear(animated)
}
//int and setup custom controlls
func setupCustomUI(){
//init Speedometer
let speedoHeight = screenHeight/2
speedoMeter.frame = CGRect(x: (Int(screenWidth) - speedoWidth), y: 0, width: speedoWidth, height: Int(speedoHeight))
speedoMeter.setup(speedoWidth, height: Int(speedoHeight))
//init and setup custom camera slider
let cameraCustomHeightMinus = CGFloat(60)
cameraCustomSlider.frame = CGRect(x: (Int(screenWidth) - frameSizeCameraSlider), y: Int(screenHeight/2), width: frameSizeCameraSlider, height: Int(speedoHeight - cameraCustomHeightMinus))
cameraCustomSlider.setup(speedoWidth, height: Int(speedoHeight - cameraCustomHeightMinus), frameWidth: frameSizeCameraSlider)
//add Subviews
view.addSubview(speedoMeter)
view.addSubview(cameraCustomSlider)
hidePlaybackViews() // hide after setup
}
//MARK: Show/Hide Bottom Controls
//
// Hide Playback Buttons & Slider
//
func hidePlaybackViews(){
followCameraButton.isHidden = true
flyButton.isHidden = true
routeSlider.isHidden = true
speedoMeter.isHidden = true
cameraCustomSlider.isHidden = true
}
func showPlaybackViews(){
followCameraButton.isHidden = false
flyButton.isHidden = false
routeSlider.isHidden = false
speedoMeter.isHidden = false
cameraCustomSlider.isHidden = false
}
func showRouteInfos(){
AnimationEngine.showViewAnimCenterBottomPosition(routeInfos)
}
func hideRouteInfos(){
AnimationEngine.hideViewBottomLeft(routeInfos)
}
func hideChartSpeed(){
// AnimationEngine.hideViewBottomLeft(chartSpeed)
}
func showChartSpeed(){
// AnimationEngine.showViewAnimCenterBottomPosition(chartSpeed)
}
func hideChartAlt(){
// AnimationEngine.hideViewBottomLeft(chartAlt)
}
func showChartAlt(){
// AnimationEngine.showViewAnimCenterBottomPosition(chartAlt)
}
func hideAllBottomController(){
hideChartSpeed()
hideRouteInfos()
hidePlaybackViews()
hideChartAlt()
}
//MARK: Stuff
// check if we have the locationStrings already
func checkLocationStartEnd(_ route:Route){
if(route.locationStart.isEmpty || route.locationEnd.isEmpty || route.locationStart == "Start Location" ) {
// let fromLocation = CLLocationCoordinate2D(latitude: route.locationsList[0].latitude, longitude:route.locationsList[0].longitude)
// let toLocation = CLLocationCoordinate2D(latitude: route.locationsList[route.locationsList.count-1].latitude, longitude: route.locationsList[route.locationsList.count-1].longitude)
//assign async text to label
// GeocodeUtils.getAdressFromCoord(fromLocation, field: "to")
// GeocodeUtils.getAdressFromCoord(toLocation, field: "from")
GoogleData.dataService.getGoogleGeoCode(route.locationsList[0].latitude, longitude: route.locationsList[0].longitude, field: "from")
//GoogleData.dataService.getGoogleGeoCode(route.locationsList[route.locationsList.count-1].latitude, longitude: route.locationsList[route.locationsList.count-1].longitude, field: "to")
print("location is empty")
} else{
print("location not empty \(route.locationStart)")
// setStartEndMarker()
GoogleData.dataService.getGoogleGeoCode(route.locationsList[0].latitude, longitude: route.locationsList[0].longitude, field: "from")
// GoogleData.dataService.getGoogleGeoCode(route.locationsList[route.locationsList.count-1].latitude, longitude: route.locationsList[route.locationsList.count-1].longitude, field: "to")
}
}
// add start/end markers with locationString text
func setStartEndMarker(){
print("Add Start/End Marker")
funcType = .PrintStartEnd
let startMarker = MGLPointAnnotation()
startMarker.coordinate = CLLocationCoordinate2DMake(self.RouteList[0].latitude, self.RouteList[0].longitude)
startMarker.title = "motoRoute!.locationStart"
startMarker.subtitle = motoRoute!.locationStart
self.mapViewShow.addAnnotation(startMarker)
let endMarker = MGLPointAnnotation()
endMarker.coordinate = CLLocationCoordinate2DMake(self.RouteList[RouteList.count-1].latitude, self.RouteList[RouteList.count-1].longitude)
endMarker.title = " motoRoute!.locationEnd"
endMarker.subtitle = motoRoute!.locationEnd
self.mapViewShow.addAnnotation(endMarker)
}
//MARK: Notification observer functions
//save location string from geolocation(notification center to realm
func saveLocationString(_ notification: Notification){
print("from notifycation location\(notification.object)")
let arrayObject = notification.object as! [AnyObject]
if let address = arrayObject[0] as? String {
if let field = arrayObject[1] as? String {
RealmUtils.updateLocation2Realm(motoRoute!, location: address, field: field)
}
setStartEndMarker()
}
}
//notifycenter func: get key from swipe on chart
func keyFromChart(_ notification: Notification){
print("Key from chart")
let arrayObject = notification.object as! [AnyObject]
if let receivedKey = arrayObject[0] as? Int {
flyToRouteKey(receivedKey)
}
}
//notifycenter func: when no marker while flying over routesm switch to stop all and start marker printing
func switchFromFly2PrintMarker(_ notification: Notification){
//get object from notification
let arrayObject = notification.object as! [AnyObject]
if let receivedKey = arrayObject[0] as? Int {
//set new sliceStartKey
sliceStart = receivedKey
stopAll()
StartStop(true)
}
}
//MARK: Slider Stuff
//custom camera value changed
func cameraSliderValueChanged(){
//print("current value target print")
//print(cameraCustomSlider.currentValue)
let currentValue = cameraCustomSlider.currentValue
globalCamDistance.gCamDistance = Double(200*currentValue)
//print( globalCamDistance.gCamDistance)
globalCamDuration.gCamDuration = Double(currentValue/1000) + 0.2
//globalArrayStep.gArrayStep = currentValue/10 > 1 ? currentValue/10 : 1
globalCamPitch.gCamPitch = currentValue*2 < 80 ? CGFloat(60 ) : 60.0
//zoom camera also when not flying,
if( globalAutoplay.gAutoplay==false && flyButton.isSelected==false ) {
//get current center coords
let centerCoords = mapViewShow.centerCoordinate
//define camera and flyTo with zoom level
let camera = MapUtils.cameraDestination(centerCoords.latitude, longitude:centerCoords.longitude, fromDistance:globalCamDistance.gCamDistance, pitch: globalCamPitch.gCamPitch, heading: globalHeading.gHeading)
mapViewShow.setCamera(camera, withDuration: globalCamDuration.gCamDuration, animationTimingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear))
// print("\(mapViewShow.centerCoordinate)")
}
}
func flyToRouteKey(_ key: Int){
//googel Test
globalRoutePos.gRoutePos = key
getGoogleImageCache(_RouteMaster._MotoRoute.id, key: key)
//routeSlider.setValues()
//stop camera flightm when selecting new route point
globalAutoplay.gAutoplay = false
//fly to route to destination
MapUtils.flyOverRoutes(RouteList, mapView: mapViewShow, n: globalRoutePos.gRoutePos, routeSlider: routeSlider, initInstance: Utils.getUniqueUUID(), identifier: "i1", speedoMeter: speedoMeter)
}
//touch event for rourte slider
func touchDowntRouteSlide(){
stopAll()
}
//touch event for rourte slider
func touchUpRouteSlide(){
}
//MARK: Start/Stop Print Marker & Timer
//start marker timer
func startMarkerTimer(){
timer = Timer.scheduledTimer(timeInterval: timeIntervalMarker, target: self, selector: #selector(showRouteController.printMarker), userInfo: nil, repeats: true)
}
//start debug timer
func startDebugTimer(){
debugTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(showRouteController.updateDebugLabel), userInfo: nil, repeats: true)
}
//stop all running Timer flying cameras
func stopAll(){
timer.invalidate()
debugTimer.invalidate()
globalAutoplay.gAutoplay = false
flyButton.isSelected = false
}
//start auto fly over routes when marker are set
func startFlytoAuto(){
flyButton.isSelected = true
globalAutoplay.gAutoplay = true
//make route fly
MapUtils.flyOverRoutes(RouteList, mapView: mapViewShow, n: sliceStart, routeSlider: routeSlider, initInstance: Utils.getUniqueUUID(), identifier: "i3", speedoMeter: speedoMeter)
}
//start/stop button function
func StartStop(_ active: Bool){
if (active){
startMarkerTimer()
startDebugTimer()
flyButton.isSelected = true
} else{
stopAll()
}
}
//update debug label
func updateDebugLabel(){
debugSeconds += 1
debugLabel.text = "\(debugSeconds) / \(sliceStart) "
}
//MARK: Print Marker, Print All, Delete Marker
//
// printing speedmarker on the map
//
func printMarker(){
//if not at end of array
if( self.RouteList.count > globalRoutePos.gRoutePos+self.sliceAmount){
//Print Marker if not already set
if(self.RouteList[globalRoutePos.gRoutePos].marker==false){
DispatchQueue.global(qos: .userInteractive).async {
self.funcType = .PrintMarker
let newMarker = MGLPointAnnotation()
newMarker.coordinate = CLLocationCoordinate2DMake(self.RouteList[globalRoutePos.gRoutePos].latitude, self.RouteList[globalRoutePos.gRoutePos].longitude)
newMarker.title = "SpeedAltMarker"
/* set globals */
globalSpeed.gSpeed = self.RouteList[globalRoutePos.gRoutePos].speed
globalAltitude.gAltitude = self.RouteList[globalRoutePos.gRoutePos].altitude
self.mapViewShow.addAnnotation(newMarker)
self.RouteList[globalRoutePos.gRoutePos].annotation = newMarker
self.RouteList[globalRoutePos.gRoutePos].marker = true
// self.unsetMarker(&self.markersSet)
globalRoutePos.gRoutePos = globalRoutePos.gRoutePos + self.sliceAmount //move array to next route
self.tmpRoutePos = globalRoutePos.gRoutePos
self.count+=1 //counter to center map, fly camer to marker
self.countGoogle+=1
//print("a: \(globalRoutePos.gRoutePos) - \(self.RouteList[globalRoutePos.gRoutePos].marker)")
//delete marker trail
let delPos = 120
if((self.tmpRoutePos - delPos) > 0 && self.RouteList[self.tmpRoutePos-delPos].marker==true){
self.mapViewShow.removeAnnotation(self.RouteList[self.tmpRoutePos-delPos].annotation)
}
DispatchQueue.main.async {
// print("b: \(self.tmpRoutePos) - \(self.RouteList[globalRoutePos.gRoutePos].marker)")
self.speedoMeter.moveSpeedo(Double(Utils.getSpeed(self.RouteList[self.tmpRoutePos].speed)))
self.routeSlider.setValue(Float(self.tmpRoutePos), animated: true)
//print("Slider Move \(n)")
self.routeSlider.setLabel((Utils.distanceFormat(0)), timeText: "wtf")
if(self.countGoogle > 20){
self.getGoogleImageCache(self._RouteMaster._MotoRoute.id, key: globalRoutePos.gRoutePos)
self.countGoogle = 0
}
if(self.count > 0 && self.followCamera == true){
MapUtils.flyOverRoutes(self.RouteList, mapView: self.mapViewShow, n: self.tmpRoutePos, routeSlider: nil, initInstance: Utils.getUniqueUUID(), identifier: "i2", speedoMeter: nil)
self.count=0
//self.startMarkerTimer()
}
}
}
}
} else{ // end of array
print("All Marker took: ")
self.stopAll()
//print(RouteList[0].marker)
}
}
func printAllMarker(_ funcSwitch: FuncTypes){
self.funcType = funcSwitch
self.deleteAllMarker()
DispatchQueue.global(qos: .background).async {
let tmpGap = 5
print("image reuse size \(self.RouteList.count / tmpGap)")
DispatchQueue.main.async {
MapUtils.printMarker(self.RouteList, mapView: self.mapViewShow, key: 0, amount: self.RouteList.count-1 , gap: tmpGap, funcType: self.funcType )
self.setStartEndMarker()
}
}
}
func deleteAllMarker(){
guard (mapViewShow.annotations != nil ) else{
print("guard")
return
}
self.mapViewShow.removeAnnotations(self.mapViewShow.annotations!)
//Set marker bool to false, to print new marker
for marker in RouteList{
marker.marker = false
}
}
//MARK: IB Actions Buttons
// new screenshot
@IBAction func flyRoute(_ sender: UIButton) {
sender.isSelected = !sender.isSelected;
sender.isHighlighted = !sender.isHighlighted
StartStop(sender.isSelected )
}
//Route Slider value changed
@IBAction func sliderRouteChanged(_ sender: UISlider) {
//get slider value as int
let key = Int(sender.value)
flyToRouteKey(key)
}
@IBAction func printAltitude(_ sender: AnyObject) {
deleteAllMarker()
printAllMarker(FuncTypes.PrintAltitude)
self.centerMap(52, duration: 1)
hideAllBottomController()
showChartAlt()
}
@IBAction func printCircleMarker(_ sender: AnyObject) {
deleteAllMarker()
printAllMarker(FuncTypes.PrintCircles)
self.centerMap(50, duration: 3)
hidePlaybackViews()
hideAllBottomController()
showChartSpeed()
}
@IBAction func printSpeedMarker(_ sender: AnyObject) {
deleteAllMarker()
printAllMarker(FuncTypes.PrintMarker)
self.centerMap(54, duration: 3)
hideAllBottomController()
showRouteInfos()
}
@IBAction func resetMarker(_ sender: AnyObject) {
deleteAllMarker()
MapUtils.printRouteOneColor(RouteList, mapView: mapViewShow)
self.centerMap(50, duration: 3)
hideAllBottomController()
showPlaybackViews()
print("playback show/hide")
}
@IBAction func printRoute(_ sender: AnyObject) {
deleteAllMarker()
MapUtils.printRoute(RouteList, mapView: mapViewShow)
self.centerMap(53, duration: 3)
}
@IBAction func switchCameraFollow(_ sender: AnyObject) {
if followCamera==false{
followCamera=true
followCameraButton.tintColor = UIColor.lightGray
} else{
followCamera=false
followCameraButton.tintColor = UIColor.white
}
}
// new screenshot
@IBAction func newScreenshot(_ sender: UIButton) {
let screenshotFilename = ImageUtils.screenshotMap(self.mapViewShow, id: motoRoute.id)
//save new screenshot to realm
//print(motoRoute)
try! self.realm.write {
self.realm.create(Route.self, value: ["id": self.motoRoute!.id, "image": screenshotFilename], update: true)
}
}
//MARK: Center Map
func centerMap(_ pitch: CGFloat, duration: Double){
//get bounds, centerpoints, of the whole Route
let Bounds = MapUtils.getBoundCoords(RouteList)
let coordArray = Bounds.coordboundArray
//let coordBounds = Bounds.coordbound
let distanceDiagonal = Bounds.distance
let distanceFactor = Bounds.distanceFactor
//get centerpoint
let centerPoint = MapUtils.getCenterFromBoundig(coordArray)
//define camera and set it to startpoint
let camera = MapUtils.cameraDestination(centerPoint.latitude, longitude:centerPoint.longitude, fromDistance: distanceDiagonal*distanceFactor, pitch: pitch, heading: 0)
//animate camera to center point, launch save overlay
mapViewShow.setCamera(camera, withDuration: duration, animationTimingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) {
}
}
func togglePhotoView(){
let animateX:CGFloat = self.routeImageView.frame.origin.x<100 ? 320 : -320; //animnate x var
//print("x: \(self.routeImageView.frame.origin.x)")
//aimate view
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: {
self.routeImageView.transform = CGAffineTransform(translationX: animateX, y: 0)
}, completion: nil)
}
//MARK: SEGUE Stuff
//
// Prepare Segue / camera stuff
//
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
//prepare for camera/photo store to MediaObhect
if segue.identifier == "showRouteOptions" {
// let destinationController = segue.destinationViewController as! motoRouteOptions
}
//unwind
if segue.identifier == "unwindExitShowRoute" {
//print("unwinding")
}
}
@IBAction func unwindTo(_ unwindSegue: UIStoryboardSegue) {
//print("unwind segue \(unwindSegue)")
}
@IBAction func close(_ segue:UIStoryboardSegue) {
if let optionController = segue.source as? motoRouteOptions {
sliceAmount = optionController.sliceAmount
timeIntervalMarker = optionController.timeIntervalMarker
}
}
}
// MARK: - MKMapViewDelegate
extension showRouteController: MGLMapViewDelegate {
func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
//Try to reuse the existing ‘pisa’ annotation image, if it exists
//var annotationImage = mapView.dequeueReusableAnnotationImageWithIdentifier("routeline\(utils.getSpeed(globalSpeed.gSpeed))")
var image: UIImage
var reuseIdentifier = ""
//reuse identifier
switch(self.funcType) {
case .PrintMarker:
reuseIdentifier = "MarkerSpeed\(Utils.getSpeed(globalSpeed.gSpeed))-1"
case .PrintBaseHeight:
reuseIdentifier = "MarkerSpeedBase\(Utils.getSpeed(globalSpeed.gSpeed))-2"
case .PrintAltitude:
reuseIdentifier = "MarkerAlt\(Int(round(globalAltitude.gAltitude / 10 )))-3"
case .Recording:
reuseIdentifier = "MarkerCircleSpeed\(Utils.getSpeed(globalSpeed.gSpeed))-4"
case .PrintCircles:
reuseIdentifier = "MarkerCircle\(Utils.getSpeed(globalSpeed.gSpeed))-5"
case .PrintStartEnd:
reuseIdentifier = "StartEndMarker"
default:
print("marker image default break")
break
}
var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier)
if annotationImage == nil {
countReuse+=1
print("reuse count \(countReuse)")
if(annotation.title! == "SpeedAltMarker"){
image = ImageUtils.drawLineOnImage(self.funcType)
} else{
image = ImageUtils.drawLineOnImage(self.funcType)
}
annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
//print("iamge is nil \(reuseIdentifier) \(globalSpeed.gSpeed) \(annotation.title!) \(self.funcType) \(image)")
}
return annotationImage
}
func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
// print("regionDidChangeAnimated")
}
func mapViewRegionIsChanging(_ mapView: MGLMapView) {
//print("region is chanhing")
}
func mapView(_ mapView: MGLMapView, regionWillChangeAnimated animated: Bool) {
//print("region will change")
}
func mapViewWillStartLoadingMap(_ mapView: MGLMapView) {
//print("mapViewWillStartLoadingMap")
}
func mapViewDidFinishRenderingMap(_ mapView: MGLMapView, fullyRendered: Bool) {
//print("mapViewDidFinishRenderingMap")
}
func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
//print("annotation")
// print(" a \(annotation.subtitle!!)")
/*
if let imgNameAnnotation:String = annotation.subtitle!! {
let imgPath = utils.getDocumentsDirectory().stringByAppendingPathComponent(imgNameAnnotation)
let image = imageUtils.loadImageFromPath(imgPath)
//show image
routeImageView.image = image
togglePhotoView()
//deselect annotation
mapView.deselectAnnotation(annotation, animated: false)
}
*/
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
// Always allow callouts to popup when annotations are tapped
return true
}
func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat {
// Set the alpha for all shape annotations to 1 (full opacity)
return 1
}
func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat {
// Set the line width for polyline annotations
return 3.0
}
func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
//let speedIndex = Int(round(speed/10))
//print(globalSpeedSet.speedSet)
return ColorUtils.polylineColors(globalSpeedSet.speedSet)
}
}
extension showRouteController: msgOverlayDelegate{
func pressedResume() {
print("pressed resume")
AnimationEngine.hideViewAnim(msgOverlay)
}
func pressedSave(){
print("pressed save")
printAllMarker(FuncTypes.PrintMarker)
//msgOverlay.saveButton.backgroundColor = colorUtils.randomColor()
}
}
| apache-2.0 | 2496f1f0a2d8ab6c47e65ddb42847bfb | 34.244468 | 237 | 0.620594 | 4.920124 | false | false | false | false |
iosyaowei/Weibo | WeiBo/Classes/View(视图和控制器)/Main/OAuth/YWUserAccount.swift | 1 | 2381 | //
// YWUserAccount.swift
// WeiBo
//
// Created by 姚巍 on 16/9/17.
// Copyright © 2016年 yao wei. All rights reserved.
// 用户账户信息
import UIKit
private let accountFile: NSString = "userAccount.json"
class YWUserAccount: NSObject {
/// 访问令牌
var access_token: String?
/// 用户代号
var uid: String?
/// access_token 的生命周期 开发者5年 使用者3天
var expires_in: TimeInterval = 0 {
didSet{
expiresDate = Date(timeIntervalSinceNow: expires_in)
}
}
//过期日期
var expiresDate: Date?
//用户昵称
var screen_name: String?
//用户头像地址(大图),180×180像素
var avatar_large: String?
override var description: String {
return yy_modelDescription()
}
//从磁盘读取用户登录信息
override init() {
super.init()
//从磁盘加载保存文件
guard let path = accountFile.yw_appendDocumentDir(),
let data = NSData(contentsOfFile: path),
let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]
else {
return
}
//使用字典设置属性值
yy_modelSet(with: dic ?? [:])
//测试日期
// expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
//判断 token 是否过期
if expiresDate?.compare(Date()) == .orderedAscending {
//账户过期 清空 token uid
access_token = nil
uid = nil
//删除账户文件
_ = try?FileManager.default.removeItem(atPath: path)
}
}
//本地化用户数据模型
func saveAccount(){
// 模型转字典
var dic = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
//删除expires_in 值
dic.removeValue(forKey: "expires_in")
//字典序列化 data
guard let data = try? JSONSerialization.data(withJSONObject: dic, options: []),
let filePath = accountFile.yw_appendDocumentDir() else {
return
}
//写入磁盘
(data as NSData).write(toFile: filePath, atomically: true)
print("用户账户保存成功\(filePath)")
}
}
| mit | c7ebfc99fba81e92de4aacf70f94cc3e | 22.674157 | 113 | 0.543901 | 4.115234 | false | false | false | false |
xxxAIRINxxx/Cmg | Sources/FaceDetection.swift | 1 | 1919 | //
// FaceDetection.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/24.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public enum Accuracy {
case low
case high
var options: [String : AnyObject] {
switch self {
case .low:
return [CIDetectorAccuracy: CIDetectorAccuracyLow as AnyObject]
case .high:
return [CIDetectorAccuracy: CIDetectorAccuracyHigh as AnyObject]
}
}
}
public enum Option {
case smile
case eyeBlink
var options: [String : AnyObject] {
switch self {
case .smile:
return [CIDetectorSmile: true as AnyObject]
case .eyeBlink:
return [CIDetectorEyeBlink: true as AnyObject]
}
}
}
public struct FaceDetection {
public let accuracy: Accuracy
public init(accuracy: Accuracy = .high) {
self.accuracy = accuracy
// let options: [String : AnyObject] = [CIDetectorSmile: true, CIDetectorEyeBlink: true]
// let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])
}
public func processing(_ uiImage: UIImage) -> [CIFaceFeature] {
guard let ciImage = CIImage.generate(uiImage) else { return [] }
let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: self.accuracy.options)
return detector!.features(in: ciImage, options: [:]).compactMap() { $0 as? CIFaceFeature }
}
public func detectionOfFaceBounds(_ image: UIImage) -> [CGRect] {
let features = self.processing(image)
return features.map() {
var faceRect = $0.bounds
faceRect.origin.y = image.size.height - faceRect.origin.y - faceRect.size.height
return faceRect
}
}
}
| mit | 6f3eef362acae458f7159fbcf6d6a856 | 27.205882 | 131 | 0.623045 | 4.534279 | false | false | false | false |
ImaginarySenseHackatons/TrolleySense | Software/PublicAppiOS/Carthage/Checkouts/MapboxDirections.swift/MapboxDirections/MBDirections.swift | 2 | 16594 | typealias JSONDictionary = [String: Any]
/// Indicates that an error occurred in MapboxDirections.
public let MBDirectionsErrorDomain = "MBDirectionsErrorDomain"
/// The Mapbox access token specified in the main application bundle’s Info.plist.
let defaultAccessToken = Bundle.main.object(forInfoDictionaryKey: "MGLMapboxAccessToken") as? String
/// The user agent string for any HTTP requests performed directly within this library.
let userAgent: String = {
var components: [String] = []
if let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
components.append("\(appName)/\(version)")
}
let libraryBundle: Bundle? = Bundle(for: Directions.self)
if let libraryName = libraryBundle?.infoDictionary?["CFBundleName"] as? String, let version = libraryBundle?.infoDictionary?["CFBundleShortVersionString"] as? String {
components.append("\(libraryName)/\(version)")
}
let system: String
#if os(OSX)
system = "macOS"
#elseif os(iOS)
system = "iOS"
#elseif os(watchOS)
system = "watchOS"
#elseif os(tvOS)
system = "tvOS"
#elseif os(Linux)
system = "Linux"
#endif
let systemVersion = ProcessInfo().operatingSystemVersion
components.append("\(system)/\(systemVersion.majorVersion).\(systemVersion.minorVersion).\(systemVersion.patchVersion)")
let chip: String
#if arch(x86_64)
chip = "x86_64"
#elseif arch(arm)
chip = "arm"
#elseif arch(arm64)
chip = "arm64"
#elseif arch(i386)
chip = "i386"
#endif
components.append("(\(chip))")
return components.joined(separator: " ")
}()
extension CLLocationCoordinate2D {
/**
Initializes a coordinate pair based on the given GeoJSON coordinates array.
*/
internal init(geoJSON array: [Double]) {
assert(array.count == 2)
self.init(latitude: array[1], longitude: array[0])
}
/**
Initializes a coordinate pair based on the given GeoJSON point object.
*/
internal init(geoJSON point: JSONDictionary) {
assert(point["type"] as? String == "Point")
self.init(geoJSON: point["coordinates"] as! [Double])
}
internal static func coordinates(geoJSON lineString: JSONDictionary) -> [CLLocationCoordinate2D] {
let type = lineString["type"] as? String
assert(type == "LineString" || type == "Point")
let coordinates = lineString["coordinates"] as! [[Double]]
return coordinates.map { self.init(geoJSON: $0) }
}
}
extension CLLocation {
/**
Initializes a CLLocation object with the given coordinate pair.
*/
internal convenience init(coordinate: CLLocationCoordinate2D) {
self.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
/**
A `Directions` object provides you with optimal directions between different locations, or waypoints. The directions object passes your request to the [Mapbox Directions API](https://www.mapbox.com/api-documentation/?language=Swift#directions) and returns the requested information to a closure (block) that you provide. A directions object can handle multiple simultaneous requests. A `RouteOptions` object specifies criteria for the results, such as intermediate waypoints, a mode of transportation, or the level of detail to be returned.
Each result produced by the directions object is stored in a `Route` object. Depending on the `RouteOptions` object you provide, each route may include detailed information suitable for turn-by-turn directions, or it may include only high-level information such as the distance, estimated travel time, and name of each leg of the trip. The waypoints that form the request may be conflated with nearby locations, as appropriate; the resulting waypoints are provided to the closure.
*/
@objc(MBDirections)
open class Directions: NSObject {
/**
A closure (block) to be called when a directions request is complete.
- parameter waypoints: An array of `Waypoint` objects. Each waypoint object corresponds to a `Waypoint` object in the original `RouteOptions` object. The locations and names of these waypoints are the result of conflating the original waypoints to known roads. The waypoints may include additional information that was not specified in the original waypoints.
If the request was canceled or there was an error obtaining the routes, this parameter may be `nil`.
- parameter routes: An array of `Route` objects. The preferred route is first; any alternative routes come next if the `RouteOptions` object’s `includesAlternativeRoutes` property was set to `true`. The preferred route depends on the route options object’s `profileIdentifier` property.
If the request was canceled or there was an error obtaining the routes, this parameter is `nil`. This is not to be confused with the situation in which no results were found, in which case the array is present but empty.
- parameter error: The error that occurred, or `nil` if the placemarks were obtained successfully.
*/
public typealias CompletionHandler = (_ waypoints: [Waypoint]?, _ routes: [Route]?, _ error: NSError?) -> Void
// MARK: Creating a Directions Object
/**
The shared directions object.
To use this object, a Mapbox [access token](https://www.mapbox.com/help/define-access-token/) should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
@objc(sharedDirections)
open static let shared = Directions(accessToken: nil)
/// The API endpoint to request the directions from.
internal var apiEndpoint: URL
/// The Mapbox access token to associate the request with.
internal let accessToken: String
/**
Initializes a newly created directions object with an optional access token and host.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the directions object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
- parameter host: An optional hostname to the server API. The [Mapbox Directions API](https://www.mapbox.com/api-documentation/?language=Swift#directions) endpoint is used by default.
*/
public init(accessToken: String?, host: String?) {
let accessToken = accessToken ?? defaultAccessToken
assert(accessToken != nil && !accessToken!.isEmpty, "A Mapbox access token is required. Go to <https://www.mapbox.com/studio/account/tokens/>. In Info.plist, set the MGLMapboxAccessToken key to your access token, or use the Directions(accessToken:host:) initializer.")
self.accessToken = accessToken!
var baseURLComponents = URLComponents()
baseURLComponents.scheme = "https"
baseURLComponents.host = host ?? "api.mapbox.com"
self.apiEndpoint = baseURLComponents.url!
}
/**
Initializes a newly created directions object with an optional access token.
The directions object sends requests to the [Mapbox Directions API](https://www.mapbox.com/api-documentation/?language=Swift#directions) endpoint.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the directions object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
public convenience init(accessToken: String?) {
self.init(accessToken: accessToken, host: nil)
}
// MARK: Getting Directions
/**
Begins asynchronously calculating the route or routes using the given options and delivers the results to a closure.
This method retrieves the routes asynchronously over a network connection. If a connection error or server error occurs, details about the error are passed into the given completion handler in lieu of the routes.
Routes may be displayed atop a [Mapbox map](https://www.mapbox.com/maps/). They may be cached but may not be stored permanently. To use the results in other contexts or store them permanently, [upgrade to a Mapbox enterprise plan](https://www.mapbox.com/directions/#pricing).
- parameter options: A `RouteOptions` object specifying the requirements for the resulting routes.
- parameter completionHandler: The closure (block) to call with the resulting routes. This closure is executed on the application’s main thread.
- returns: The data task used to perform the HTTP request. If, while waiting for the completion handler to execute, you no longer want the resulting routes, cancel this task.
*/
@objc(calculateDirectionsWithOptions:completionHandler:)
open func calculate(_ options: RouteOptions, completionHandler: @escaping CompletionHandler) -> URLSessionDataTask {
let url = self.url(forCalculating: options)
let task = dataTask(with: url, completionHandler: { (json) in
let response = options.response(from: json)
if let routes = response.1 {
for route in routes {
route.accessToken = self.accessToken
route.apiEndpoint = self.apiEndpoint
}
}
completionHandler(response.0, response.1, nil)
}) { (error) in
completionHandler(nil, nil, error)
}
task.resume()
return task
}
/**
Returns a URL session task for the given URL that will run the given closures on completion or error.
- parameter url: The URL to request.
- parameter completionHandler: The closure to call with the parsed JSON response dictionary.
- parameter errorHandler: The closure to call when there is an error.
- returns: The data task for the URL.
- postcondition: The caller must resume the returned task.
*/
fileprivate func dataTask(with url: URL, completionHandler: @escaping (_ json: JSONDictionary) -> Void, errorHandler: @escaping (_ error: NSError) -> Void) -> URLSessionDataTask {
var request = URLRequest(url: url)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
return URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
var json: JSONDictionary = [:]
if let data = data, response?.mimeType == "application/json" {
do {
json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDictionary
} catch {
assert(false, "Invalid data")
}
}
let apiStatusCode = json["code"] as? String
let apiMessage = json["message"] as? String
guard data != nil && error == nil && ((apiStatusCode == nil && apiMessage == nil) || apiStatusCode == "Ok") else {
let apiError = Directions.informativeError(describing: json, response: response, underlyingError: error as NSError?)
DispatchQueue.main.async {
errorHandler(apiError)
}
return
}
DispatchQueue.main.async {
completionHandler(json)
}
}
}
/**
The HTTP URL used to fetch the routes from the API.
After requesting the URL returned by this method, you can parse the JSON data in the response and pass it into the `Route.init(json:waypoints:profileIdentifier:)` initializer.
*/
@objc(URLForCalculatingDirectionsWithOptions:)
open func url(forCalculating options: RouteOptions) -> URL {
let params = options.params + [
URLQueryItem(name: "access_token", value: accessToken),
]
let unparameterizedURL = URL(string: options.path, relativeTo: apiEndpoint)!
var components = URLComponents(url: unparameterizedURL, resolvingAgainstBaseURL: true)!
components.queryItems = params
return components.url!
}
/**
Returns an error that supplements the given underlying error with additional information from the an HTTP response’s body or headers.
*/
static func informativeError(describing json: JSONDictionary, response: URLResponse?, underlyingError error: NSError?) -> NSError {
let apiStatusCode = json["code"] as? String
var userInfo = error?.userInfo ?? [:]
if let response = response as? HTTPURLResponse {
var failureReason: String? = nil
var recoverySuggestion: String? = nil
switch (response.statusCode, apiStatusCode ?? "") {
case (200, "NoRoute"):
failureReason = "No route could be found between the specified locations."
recoverySuggestion = "Make sure it is possible to travel between the locations with the mode of transportation implied by the profileIdentifier option. For example, it is impossible to travel by car from one continent to another without either a land bridge or a ferry connection."
case (200, "NoSegment"):
failureReason = "A specified location could not be associated with a roadway or pathway."
recoverySuggestion = "Make sure the locations are close enough to a roadway or pathway. Try setting the coordinateAccuracy property of all the waypoints to a negative value."
case (404, "ProfileNotFound"):
failureReason = "Unrecognized profile identifier."
recoverySuggestion = "Make sure the profileIdentifier option is set to one of the provided constants, such as MBDirectionsProfileIdentifierAutomobile."
case (429, _):
if let timeInterval = response.rateLimitInterval, let maximumCountOfRequests = response.rateLimit {
let intervalFormatter = DateComponentsFormatter()
intervalFormatter.unitsStyle = .full
let formattedInterval = intervalFormatter.string(from: timeInterval) ?? "\(timeInterval) seconds"
let formattedCount = NumberFormatter.localizedString(from: NSNumber(value: maximumCountOfRequests), number: .decimal)
failureReason = "More than \(formattedCount) requests have been made with this access token within a period of \(formattedInterval)."
}
if let rolloverTime = response.rateLimitResetTime {
let formattedDate = DateFormatter.localizedString(from: rolloverTime, dateStyle: .long, timeStyle: .long)
recoverySuggestion = "Wait until \(formattedDate) before retrying."
}
default:
// `message` is v4 or v5; `error` is v4
failureReason = json["message"] as? String ?? json["error"] as? String
}
userInfo[NSLocalizedFailureReasonErrorKey] = failureReason ?? userInfo[NSLocalizedFailureReasonErrorKey] ?? HTTPURLResponse.localizedString(forStatusCode: error?.code ?? -1)
userInfo[NSLocalizedRecoverySuggestionErrorKey] = recoverySuggestion ?? userInfo[NSLocalizedRecoverySuggestionErrorKey]
}
if let error = error {
userInfo[NSUnderlyingErrorKey] = error
}
return NSError(domain: error?.domain ?? MBDirectionsErrorDomain, code: error?.code ?? -1, userInfo: userInfo)
}
}
extension HTTPURLResponse {
var rateLimit: UInt? {
guard let limit = allHeaderFields["X-Rate-Limit-Limit"] as? String else {
return nil
}
return UInt(limit)
}
var rateLimitInterval: TimeInterval? {
guard let interval = allHeaderFields["X-Rate-Limit-Interval"] as? String else {
return nil
}
return TimeInterval(interval)
}
var rateLimitResetTime: Date? {
guard let resetTime = allHeaderFields["X-Rate-Limit-Reset"] as? String else {
return nil
}
guard let resetTimeNumber = Double(resetTime) else {
return nil
}
return Date(timeIntervalSince1970: resetTimeNumber)
}
}
| apache-2.0 | dbbbda2ab3c5f766652d44d55a11a21f | 52.305466 | 541 | 0.674991 | 5.046575 | false | false | false | false |
badoo/Chatto | ChattoAdditions/sources/Chat Items/PhotoMessages/PhotoMessagePresenterBuilder.swift | 1 | 3244 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import Chatto
open class PhotoMessagePresenterBuilder<ViewModelBuilderT, InteractionHandlerT>: ChatItemPresenterBuilderProtocol where
ViewModelBuilderT: ViewModelBuilderProtocol,
ViewModelBuilderT.ViewModelT: PhotoMessageViewModelProtocol,
InteractionHandlerT: BaseMessageInteractionHandlerProtocol,
InteractionHandlerT.MessageType == ViewModelBuilderT.ModelT,
InteractionHandlerT.ViewModelType == ViewModelBuilderT.ViewModelT {
public typealias ModelT = ViewModelBuilderT.ModelT
public typealias ViewModelT = ViewModelBuilderT.ViewModelT
public init(
viewModelBuilder: ViewModelBuilderT,
interactionHandler: InteractionHandlerT?) {
self.viewModelBuilder = viewModelBuilder
self.interactionHandler = interactionHandler
}
public let viewModelBuilder: ViewModelBuilderT
public let interactionHandler: InteractionHandlerT?
public let sizingCell: PhotoMessageCollectionViewCell = PhotoMessageCollectionViewCell.sizingCell()
public lazy var photoCellStyle: PhotoMessageCollectionViewCellStyleProtocol = PhotoMessageCollectionViewCellDefaultStyle()
public lazy var baseCellStyle: BaseMessageCollectionViewCellStyleProtocol = BaseMessageCollectionViewCellDefaultStyle()
open func canHandleChatItem(_ chatItem: ChatItemProtocol) -> Bool {
return self.viewModelBuilder.canCreateViewModel(fromModel: chatItem)
}
open func createPresenterWithChatItem(_ chatItem: ChatItemProtocol) -> ChatItemPresenterProtocol {
assert(self.canHandleChatItem(chatItem))
return PhotoMessagePresenter<ViewModelBuilderT, InteractionHandlerT>(
messageModel: chatItem as! ModelT,
viewModelBuilder: self.viewModelBuilder,
interactionHandler: self.interactionHandler,
sizingCell: sizingCell,
baseCellStyle: self.baseCellStyle,
photoCellStyle: self.photoCellStyle
)
}
open var presenterType: ChatItemPresenterProtocol.Type {
return PhotoMessagePresenter<ViewModelBuilderT, InteractionHandlerT>.self
}
}
| mit | 76ac93dc5aeb9d407d49d234cfef1a46 | 46.014493 | 126 | 0.780826 | 6.097744 | false | false | false | false |
ciiqr/contakt | contakt/contakt/Visuals.swift | 1 | 1477 | //
// Visuals.swift
// contakt
//
// Created by William Villeneuve on 2016-01-19.
// Copyright © 2016 William Villeneuve. All rights reserved.
//
import UIKit
struct Visuals
{
// MARK: - Constants
// MARK: Colours
private static let white = UIColor.whiteColor()
private static let lightBlue = UIColor(hex: 0xADD8E6)
private static let lightGray = UIColor(hex: 0xFCFCFC)
private static let lightGreen = UIColor(hex: 0xBDDCB6)
private static let lightPurple = UIColor(hex: 0xC9A3DB)
// MARK: Nav Bar
static let navBarBackgroundColour = lightBlue
static let navBarTint = white
static let navBarTextAttributes = [NSForegroundColorAttributeName : navBarTint]
static let navBarIcon = UIImage(imageLiteral: "navbar-icon")
static let navBarFont = UIFont(name: "AvenirNext", size: 20)
// MARK: Background
static let backgroundColour = lightGray
// MARK: Contacts List
static let contactSwipePhoneActionColour = lightGreen
static let contactSwipeEmailActionColour = lightPurple
static let contactsListSectionIndexColor = lightBlue
static let contactsListSectionIndexBackgroundColor = lightGray
// MARK: Search bar
static let searchBarBackgroundColour = lightBlue
static let searchBarTint = white
static let searchBarTextFieldTint = lightBlue
// MARK: Contact photo
static let contactDefaultPhoto = UIImage(imageLiteral: "contact-photo-default")
} | unlicense | db88ce65e5d21ae91ef1f9d4619b7085 | 31.822222 | 83 | 0.724255 | 4.6125 | false | false | false | false |
LeoMobileDeveloper/PullToRefreshKit | Demo/Demo/TaoBaoRefreshHeader.swift | 1 | 5393 | //
// TaoBaoRefreshHeader.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/7/14.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
import PullToRefreshKit
class TaoBaoRefreshHeader:UIView,RefreshableHeader{
fileprivate let circleLayer = CAShapeLayer()
fileprivate let arrowLayer = CAShapeLayer()
fileprivate let textLabel = UILabel()
fileprivate let strokeColor = UIColor(red: 135.0/255.0, green: 136.0/255.0, blue: 137.0/255.0, alpha: 1.0)
fileprivate let imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 230, height: 35))
override init(frame: CGRect) {
super.init(frame: frame)
setUpCircleLayer()
setUpArrowLayer()
textLabel.textAlignment = .center
textLabel.textColor = UIColor.lightGray
textLabel.font = UIFont.systemFont(ofSize: 14)
textLabel.text = "下拉即可刷新..."
imageView.image = UIImage(named: "taobaoLogo")
self.addSubview(imageView)
self.addSubview(textLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
//放置Views和Layer
textLabel.frame = CGRect(x: 0,y: 0,width: 120, height: 40)
imageView.center = CGPoint(x: self.frame.width/2, y: self.frame.height - 60 - 18)
textLabel.center = CGPoint(x: self.frame.width/2 + 20, y: self.frame.height - 30)
self.arrowLayer.position = CGPoint(x: self.frame.width/2 - 60, y: self.frame.height - 30)
self.circleLayer.position = CGPoint(x: self.frame.width/2 - 60, y: self.frame.height - 30)
}
func setUpArrowLayer(){
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 20, y: 15))
bezierPath.addLine(to: CGPoint(x: 20, y: 25))
bezierPath.addLine(to: CGPoint(x: 25,y: 20))
bezierPath.move(to: CGPoint(x: 20, y: 25))
bezierPath.addLine(to: CGPoint(x: 15, y: 20))
self.arrowLayer.path = bezierPath.cgPath
self.arrowLayer.strokeColor = UIColor.lightGray.cgColor
self.arrowLayer.fillColor = UIColor.clear.cgColor
self.arrowLayer.lineWidth = 1.0
#if swift(>=4.2)
self.circleLayer.lineCap = CAShapeLayerLineCap.round
#else
self.circleLayer.lineCap = kCALineCapRound
#endif
self.arrowLayer.bounds = CGRect(x: 0, y: 0,width: 40, height: 40)
self.arrowLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.layer.addSublayer(self.arrowLayer)
}
func setUpCircleLayer(){
let bezierPath = UIBezierPath(arcCenter: CGPoint(x: 20, y: 20),
radius: 12.0,
startAngle:-CGFloat.pi/2,
endAngle: CGFloat.pi/2.0 * 3.0,
clockwise: true)
self.circleLayer.path = bezierPath.cgPath
self.circleLayer.strokeColor = UIColor.lightGray.cgColor
self.circleLayer.fillColor = UIColor.clear.cgColor
self.circleLayer.strokeStart = 0.05
self.circleLayer.strokeEnd = 0.05
self.circleLayer.lineWidth = 1.0
#if swift(>=4.2)
self.circleLayer.lineCap = CAShapeLayerLineCap.round
#else
self.circleLayer.lineCap = kCALineCapRound
#endif
self.circleLayer.bounds = CGRect(x: 0, y: 0,width: 40, height: 40)
self.circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.layer.addSublayer(self.circleLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - RefreshableHeader -
func heightForHeader() -> CGFloat {
return 100
}
func heightForFireRefreshing() -> CGFloat {
return 60.0
}
func heightForRefreshingState() -> CGFloat {
return 60.0
}
func percentUpdateDuringScrolling(_ percent:CGFloat){
let adjustPercent = max(min(1.0, percent),0.0)
if adjustPercent == 1.0{
textLabel.text = "释放即可刷新..."
}else{
textLabel.text = "下拉即可刷新..."
}
self.circleLayer.strokeEnd = 0.05 + 0.9 * adjustPercent
}
func didBeginRefreshingState(){
self.circleLayer.strokeEnd = 0.95
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.toValue = NSNumber(value: Double.pi * 2.0)
rotateAnimation.duration = 0.6
rotateAnimation.isCumulative = true
rotateAnimation.repeatCount = 10000000
self.circleLayer.add(rotateAnimation, forKey: "rotate")
self.arrowLayer.isHidden = true
textLabel.text = "刷新中..."
}
func didBeginHideAnimation(_ result:RefreshResult){
transitionWithOutAnimation {
self.circleLayer.strokeEnd = 0.05
};
self.circleLayer.removeAllAnimations()
}
func didCompleteHideAnimation(_ result:RefreshResult){
transitionWithOutAnimation {
self.circleLayer.strokeEnd = 0.05
};
self.arrowLayer.isHidden = false
textLabel.text = "下拉即可刷新"
}
func transitionWithOutAnimation(_ clousre:()->()){
CATransaction.begin()
CATransaction.setDisableActions(true)
clousre()
CATransaction.commit()
}
}
| mit | cccfb82100925bc75fadd1b870446266 | 36.272727 | 110 | 0.620263 | 4.230159 | false | false | false | false |
rollbar/rollbar-ios | Examples/RollbarWithinAnotherFramework/KnobControl/KnobControl/RotationGestureRecognizer.swift | 1 | 2762 | /// Copyright (c) 2018 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
import UIKit.UIGestureRecognizerSubclass
class RotationGestureRecognizer: UIPanGestureRecognizer {
private(set) var touchAngle: CGFloat = 0
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
updateAngle(with: touches)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
updateAngle(with: touches)
}
private func updateAngle(with touches: Set<UITouch>) {
guard let touch = touches.first, let view = view else {
return
}
let touchPoint = touch.location(in: view)
touchAngle = angle(for: touchPoint, in: view)
}
private func angle(for point: CGPoint, in view: UIView) -> CGFloat {
let centerOffset = CGPoint(x: point.x - view.bounds.midX, y: point.y - view.bounds.midY)
return atan2(centerOffset.y, centerOffset.x)
}
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
maximumNumberOfTouches = 1
minimumNumberOfTouches = 1
}
}
| mit | fc6efffffaa4caf61f555ae36ae0e302 | 42.15625 | 92 | 0.738957 | 4.491057 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Home/VersionCheck/VersionCheckAlertViewController.swift | 1 | 4028 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Reusable
protocol VersionCheckAlertViewControllerDelegate: AnyObject {
func alertViewControllerDidRequestDismissal(_ alertViewController: VersionCheckAlertViewController)
func alertViewControllerDidRequestAction(_ alertViewController: VersionCheckAlertViewController)
}
struct VersionCheckAlertViewControllerDetails {
let title: String
let subtitle: String
let actionButtonTitle: String
}
class VersionCheckAlertViewController: UIViewController {
@IBOutlet private var alertContainerView: UIView!
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var subtitleLabel: UILabel!
@IBOutlet private var dismissButton: UIButton!
@IBOutlet private var actionButton: UIButton!
private var themeService: ThemeService!
private var details: VersionCheckAlertViewControllerDetails?
weak var delegate: VersionCheckAlertViewControllerDelegate?
static func instantiate(themeService: ThemeService) -> VersionCheckAlertViewController {
let versionCheckAlertViewController = VersionCheckAlertViewController(nibName: nil, bundle: nil)
versionCheckAlertViewController.themeService = themeService
versionCheckAlertViewController.modalPresentationStyle = .overFullScreen
versionCheckAlertViewController.modalTransitionStyle = .crossDissolve
return versionCheckAlertViewController
}
override func viewDidLoad() {
super.viewDidLoad()
actionButton.layer.masksToBounds = true
actionButton.layer.cornerRadius = 6.0
configureWithDetails(details)
NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: .themeServiceDidChangeTheme, object: nil)
updateTheme()
}
func configureWithDetails(_ details: VersionCheckAlertViewControllerDetails?) {
guard let details = details else {
return
}
guard self.isViewLoaded else {
self.details = details
return
}
titleLabel.text = details.title
actionButton.setTitle(details.actionButtonTitle, for: .normal)
let attributedSubtitle = NSMutableAttributedString(string: details.subtitle)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.2
paragraphStyle.alignment = .center
attributedSubtitle.addAttribute(.paragraphStyle, value: paragraphStyle, range: .init(location: 0, length: attributedSubtitle.length))
subtitleLabel.attributedText = attributedSubtitle
}
// MARK: - Private
@IBAction private func onDismissButtonTap(_ sender: UIButton) {
delegate?.alertViewControllerDidRequestDismissal(self)
}
@IBAction private func onActionButtonTap(_ sender: UIButton) {
delegate?.alertViewControllerDidRequestAction(self)
}
@objc private func updateTheme() {
let theme = themeService.theme
alertContainerView.backgroundColor = theme.colors.background
titleLabel.textColor = theme.colors.primaryContent
subtitleLabel.textColor = theme.colors.secondaryContent
dismissButton.tintColor = theme.colors.secondaryContent
actionButton.vc_setBackgroundColor(theme.colors.accent, for: .normal)
}
}
| apache-2.0 | a34aef04c40c899a5b16bcf78d170036 | 35.618182 | 141 | 0.717726 | 5.804035 | false | false | false | false |
lxdcn/NEPacketTunnelVPNDemo | NEPacketTunnelVPNDemo/ViewController.swift | 1 | 4446 | //
// ViewController.swift
// NEPacketTunnelVPNDemo
//
// Created by lxd on 12/8/16.
// Copyright © 2016 lxd. All rights reserved.
//
import UIKit
import NetworkExtension
class ViewController: UIViewController {
var vpnManager: NETunnelProviderManager = NETunnelProviderManager()
@IBOutlet var connectButton: UIButton!
// Hard code VPN configurations
let tunnelBundleId = "ne.packet.tunnel.vpn.demo.tunnel"
let serverAddress = "<server-ip>"
let serverPort = "54345"
let mtu = "1400"
let ip = "10.8.0.2"
let subnet = "255.255.255.0"
let dns = "8.8.8.8,8.4.4.4"
private func initVPNTunnelProviderManager() {
NETunnelProviderManager.loadAllFromPreferences { (savedManagers: [NETunnelProviderManager]?, error: Error?) in
if let error = error {
print(error)
}
if let savedManagers = savedManagers {
if savedManagers.count > 0 {
self.vpnManager = savedManagers[0]
}
}
self.vpnManager.loadFromPreferences(completionHandler: { (error:Error?) in
if let error = error {
print(error)
}
let providerProtocol = NETunnelProviderProtocol()
providerProtocol.providerBundleIdentifier = self.tunnelBundleId
providerProtocol.providerConfiguration = ["port": self.serverPort,
"server": self.serverAddress,
"ip": self.ip,
"subnet": self.subnet,
"mtu": self.mtu,
"dns": self.dns
]
providerProtocol.serverAddress = self.serverAddress
self.vpnManager.protocolConfiguration = providerProtocol
self.vpnManager.localizedDescription = "NEPacketTunnelVPNDemoConfig"
self.vpnManager.isEnabled = true
self.vpnManager.saveToPreferences(completionHandler: { (error:Error?) in
if let error = error {
print(error)
} else {
print("Save successfully")
}
})
self.VPNStatusDidChange(nil)
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initVPNTunnelProviderManager()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func VPNStatusDidChange(_ notification: Notification?) {
print("VPN Status changed:")
let status = self.vpnManager.connection.status
switch status {
case .connecting:
print("Connecting...")
connectButton.setTitle("Disconnect", for: .normal)
break
case .connected:
print("Connected...")
connectButton.setTitle("Disconnect", for: .normal)
break
case .disconnecting:
print("Disconnecting...")
break
case .disconnected:
print("Disconnected...")
connectButton.setTitle("Connect", for: .normal)
break
case .invalid:
print("Invliad")
break
case .reasserting:
print("Reasserting...")
break
}
}
@IBAction func go(_ sender: UIButton, forEvent event: UIEvent) {
print("Go!")
self.vpnManager.loadFromPreferences { (error:Error?) in
if let error = error {
print(error)
}
if (sender.title(for: .normal) == "Connect") {
do {
try self.vpnManager.connection.startVPNTunnel()
} catch {
print(error)
}
} else {
self.vpnManager.connection.stopVPNTunnel()
}
}
}
}
| mit | 4375623614a479a255d4d63f66643376 | 32.674242 | 173 | 0.526884 | 5.297974 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps | Playgrounds/GCD_Closure_PartThree.playground/Contents.swift | 1 | 430 | //: Playground - noun: a place where people can play
import UIKit
typealias Integer = Int
typealias int = Int
let a: Integer = 1
let b: int = 2
let c = 1+2
typealias IntToInt = (Int) -> Int
typealias IntMaker = (Void)->Int
func makeCounter() -> IntMaker {
var n = 0
func adder() -> Int {
n = n + 1
return n
}
return adder
}
// each closure has a copy of all the captured variables
| mit | 8ac56e20a5b5b0fcaeaabd7a20fbcf14 | 14.925926 | 56 | 0.606977 | 3.553719 | false | false | false | false |
doncl/shortness-of-pants | BBPDropDown/BBPDropDown/BBPDropDownCell.swift | 1 | 1092 | //
// BBPDropDownCell.swift
// BBPDropDown
//
// Created by Don Clore on 3/5/16.
// Copyright © 2016 Beer Barrel Poker Studios. All rights reserved.
//
import UIKit
class BBPDropDownCell: UITableViewCell {
@IBOutlet var selectionIndicator: UIImageView!
var selectionImage : UIImage? {
get {
return selectionIndicator.image
}
set (newImage) {
selectionIndicator.image = newImage
}
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clear
textLabel!.textColor = UIColor.white
textLabel!.font = UIFont(name: "HelveticaNueue", size:22.0)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView!.frame = imageView!.frame.offsetBy(dx: 6, dy: 0)
textLabel!.frame = textLabel!.frame.offsetBy(dx: 6, dy: 0)
}
func showSelectionMark(_ selected: Bool) {
selectionIndicator.isHidden = !selected
}
}
| mit | fbbd74d182ff21b5bb792d61bc88a212 | 23.795455 | 68 | 0.625115 | 4.434959 | false | false | false | false |
zarochintsev/MotivationBox | CurrentMotivation/Classes/PresentationLayer/Modules/CurrentMotivation/Module/Assembly/CurrentMotivationAssembly.swift | 1 | 2695 | //
// CurrentMotivationAssembly.swift
//
// MIT License
//
// Copyright (c) 2017 Alex Zarochintsev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Swinject
import SwinjectStoryboard
class CurrentMotivationAssembly: Assembly {
func assemble(container: Container) {
container.register(CurrentMotivationInteractor.self) { (r: Resolver, presenter: CurrentMotivationPresenter) in
let interactor = CurrentMotivationInteractor()
interactor.output = presenter
interactor.motivationService = r.resolve(MotivationService.self)
return interactor
}
container.register(CurrentMotivationRouter.self) { (r: Resolver, viewController: CurrentMotivationViewController) in
let router = CurrentMotivationRouter()
router.transitionHandler = viewController
return router
}
container.register(CurrentMotivationPresenter.self) { (r: Resolver, viewController: CurrentMotivationViewController) in
let presenter = CurrentMotivationPresenter()
presenter.view = viewController
presenter.interactor = r.resolve(CurrentMotivationInteractor.self, argument: presenter)
presenter.router = r.resolve(CurrentMotivationRouter.self, argument: viewController)
return presenter
}
container.storyboardInitCompleted(CurrentMotivationViewController.self) { r, viewController in
viewController.output = r.resolve(CurrentMotivationPresenter.self, argument: viewController)
}
}
}
| mit | 83678d29874f30acf252d201302c84a4 | 41.109375 | 127 | 0.712059 | 5.315582 | false | false | false | false |
IT-Department-Projects/POP-II | iOS App/notesNearby_iOS_finalUITests/notesNearby_iOS_final/IQKeyboardManagerSwift/IQTextView/IQTextView.swift | 1 | 4649 | //
// IQTextView.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract UITextView with placeholder support */
public class IQTextView : UITextView {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}
override public func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private var placeholderLabel: UILabel?
/** @abstract To set textView's placeholder text. Default is ni. */
@IBInspectable public var placeholder : String? {
get {
return placeholderLabel?.text
}
set {
if placeholderLabel == nil {
placeholderLabel = UILabel()
if let unwrappedPlaceholderLabel = placeholderLabel {
unwrappedPlaceholderLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
unwrappedPlaceholderLabel.lineBreakMode = .byWordWrapping
unwrappedPlaceholderLabel.numberOfLines = 0
unwrappedPlaceholderLabel.font = self.font
unwrappedPlaceholderLabel.backgroundColor = UIColor.clear
unwrappedPlaceholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0)
unwrappedPlaceholderLabel.alpha = 0
addSubview(unwrappedPlaceholderLabel)
}
}
placeholderLabel?.text = newValue
refreshPlaceholder()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
if let unwrappedPlaceholderLabel = placeholderLabel {
unwrappedPlaceholderLabel.sizeToFit()
unwrappedPlaceholderLabel.frame = CGRect(x: 8, y: 8, width: self.frame.width-16, height: unwrappedPlaceholderLabel.frame.height)
}
}
public func refreshPlaceholder() {
if text.characters.count != 0 {
placeholderLabel?.alpha = 0
} else {
placeholderLabel?.alpha = 1
}
}
override public var text: String! {
didSet {
refreshPlaceholder()
}
}
override public var font : UIFont? {
didSet {
if let unwrappedFont = font {
placeholderLabel?.font = unwrappedFont
} else {
placeholderLabel?.font = UIFont.systemFont(ofSize: 12)
}
}
}
override public var delegate : UITextViewDelegate? {
get {
refreshPlaceholder()
return super.delegate
}
set {
super.delegate = newValue
}
}
}
| mit | f75be18b5694a4188f1f4a1e42d851ec | 33.69403 | 163 | 0.630458 | 5.746601 | false | false | false | false |
natecook1000/swift | test/stdlib/Error.swift | 1 | 4548 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -o %t/Error -DPTR_SIZE_%target-ptrsize -module-name main %s
// RUN: %target-run %t/Error
// REQUIRES: executable_test
import StdlibUnittest
var ErrorTests = TestSuite("Error")
var NoisyErrorLifeCount = 0
var NoisyErrorDeathCount = 0
protocol OtherProtocol {
var otherProperty: String { get }
}
protocol OtherClassProtocol : class {
var otherClassProperty: String { get }
}
class NoisyError : Error, OtherProtocol, OtherClassProtocol {
init() { NoisyErrorLifeCount += 1 }
deinit { NoisyErrorDeathCount += 1 }
let _domain = "NoisyError"
let _code = 123
let otherProperty = "otherProperty"
let otherClassProperty = "otherClassProperty"
}
ErrorTests.test("erasure") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let e: Error = NoisyError()
expectEqual(e._domain, "NoisyError")
expectEqual(e._code, 123)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorTests.test("reflection") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let ne = NoisyError()
let e: Error = ne
var neDump = "", eDump = ""
dump(ne, to: &neDump)
dump(e, to: &eDump)
expectEqual(eDump, neDump)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorTests.test("dynamic casts") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
do {
let ne = NoisyError()
let e: Error = ne
expectTrue(e as! NoisyError === ne)
expectEqual((e as! OtherClassProtocol).otherClassProperty, "otherClassProperty")
expectEqual((e as! OtherProtocol).otherProperty, "otherProperty")
let op: OtherProtocol = ne
expectEqual((op as! Error)._domain, "NoisyError")
expectEqual((op as! Error)._code, 123)
let ocp: OtherClassProtocol = ne
expectEqual((ocp as! Error)._domain, "NoisyError")
expectEqual((ocp as! Error)._code, 123)
// Do the same with rvalues, so we exercise the
// take-on-success/destroy-on-failure paths.
expectEqual(((NoisyError() as Error) as! NoisyError)._domain, "NoisyError")
expectEqual(((NoisyError() as Error) as! OtherClassProtocol).otherClassProperty, "otherClassProperty")
expectEqual(((NoisyError() as Error) as! OtherProtocol).otherProperty, "otherProperty")
expectEqual(((NoisyError() as OtherProtocol) as! Error)._domain, "NoisyError")
expectEqual(((NoisyError() as OtherProtocol) as! Error)._code, 123)
expectEqual(((NoisyError() as OtherClassProtocol) as! Error)._domain, "NoisyError")
expectEqual(((NoisyError() as OtherClassProtocol) as! Error)._code, 123)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
struct DefaultStruct : Error { }
class DefaultClass : Error { }
ErrorTests.test("default domain and code") {
expectEqual(DefaultStruct()._domain, "main.DefaultStruct")
expectEqual(DefaultStruct()._code, 1)
expectEqual(DefaultClass()._domain, "main.DefaultClass")
expectEqual(DefaultClass()._code, 1)
}
enum SillyError: Error { case JazzHands }
ErrorTests.test("try!")
.skip(.custom({ _isFastAssertConfiguration() },
reason: "trap is not guaranteed to happen in -Ounchecked"))
.crashOutputMatches(_isDebugAssertConfiguration()
? "'try!' expression unexpectedly raised an error: "
+ "main.SillyError.JazzHands"
: "")
.code {
expectCrashLater()
let _: () = try! { throw SillyError.JazzHands }()
}
ErrorTests.test("try?") {
var value = try? { () throws -> Int in return 1 }()
expectType(Optional<Int>.self, &value)
expectEqual(Optional(1), value)
expectNil(try? { () throws -> Int in throw SillyError.JazzHands }())
}
enum LifetimeError : Error {
case MistakeOfALifetime(LifetimeTracked, yearsIncarcerated: Int)
}
ErrorTests.test("existential in lvalue") {
expectEqual(0, LifetimeTracked.instances)
do {
var e: Error?
do {
throw LifetimeError.MistakeOfALifetime(LifetimeTracked(0),
yearsIncarcerated: 25)
} catch {
e = error
}
expectEqual(1, LifetimeTracked.instances)
expectEqual(0, e?._code)
}
expectEqual(0, LifetimeTracked.instances)
}
enum UnsignedError: UInt, Error {
#if PTR_SIZE_64
case negativeOne = 0xFFFFFFFFFFFFFFFF
#elseif PTR_SIZE_32
case negativeOne = 0xFFFFFFFF
#else
#error ("Unknown pointer size")
#endif
}
ErrorTests.test("unsigned raw value") {
let negOne: Error = UnsignedError.negativeOne
expectEqual(-1, negOne._code)
}
runAllTests()
| apache-2.0 | ef6168f7d3c1921dc9f7accc364dc84c | 26.731707 | 106 | 0.684257 | 4.183993 | false | true | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/TextFormattingProviding.swift | 1 | 2147 | protocol TextFormattingProviding: AnyObject {
var delegate: TextFormattingDelegate? { get set }
}
protocol TextFormattingButtonsProviding: TextFormattingProviding {
var buttons: [TextFormattingButton] { get set }
}
extension TextFormattingButtonsProviding {
func selectButton(_ button: SectionEditorButton) {
buttons.lazy.first(where: { $0.kind == button.kind })?.isSelected = true
}
func disableButton(_ button: SectionEditorButton) {
buttons.lazy.first(where: { $0.kind == button.kind })?.isEnabled = false
}
func enableAllButtons() {
buttons.lazy.forEach { $0.isEnabled = true }
}
func deselectAllButtons() {
buttons.lazy.forEach { $0.isSelected = false }
}
}
protocol TextFormattingDelegate: AnyObject {
func textFormattingProvidingDidTapClose()
func textFormattingProvidingDidTapHeading(depth: Int)
func textFormattingProvidingDidTapBold()
func textFormattingProvidingDidTapItalics()
func textFormattingProvidingDidTapUnderline()
func textFormattingProvidingDidTapStrikethrough()
func textFormattingProvidingDidTapReference()
func textFormattingProvidingDidTapTemplate()
func textFormattingProvidingDidTapComment()
func textFormattingProvidingDidTapLink()
func textFormattingProvidingDidTapIncreaseIndent()
func textFormattingProvidingDidTapDecreaseIndent()
func textFormattingProvidingDidTapOrderedList()
func textFormattingProvidingDidTapUnorderedList()
func textFormattingProvidingDidTapSuperscript()
func textFormattingProvidingDidTapSubscript()
func textFormattingProvidingDidTapCursorUp()
func textFormattingProvidingDidTapCursorDown()
func textFormattingProvidingDidTapCursorRight()
func textFormattingProvidingDidTapCursorLeft()
func textFormattingProvidingDidTapFindInPage()
func textFormattingProvidingDidTapTextSize(newSize: TextSizeType)
func textFormattingProvidingDidTapTextFormatting()
func textFormattingProvidingDidTapTextStyleFormatting()
func textFormattingProvidingDidTapClearFormatting()
func textFormattingProvidingDidTapMediaInsert()
}
| mit | d09566c6b6800b67c5630afb62971e6f | 38.036364 | 80 | 0.787611 | 5.327543 | false | false | false | false |
asowers1/ASTimer | Example/ASTimer/ViewController.swift | 1 | 3426 | //
// ViewController.swift
// ASTimer
//
// Created by asowers1 on 01/14/2016.
// Copyright (c) 2016 asowers1. All rights reserved.
//
import UIKit
import ASTimer
class ViewController: UIViewController, ASTimerDelegate {
var asTimer:ASTimer?
@IBOutlet weak var timeRemainingLabel: UILabel!
@IBOutlet weak var countdownFinishedImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let now = NSDate()
let timeInterval: NSTimeInterval = 10 // ten seconds
let secondslater = now.dateByAddingTimeInterval(timeInterval) // some seconds as a time intrval
let images = self.animationsImages()
self.countdownFinishedImageView.animationImages = images
self.countdownFinishedImageView.animationDuration = 1
asTimer = ASTimer().timer("Test Timer", expirationTime: secondslater.timeIntervalSinceDate(now), completionBlock: {(Void) -> (Void) in
self.countdownFinishedImageView.startAnimating()
self.timeRemainingLabel.text = "Happy New Year!"
print("Hey, it's been \(timeInterval) seconds! Happy New Year!")
})
// we can listen for timer ticks via the delegate
asTimer?.delegate = self
// Some Example notifications to listen for:
//
// UIApplicationBackgroundRefreshStatusDidChangeNotification
// UIApplicationDidBecomeActiveNotification
// UIApplicationDidChangeStatusBarFrameNotification
// UIApplicationDidChangeStatusBarOrientationNotification
// UIApplicationDidEnterBackgroundNotification
// UIApplicationDidFinishLaunchingNotification
// UIApplicationDidReceiveMemoryWarningNotification
// UIApplicationProtectedDataDidBecomeAvailable
// UIApplicationProtectedDataWillBecomeUnavailable
// UIApplicationSignificantTimeChangeNotification
// UIApplicationUserDidTakeScreenshotNotification
// UIApplicationWillChangeStatusBarOrientationNotification
// UIApplicationWillChangeStatusBarFrameNotification
// UIApplicationWillEnterForegroundNotification
// UIApplicationWillResignActiveNotification
// UIApplicationWillTerminateNotification
// UIContentSizeCategoryDidChangeNotification
//
// Source: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/
// This will always start the timer if it's not already
asTimer?.observeStartNotification("UIApplicationDidBecomeActiveNotification")
// This will always stop the timer if it's not already
asTimer?.observeStopNotification("UIApplicationDidEnterBackgroundNotification")
// for debugging purposes
asTimer?.debugMode = false // false by default
// we fire the timer to start it, but you fire a notification of your choice to do the same thing
asTimer?.fireTimer()
}
// load some images for our example animation that occurs when the timer completion closure is executed
func animationsImages() -> [UIImage] {
var images = [UIImage]()
for index in 0 ... 66 {
images.insert(UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("sparkler_\(index)",ofType:"png")!)!, atIndex: index)
}
return images
}
func timerDidFire(timerName: String?, timeRemaining: NSTimeInterval) {
self.timeRemainingLabel.text = "\(round(timeRemaining)) seconds!"
print("the timer \(timerName as String!) has \(round(timeRemaining)) seconds left")
}
}
| mit | 6aac7ed839cc29acc853dd43798056f2 | 35.446809 | 138 | 0.747519 | 5.395276 | false | false | false | false |
russbishop/swift | stdlib/public/core/Builtin.swift | 1 | 19207 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(X.self)`, when `X` is a class type, is the
/// same regardless of how many stored properties `X` has.
@_transparent
public func sizeof<T>(_:T.Type) -> Int {
return Int(Builtin.sizeof(T.self))
}
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(a)`, when `a` is a class instance, is the
/// same regardless of how many stored properties `a` has.
@_transparent
public func sizeofValue<T>(_:T) -> Int {
return sizeof(T.self)
}
/// Returns the minimum memory alignment of `T`.
@_transparent
public func alignof<T>(_:T.Type) -> Int {
return Int(Builtin.alignof(T.self))
}
/// Returns the minimum memory alignment of `T`.
@_transparent
public func alignofValue<T>(_:T) -> Int {
return alignof(T.self)
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
public func strideof<T>(_:T.Type) -> Int {
return Int(Builtin.strideof_nonzero(T.self))
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
public func strideofValue<T>(_:T) -> Int {
return strideof(T.self)
}
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@_versioned
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@_versioned
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@_versioned
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
@_versioned
internal func _roundUp<T, DestinationType>(
_ pointer: UnsafeMutablePointer<T>,
toAlignmentOf destinationType: DestinationType.Type
) -> UnsafeMutablePointer<DestinationType> {
// Note: unsafe unwrap is safe because this operation can only increase the
// value, and can not produce a null pointer.
return UnsafeMutablePointer<DestinationType>(
bitPattern: _roundUpImpl(
UInt(bitPattern: pointer),
toAlignment: alignof(DestinationType.self))
).unsafelyUnwrapped
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to: U.Type) -> U {
_precondition(sizeof(T.self) == sizeof(U.self),
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
public func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_transparent
func ==(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func !=(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_transparent
func ==(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func !=(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_versioned @_transparent @noreturn internal
func _conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
@_versioned
@_silgen_name("_swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@_versioned
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
let tmp = _canBeClass(x)
// Is not a class.
if tmp == 0 {
return false
// Is a class.
} else if tmp == 1 {
return true
}
// Maybe a class.
return _swift_isClassOrObjCExistentialType(x)
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@_transparent
public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Void> {
return UnsafePointer(Builtin.bridgeToRawPointer(object))
}
@available(*, unavailable, renamed: "unsafeAddress(of:)")
public func unsafeAddressOf(_ object: AnyObject) -> UnsafePointer<Void> {
Builtin.unreachable()
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutablePointer<UInt8> {
let storedPropertyOffset = _roundUp(
sizeof(_HeapObject.self),
toAlignment: alignof(Optional<AnyObject>.self))
return UnsafeMutablePointer<UInt8>(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_versioned
@_transparent
@_semantics("branchhint")
internal func _branchHint<C : Boolean>(_ actual: C, expected: Bool)
-> Bool {
return Bool(Builtin.int_expect_Int1(actual.boolValue._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath<C: Boolean>(_ x: C) -> Bool {
return _branchHint(x.boolValue, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath<C : Boolean>(_ x: C) -> Bool {
return _branchHint(x.boolValue, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
@_versioned
@inline(__always)
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
#if _runtime(_ObjC)
return swift_objc_class_usesNativeSwiftReferenceCounting(
unsafeAddress(of: theClass)
)
#else
return true
#endif
}
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(s390x)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@_versioned
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@_versioned
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@_versioned
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@_versioned
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@_versioned
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(object.dynamicType)
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return unsafeBitCast(
_swift_class_getSuperclass(unsafeBitCast(t, to: OpaquePointer.self)),
to: AnyClass.self)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@_versioned
@_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@_versioned
@_transparent
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
@available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.")
public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T {
Builtin.unreachable()
}
| apache-2.0 | 17b3f007679690e62fcda63a0630c5ed | 31.22651 | 105 | 0.694226 | 3.998959 | false | false | false | false |
LemonLess/BingPaper | BingPaper/StatusBarViewController.swift | 2 | 8157 | //
// StatusBarViewController.swift
// BingPaper
//
// Created by Peng Jingwen on 2015-03-13.
// Copyright (c) 2015 Peng Jingwen. All rights reserved.
//
import Cocoa
import MASPreferences
class StatusBarViewController: NSViewController {
var timerTask = Timer()
var bingPictureManager = BingPictureManager()
var previousDateString = ""
var nextDateString = ""
var wallpaperInfoUrlString = ""
var preferencesWindowController: NSWindowController?
@IBOutlet weak var previousDayButton: NSButton!
@IBOutlet weak var todayButton: NSButton!
@IBOutlet weak var nextDayButton: NSButton!
@IBOutlet weak var dateTextField: NSTextField!
@IBOutlet weak var wallpaperInfoButton: NSButton!
override func awakeFromNib() {
setupDockIcon()
setupTimerTask()
if let currentDate = SharedPreferences.string(forKey: SharedPreferences.Key.CurrentSelectedImageDate) {
_ = jumpToDate(currentDate)
} else {
jumpToToday()
}
downloadWallpapers()
}
func setupDockIcon() {
if SharedPreferences.bool(forKey: SharedPreferences.Key.WillDisplayIconInDock) {
NSApplication.shared.setActivationPolicy(NSApplication.ActivationPolicy.regular)
} else {
NSApplication.shared.setActivationPolicy(NSApplication.ActivationPolicy.accessory)
}
}
func setupTimerTask() {
timerTask = Timer.scheduledTimer(
timeInterval: 3600,
target: self,
selector: #selector(StatusBarViewController.downloadWallpapers),
userInfo: nil,
repeats: true
)
}
@objc func downloadWallpapers() {
DispatchQueue.main.async {
if SharedPreferences.bool(forKey: SharedPreferences.Key.WillAutoDownloadNewImages) {
if let workDir = SharedPreferences.string(forKey: SharedPreferences.Key.DownloadedImagesStoragePath),
let region = SharedPreferences.string(forKey: SharedPreferences.Key.CurrentSelectedBingRegion) {
self.bingPictureManager.fetchWallpapers(workDir: workDir, atRegin: region)
}
if SharedPreferences.bool(forKey: SharedPreferences.Key.WillAutoChangeWallpaper) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
_ = self.jumpToDate(formatter.string(from: Date()))
}
}
}
}
func jumpToDate(_ date: String) -> Bool {
if let workDir = SharedPreferences.string(forKey: SharedPreferences.Key.DownloadedImagesStoragePath),
let region = SharedPreferences.string(forKey: SharedPreferences.Key.CurrentSelectedBingRegion) {
if bingPictureManager.checkWallpaperExist(workDir: workDir, onDate: date, atRegion: region) {
let info = bingPictureManager.getWallpaperInfo(workDir: workDir, onDate: date, atRegion: region)
var infoString = info.copyright
infoString = infoString.replacingOccurrences(of: ",", with: "\n")
infoString = infoString.replacingOccurrences(of: "(", with: "\n")
infoString = infoString.replacingOccurrences(of: ")", with: "")
wallpaperInfoButton.title = infoString
wallpaperInfoUrlString = info.copyrightLink
dateTextField.stringValue = date
SharedPreferences.set(date, forKey: SharedPreferences.Key.CurrentSelectedImageDate)
bingPictureManager.setWallpaper(workDir: workDir, onDate: date, atRegion: region)
let searchLimit = 365
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let date = formatter.date(from: date) {
previousDayButton.isEnabled = false
for index in 1...searchLimit {
let timeInterval = TimeInterval(-3600 * 24 * index)
let anotherDay = date.addingTimeInterval(timeInterval)
let anotherDayString = formatter.string(from: anotherDay)
if bingPictureManager.checkWallpaperExist(workDir: workDir, onDate: anotherDayString, atRegion: region) {
previousDateString = anotherDayString
previousDayButton.isEnabled = true
break
}
}
}
if let date = formatter.date(from: date) {
nextDayButton.isEnabled = false
for index in 1...searchLimit {
let timeInterval = TimeInterval(3600 * 24 * index)
let anotherDay = date.addingTimeInterval(timeInterval)
let anotherDayString = formatter.string(from: anotherDay)
if bingPictureManager.checkWallpaperExist(workDir: workDir, onDate: anotherDayString, atRegion: region) {
nextDateString = anotherDayString
nextDayButton.isEnabled = true
break
}
}
}
return true
}
}
return false
}
func jumpToToday() {
DispatchQueue.main.async {
self.todayButton.isEnabled = false
self.todayButton.title = NSLocalizedString("Fetching...", comment: "N/A")
if let workDir = SharedPreferences.string(forKey: SharedPreferences.Key.DownloadedImagesStoragePath),
let currentRegion = SharedPreferences.string(forKey: SharedPreferences.Key.CurrentSelectedBingRegion) {
self.bingPictureManager.fetchLastWallpaper(workDir: workDir, atRegin: currentRegion)
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let ok = self.jumpToDate(formatter.string(from: Date()))
if !ok {
// Try to use last day's picture.
_ = self.jumpToDate(formatter.string(from: Date().addingTimeInterval(-(3600 * 24))))
}
self.todayButton.isEnabled = true
self.todayButton.title = NSLocalizedString("Today !", comment: "N/A")
}
}
@IBAction func logoClicked(_ sender: NSButton) {
if let path = SharedPreferences.string(forKey: SharedPreferences.Key.DownloadedImagesStoragePath) {
NSWorkspace.shared.openFile(path)
}
}
@IBAction func previousDay(_ sender: NSButton) {
_ = jumpToDate(previousDateString)
}
@IBAction func today(_ sender: NSButton) {
jumpToToday()
}
@IBAction func nextDay(_ sender: NSButton) {
_ = jumpToDate(nextDateString)
}
@IBAction func wallpaperInfoButtonClicked(_ sender: NSButton) {
NSWorkspace.shared.open(NSURL(string: wallpaperInfoUrlString)! as URL)
}
@IBAction func launchPreferencesWindow(_ sender: NSButton) {
if (preferencesWindowController == nil) {
preferencesWindowController = MASPreferencesWindowController.init(
viewControllers: [GeneralPreferencesViewController(), AboutPreferencesViewController()],
title: NSLocalizedString("BingPaper Preferences", comment: "N/A")
)
}
preferencesWindowController?.showWindow(self)
preferencesWindowController?.window?.makeKeyAndOrderFront(self)
NSApplication.shared.activate(ignoringOtherApps: true)
}
@IBAction func quitApplication(_ sender: NSButton) {
NSApplication.shared.terminate(nil)
}
}
| gpl-3.0 | 76b798f1cce4aab9059f0c320d497176 | 39.381188 | 129 | 0.586368 | 5.496631 | false | false | false | false |
kostiakoval/Versions | Source/Versions.swift | 1 | 1897 | //
// Versions.swift
// Versions
//
// Created by Christoffer Winterkvist on 3/2/15.
//
//
import Foundation
public enum Semantic {
case Major, Minor, Patch, Same, Unknown
}
public extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex)))
}
var major: String {
return self[0]
}
var minor: String {
return self[0...2]
}
var patch: String {
return self[0...4]
}
func newerThan(version :String) -> Bool {
return self.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending
}
func olderThan(version: String) -> Bool {
let isEqual: Bool = self == version
return !isEqual ? !self.newerThan(version) : false
}
func majorChange(version: String) -> Bool {
return self.major != version.major
}
func minorChange(version: String) -> Bool {
return self.minor != version.minor && self.olderThan(version)
}
func patchChange(version: String) -> Bool {
return self.patch != version.patch && self.olderThan(version)
}
func semanticCompare(version: String) -> Semantic {
switch self {
case _ where self == version:
return .Same
case _ where self.major != version.major:
return .Major
case _ where self.minor != version.minor && self.olderThan(version):
return .Minor
case _ where self.patch != version.patch && self.olderThan(version):
return .Patch
default:
return .Unknown
}
}
}
| mit | 033798af6b5e7d047214e7731d53e29a | 24.293333 | 123 | 0.600949 | 4.178414 | false | false | false | false |
benlangmuir/swift | validation-test/compiler_crashers_2_fixed/0202-rdar53183030.swift | 28 | 515 | // RUN: not %target-swift-frontend -typecheck %s
protocol MyBindableObject {}
@propertyWrapper
struct MyBinding<T> where T : MyBindableObject {
public var wrappedV: T
public var wrapperValue: MyBinding<T> {
return self
}
public init(initialValue: T) {
self.value = initialValue
}
}
class BeaconDetector: MyBindableObject {
struct ContentView {
@MyBinding var detector = BeaconDetector()
func foo() {
_ = detector.undefined == 1
}
}
}
| apache-2.0 | 571c03c915f9d54389a2395e5e04bda8 | 23.52381 | 50 | 0.63301 | 4.153226 | false | false | false | false |
sgr-ksmt/AutoIncrement_id_Realm_Example | Demo/Blog.swift | 1 | 668 | //
// Blog.swift
// Demo
//
// Created by Suguru Kishimoto on 12/20/16.
//
//
import Foundation
import Realm
import RealmSwift
final class Blog: Object {
dynamic var id = 0
dynamic var title = ""
dynamic var body = ""
dynamic var author = ""
dynamic var createdAt = Date()
dynamic var updatedAt = Date()
convenience init(title: String, body: String, author: String) {
self.init()
self.id = AutoIncrementableID.incremented(for: type(of: self))
self.title = title
self.body = body
self.author = author
}
override static func primaryKey() -> String? {
return "id"
}
}
| mit | d6243236ed20fcba9ddfe924ce75cee9 | 19.875 | 70 | 0.600299 | 3.952663 | false | false | false | false |
Agnosis/Buddlist | Buddlist/Buddlist/ModelController.swift | 1 | 3223 | //
// ModelController.swift
// Buddlist
//
// Created by K on 15/6/4.
// Copyright (c) 2015年 K. All rights reserved.
//
import UIKit
/*
A controller object that manages a simple model -- a collection of month names.
The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:.
It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application.
There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand.
*/
class ModelController: NSObject, UIPageViewControllerDataSource {
var pageData = NSArray()
override init() {
super.init()
// Create the data model.
let dateFormatter = NSDateFormatter()
pageData = dateFormatter.monthSymbols
}
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? {
// Return the data view controller for the given index.
if (self.pageData.count == 0) || (index >= self.pageData.count) {
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController
dataViewController.dataObject = self.pageData[index]
return dataViewController
}
func indexOfViewController(viewController: DataViewController) -> Int {
// Return the index of the given data view controller.
// For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index.
if let dataObject: AnyObject = viewController.dataObject {
return self.pageData.indexOfObject(dataObject)
} else {
return NSNotFound
}
}
// MARK: - Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if (index == 0) || (index == NSNotFound) {
return nil
}
index--
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if index == NSNotFound {
return nil
}
index++
if index == self.pageData.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
}
| mit | a25c9f091431c04a1f7e72a21c57b1ff | 38.765432 | 225 | 0.707544 | 5.621291 | false | false | false | false |
dulingkang/SSImageCropEdit | SSImageCropper/SSImageCropper/CustomClass/ImageCropExtention.swift | 1 | 1503 | //
// ImageCropExtention.swift
// SSImageCropper
//
// Created by dulingkang on 30/11/15.
// Copyright © 2015 shawn. All rights reserved.
//
import UIKit
extension UIImage {
func rotatedImageWithtransform(rotation: CGAffineTransform, rect: CGRect) -> UIImage {
let rotatedImage = self.ssRotatedImageWithtransform(rotation)
let scale = rotatedImage.scale
let cropRect = CGRectApplyAffineTransform(rect, CGAffineTransformMakeScale(scale, scale))
let croppedImage = CGImageCreateWithImageInRect(rotatedImage.CGImage, cropRect)
let image = UIImage(CGImage: croppedImage!, scale: self.scale, orientation: rotatedImage.imageOrientation)
return image
}
func ssRotatedImageWithtransform(transform: CGAffineTransform) -> UIImage {
let size = self.size
UIGraphicsBeginImageContextWithOptions(size,
true, // Opaque
self.scale); // Use image scale
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, size.width / 2, size.height / 2)
CGContextConcatCTM(context, transform)
CGContextTranslateCTM(context, size.width / -2, size.height / -2)
self.drawInRect(CGRectMake(0.0, 0.0, size.width, size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return rotatedImage
}
}
| mit | 7b7b6c984db4c567a8ddf15592299ead | 34.761905 | 114 | 0.658455 | 5.108844 | false | false | false | false |
zhihuitang/Apollo | Apollo/TrafficData.swift | 1 | 1272 | //
// TrafficData.swift
// TrafficPolice
//
// Created by 刘栋 on 2016/11/18.
// Copyright © 2016年 anotheren.com. All rights reserved.
//
import Foundation
public struct TrafficData {
public var received: UInt32 // btyes
public var sent: UInt32 // btyes
public init(received: UInt32, sent: UInt32) {
self.received = received
self.sent = sent
}
public static var zero: TrafficData {
return TrafficData(received: 0, sent: 0)
}
public var total: UInt32 {
return received + sent
}
}
extension TrafficData: CustomStringConvertible {
public var description: String {
return "Rx: \(received.double.unitString), Tx: \(sent.double.unitString)"
}
}
public func +(lhs: TrafficData, rhs: TrafficData) -> TrafficData {
var result = lhs
result.received += rhs.received
result.sent += rhs.sent
return result
}
public func -(lhs: TrafficData, rhs: TrafficData) -> TrafficData {
var result = lhs
if result.received > rhs.received {
result.received -= rhs.received
} else {
result.received = 0
}
if result.sent > rhs.sent {
result.sent -= rhs.sent
} else {
result.sent = 0
}
return result
}
| apache-2.0 | 03b34f3830880e0a2b03191d794106fd | 21.192982 | 81 | 0.618182 | 3.844985 | false | false | false | false |
Molbie/Outlaw | Sources/Outlaw/Types/Value/Set+Value.swift | 1 | 1489 | //
// Set+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/9/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public extension Set {
static func mappedValue<Element: Value>(from object: Any) throws -> Set<Element> {
let anyArray: [Element] = try [Element].mappedValue(from: object)
return Set<Element>(anyArray)
}
}
// MARK: -
// MARK: Transforms
public extension Set {
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element) throws -> T) throws -> Set<T> {
let anyArray: [T] = try [Element].mappedValue(from: object, with: transform)
return Set<T>(anyArray)
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element?) throws -> T) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element?) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
}
| mit | 556929780026787309208977707195c8 | 34.428571 | 122 | 0.633737 | 3.576923 | false | false | false | false |
AlexMcArdle/LooseFoot | LooseFoot/Views/OverviewCellNode.swift | 1 | 1302 | //
// OverviewCellNode.swift
// LooseFoot
//
// Created by Alexander McArdle on 2/6/17.
// Copyright © 2017 Alexander McArdle. All rights reserved.
//
import AsyncDisplayKit
class OverviewCellNode: ASCellNode {
let layoutExampleType: LayoutExampleNode.Type
fileprivate let titleNode = ASTextNode()
fileprivate let descriptionNode = ASTextNode()
init(layoutExampleType le: LayoutExampleNode.Type) {
layoutExampleType = le
super.init()
self.automaticallyManagesSubnodes = true
titleNode.attributedText = NSAttributedString.attributedString(string: layoutExampleType.title(), fontSize: 16, color: .black)
descriptionNode.attributedText = NSAttributedString.attributedString(string: layoutExampleType.descriptionTitle(), fontSize: 12, color: .lightGray)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let verticalStackSpec = ASStackLayoutSpec.vertical()
verticalStackSpec.alignItems = .start
verticalStackSpec.spacing = 5.0
verticalStackSpec.children = [titleNode, descriptionNode]
return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 10), child: verticalStackSpec)
}
}
| gpl-3.0 | 1be2078640f2d2a962ff14e7fd27bd86 | 34.162162 | 155 | 0.707148 | 5.023166 | false | false | false | false |
brandonlee503/Atmosphere | Weather App/ForecastService.swift | 2 | 1631 | //
// ForecastService.swift
// Weather App
//
// Created by Brandon Lee on 7/13/15.
// Copyright (c) 2015 Brandon Lee. All rights reserved.
//
import Foundation
struct ForecastService {
// Struct properties
let forecastAPIKey: String
let forecastBaseURL: NSURL?
// Initilize struct properties
init(APIKey: String) {
forecastAPIKey = APIKey
forecastBaseURL = NSURL(string: "https://api.forecast.io/forecast/\(forecastAPIKey)/")
}
// Input location and a closure and return the forecast
// Use closure here since we'll be calling the download JSON method of NetworkOperation
func getForecast(lat: Double, long: Double, completion: (Forecast? -> Void)) {
// Safely initilize forecast URL
if let forecastURL = NSURL(string: "\(lat),\(long)", relativeToURL: forecastBaseURL) {
let networkOperation = NetworkOperation(url: forecastURL)
// Trailing closure
networkOperation.downloadJSONFromURL {
(let JSONDictionary) in
let forecast = Forecast(weatherDictionary: JSONDictionary)
// This moves it up to the completion handler in parameter so that if we call the getForecast() method,
// and complete the completion handler and access the currentWeather variable, we get access to the
// populated instance that we're passing up.
completion(forecast)
}
} else {
println("Could not construct a valid URL")
}
}
} | mit | bcb772234a8e868d5626fca8e9150e81 | 33.723404 | 119 | 0.613121 | 5.210863 | false | false | false | false |
hyperoslo/Tabby | Demo/TabbyDemo/TabbyDemo/Controllers/SecondController.swift | 1 | 905 | import UIKit
class SecondController: GeneralController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
title = "Donut".uppercased()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .brown
titleLabel.text = "Who doesn't like some donuts?"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let controller = UIAlertController(title: "Alert", message: "This is an alert", preferredStyle: .alert)
let action = UIAlertAction(title: "Action", style: .default, handler: nil)
controller.addAction(action)
present(controller, animated: true, completion: nil)
}
}
| mit | 3c7bb6e37d89ba33711f63d432a91a0c | 27.28125 | 107 | 0.710497 | 4.436275 | false | false | false | false |
kdawgwilk/vapor | Sources/Vapor/JSON/JSONFile.swift | 1 | 417 | struct JSONFile {
let name: String
let json: JSON
private static let suffix = ".json"
init(name: String, json: JSON) {
if
let nameSequence = name.characters.split(separator: ".").first
where name.hasSuffix(JSONFile.suffix)
{
self.name = String(nameSequence)
} else {
self.name = name
}
self.json = json
}
}
| mit | a22d9ea606dfbae14b5e1a3ad4461696 | 22.166667 | 74 | 0.532374 | 4.255102 | false | false | false | false |
vonox7/Kotlift | test-dest/24_types.swift | 2 | 798 | func main(args: [String]) {
// Defined types
let double: Double = 64.64
let float: Double = 32.32
let long: Int64 = 64
let int: Int32 = 32
let short: Int16 = 16
let byte: Int8 = 8
// Auto types
let double2 = 64.64
let float2 = 32.32
let long2 = 64
let int2 = 32
if double != double2 {
print("double error")
}
if float != float2 {
print("float error")
}
if long != long2 {
print("long error")
}
if int != int2 {
print("int error")
}
let sum = double + float + long + int + short + byte + double2 + float2 + long2 + int2
if abs(sum - 409.9199993896484) > 0.01 {
print("sum error")
}
if max(100, long) != 100 {
print("max error")
}
if min(32, float) != 32 {
print("min error")
}
print("finished")
}
main([])
| apache-2.0 | 329f00f333c8950356d7d17652278e31 | 15.978723 | 88 | 0.562657 | 3.081081 | false | false | false | false |
XYXiaoYuan/Meilishuo | Meilishuo/Classes/Other/Protocol/Thanable.swift | 1 | 1141 | //
// Thanable.swift
// Meilishuo
//
// Created by 袁小荣 on 2017/5/15.
// Copyright © 2017年 袁小荣. All rights reserved.
//
import Foundation
/// Then语法糖
public protocol Then {}
extension Then where Self: Any {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
*/
/// Then语法糖
public func then( block: (inout Self) -> Void) -> Self {
var copy = self
block(©)
return copy
}
}
extension Then where Self: AnyObject {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
*/
/// Then语法糖
public func then( block: (Self) -> Void) -> Self {
block(self)
return self
}
}
extension NSObject: Then {}
| mit | 843bcff3420b45a2ba8b37ddf7028669 | 18.438596 | 80 | 0.555054 | 3.94306 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/Subscription/SubscriptionUnreadRequest.swift | 1 | 794 | //
// SubscriptionUnreadRequest.swift
// Rocket.Chat
//
// Created by Filipe Alvarenga on 26/07/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
final class SubscriptionUnreadRequest: APIRequest {
typealias APIResourceType = SubscriptionUnreadResource
let requiredVersion = Version(0, 65, 0)
let method: HTTPMethod = .post
let path = "/api/v1/subscriptions.unread"
let rid: String
init(rid: String) {
self.rid = rid
}
func body() -> Data? {
let body = JSON([
"roomId": rid
])
return body.rawString()?.data(using: .utf8)
}
}
final class SubscriptionUnreadResource: APIResource {
var success: Bool? {
return raw?["success"].boolValue
}
}
| mit | 226b87d4d7ec74a87d01cc73f4469b1f | 19.333333 | 58 | 0.639344 | 4.025381 | false | false | false | false |
MyBar/MyBarMusic | MyBarMusic/MyBarMusic/Classes/Utility/Inherit/GUI/RotationAnimationImageView.swift | 1 | 1614 | //
// RotationAnimationImageView.swift
// MyBarMusic
//
// Created by lijingui2010 on 2017/8/19.
// Copyright © 2017年 MyBar. All rights reserved.
//
import UIKit
class RotationAnimationImageView: UIImageView {
var rotationAngle: CGFloat = 0
private var timer: Timer?
func initAnimation(with rotationAngle: CGFloat = 0.0) {
self.rotationAngle = rotationAngle
self.transform = CGAffineTransform(rotationAngle: rotationAngle)
}
func resumeAnimation() {
self.addTimer()
}
func pauseAnimation() {
self.removeTimer()
}
func removeAnimation() {
self.rotationAngle = 0.0
self.removeTimer()
self.transform = CGAffineTransform.identity
}
private func addTimer() {
guard self.timer == nil else {
return
}
self.timer = Timer.scheduledTimer(timeInterval: 1.0 / 20.0, target: self, selector: #selector(self.refreshUI), userInfo: nil, repeats: true)
RunLoop.main.add(self.timer!, forMode: RunLoopMode.commonModes)
}
private func removeTimer() {
guard self.timer != nil else {
return
}
self.timer?.invalidate()
self.timer = nil
}
func refreshUI() {
rotationAngle += 0.01
if rotationAngle >= CGFloat(Float.pi * 2.0) {
rotationAngle = 0
}
let transform = CGAffineTransform(rotationAngle: CGFloat(rotationAngle))
self.transform = transform
}
}
| mit | b6ff92172e8804c054ed8866e7548225 | 21.690141 | 148 | 0.577281 | 4.867069 | false | false | false | false |
louisdh/lioness | Sources/Lioness/Bytecode/BytecodeInstructionType.swift | 1 | 2541 | //
// BytecodeInstructionType.swift
// Lioness
//
// Created by Louis D'hauwe on 09/10/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
/// Scorpion Bytecode Instruction Type
///
/// Enum cases are lower camel case (per Swift guideline)
///
/// Instruction command descriptions are lower snake case
public enum BytecodeInstructionType: UInt8, CustomStringConvertible {
// TODO: add documentation with stack before/after execution
case pushConst = 0
case add = 1
case sub = 2
case mul = 3
case div = 4
case pow = 5
case and = 6
case or = 7
case not = 8
/// Equal
case eq = 9
/// Not equals
case neq = 10
case ifTrue = 11
case ifFalse = 12
/// Compare less than or equal
case cmple = 13
/// Compare less than
case cmplt = 14
case goto = 15
case registerStore = 16
case registerUpdate = 17
case registerClear = 18
case registerLoad = 19
case invokeVirtual = 20
case exitVirtual = 21
case pop = 22
case skipPast = 23
case structInit = 24
case structSet = 25
case structUpdate = 26
case structGet = 27
case virtualHeader = 28
case privateVirtualHeader = 29
case virtualEnd = 30
case privateVirtualEnd = 31
public var opCode: UInt8 {
return self.rawValue
}
public var description: String {
switch self {
case .pushConst:
return "push_const"
case .add:
return "add"
case .sub:
return "sub"
case .mul:
return "mul"
case .div:
return "div"
case .pow:
return "pow"
case .and:
return "and"
case .or:
return "or"
case .not:
return "not"
case .eq:
return "eq"
case .neq:
return "neq"
case .ifTrue:
return "if_true"
case .ifFalse:
return "if_false"
case .cmple:
return "cmple"
case .cmplt:
return "cmplt"
case .goto:
return "goto"
case .registerStore:
return "reg_store"
case .registerUpdate:
return "reg_update"
case .registerClear:
return "reg_clear"
case .registerLoad:
return "reg_load"
case .invokeVirtual:
return "invoke_virt"
case .exitVirtual:
return "exit_virt"
case .pop:
return "pop"
case .skipPast:
return "skip_past"
case .structInit:
return "struct_init"
case .structSet:
return "struct_set"
case .structUpdate:
return "struct_update"
case .structGet:
return "struct_get"
case .virtualHeader:
return "virt_h"
case .privateVirtualHeader:
return "pvirt_h"
case .virtualEnd:
return "virt_e"
case .privateVirtualEnd:
return "pvirt_e"
}
}
}
| mit | b8ce790cdc1aa18529117fa72e45fe80 | 13.269663 | 69 | 0.657874 | 3.016627 | false | false | false | false |
sunflash/SwiftHTTPClient | HTTPClient/Classes/SchemeGenerator/SchemeBinding.swift | 1 | 14007 | //
// SchemeBinding.swift
// HTTPClient
//
// Created by Min Wu on 05/06/2017.
// Copyright © 2017 Min Wu. All rights reserved.
//
import Foundation
// MARK: - Generate OBJC Bindings
class SchemeBinding {
static func generateOBJCBindings(_ schemeInfo: SchemeInfo) -> String {
guard let objcType = schemeInfo.objcType else {
return "!! Objective-C objecttype was not specified."
}
var bindings = SchemeUtility.generateImport(moduleNames: ["Foundation"])
// Generate binding info
let swiftObject = schemeInfo.swiftType.init()
let objcObject = objcType.init()
var objToSwiftBindingInfo = SchemeBindingInfo(fromObject: objcObject, toObject: swiftObject, toSwift: true, prefix: schemeInfo.prefix)
objToSwiftBindingInfo.typeInfo = schemeInfo.typeInfo
var swiftToObjcBindingInfo = SchemeBindingInfo(fromObject: swiftObject, toObject: objcObject, toSwift: false, prefix: schemeInfo.prefix)
swiftToObjcBindingInfo.typeInfo = schemeInfo.typeInfo
// Generate bindings
let objcToSwift = generateBinding(objToSwiftBindingInfo)
let swiftToObjc = generateBinding(swiftToObjcBindingInfo)
bindings += objcToSwift
bindings += swiftToObjc
return bindings
}
}
// MARK: - Generate Bindings
extension SchemeBinding {
fileprivate struct SchemeBindingInfo {
let fromObject: Mappable
let toObject: Mappable
let toSwift: Bool
let prefix: String
var typeInfo = SchemeTypeInfo()
init(fromObject: Mappable, toObject: Mappable, toSwift: Bool, prefix: String) {
self.fromObject = fromObject
self.toObject = toObject
self.toSwift = toSwift
self.prefix = prefix
}
}
fileprivate struct SchemeBindingValue {
let fromValue: Any
let toValue: Any
let toSwift: Bool
let prefix: String
var typeInfo = SchemeTypeInfo()
init(fromValue: Any, toValue: Any, toSwift: Bool, prefix: String) {
self.fromValue = fromValue
self.toValue = toValue
self.toSwift = toSwift
self.prefix = prefix
}
}
fileprivate struct TypeMatchResult {
let isTypeMatch: Bool
let coalescing: String
let fromOptional: Bool
let toOptional: Bool
let nestedObjectType: SchemeUtility.NestedObjectType
}
fileprivate struct NestedBindingResult {
var nestedObjectType: SchemeUtility.NestedObjectType = .nonNestedObject
var fromObjectType = ""
var toObjectType = ""
var nestedBinding = ""
}
}
extension SchemeBinding {
// swiftlint:disable identifier_name
fileprivate static func generateBinding(_ bindingInfo: SchemeBindingInfo) -> String {
// Extract object type info and values
let b = bindingInfo
let fromObjectArrayTypes = b.toSwift ? b.typeInfo.objcObjectArrayTypes : b.typeInfo.swiftObjectArrayTypes
let toObjectArrayTypes = b.toSwift ? b.typeInfo.swiftObjectArrayTypes : b.typeInfo.objcObjectArrayTypes
let fromObjectTypes = b.toSwift ? b.typeInfo.objcObjectTypes : b.typeInfo.swiftObjectTypes
let toObjectTypes = b.toSwift ? b.typeInfo.swiftObjectTypes : b.typeInfo.objcObjectTypes
let fromObjType = SchemeUtility.objectTypeDescription(mirror: Mirror(reflecting: b.fromObject))
let toObjType = SchemeUtility.objectTypeDescription(mirror: Mirror(reflecting: b.toObject))
let removePrefixType = removeSubStrings(fromObjType, [bindingInfo.prefix])
let fromObjInstance = lowerCaseFirstLetter(removePrefixType)
let fromObjValues = b.fromObject.propertyValuesRaw.sorted {$0.key < $1.key}
let toObjValues = b.toObject.propertyValuesRaw
var bindingExtension = ""
var subObjectBindingExtension = ""
// Generate extension
bindingExtension += "extension \(toObjType) {" + newLine(2)
bindingExtension += generateDocumentation(fromObjType: fromObjType, toObjType: toObjType, fromObjInstance: fromObjInstance, toSwift: b.toSwift)
bindingExtension += tab() + (b.toSwift ? "" : "convenience ") + "init(\(fromObjInstance): \(fromObjType)) {" + newLine(2)
if b.toSwift == false {bindingExtension += tab(2) + "self.init()" + newLine()}
// Generate type mapping
for (key, value) in fromObjValues {
let leftSide = "self.\(key)"
var rightSide = "!! NO MATCH"
// Check match property name, else continue and mark mapping with "!! NO MATCH"
var fromValue = value
guard var toValue = toObjValues[key] else {
bindingExtension += (tab(2) + leftSide + " = " + rightSide + newLine())
continue
}
// Do property type match check
let match = typeMatch(key: key, fromValue: fromValue, toValue: toValue)
guard match.isTypeMatch == true else {
rightSide = "!! Type DOES NOT MATCH"
bindingExtension += (tab(2) + leftSide + " = " + rightSide + newLine())
continue
}
// Generate object or object array if they are optional. (need real object that is not nil to do object mapping)
switch match.nestedObjectType {
case .nestedObjectArray:
fromValue = [fromObjectArrayTypes?[key]?.init()]
toValue = [toObjectArrayTypes?[key]?.init()]
case .nestedObject:
fromValue = fromObjectTypes?[key]?.init() ?? fromValue
toValue = toObjectTypes?[key]?.init() ?? toValue
default:
break
}
// Generate bindings for property and object, object array
var schemeBindingValue = SchemeBindingValue(fromValue: fromValue, toValue: toValue, toSwift: b.toSwift, prefix: b.prefix)
schemeBindingValue.typeInfo = bindingInfo.typeInfo
let result = generateNestedBinding(schemeBindingValue)
switch result.nestedObjectType {
case .nestedObject:
let nestedFromObjectInstance = lowerCaseFirstLetter(result.fromObjectType)
rightSide = "\(result.toObjectType)(\(nestedFromObjectInstance): \(fromObjInstance).\(key) \(match.coalescing))"
subObjectBindingExtension += result.nestedBinding
case .nestedObjectArray:
let optional = (match.fromOptional) ? "?" : ""
let nestedFromObjectInstance = lowerCaseFirstLetter(result.fromObjectType)
let map = "\(result.toObjectType)(\(nestedFromObjectInstance): $0)"
rightSide = "\(fromObjInstance).\(key)" + optional + ".flatMap" + " {\(map)}" + match.coalescing
subObjectBindingExtension += result.nestedBinding
case .nonNestedObject:
rightSide = "\(fromObjInstance).\(key)" + match.coalescing
}
bindingExtension += (tab(2) + leftSide + " = " + rightSide + newLine())
}
bindingExtension += tab() + "}" + newLine()
bindingExtension += "}" + newLine(2)
bindingExtension += subObjectBindingExtension
return bindingExtension
}
fileprivate static func generateNestedBinding(_ bindingValue: SchemeBindingValue) -> NestedBindingResult {
// Check for nested object and object array
let fromValue = bindingValue.fromValue
let toValue = bindingValue.toValue
var nestedBindingResult = NestedBindingResult()
guard let fromMappable = (fromValue as? Mappable) ?? (fromValue as? [Mappable])?.first else {
return nestedBindingResult
}
guard let toMappable = (toValue as? Mappable) ?? (toValue as? [Mappable])?.first else {
return nestedBindingResult
}
// Generate nested binding
let fromObjectMirror = Mirror(reflecting: fromMappable)
let fromObjectType = SchemeUtility.objectTypeDescription(mirror: fromObjectMirror)
nestedBindingResult.fromObjectType = fromObjectType
let toObjectMirror = Mirror(reflecting: toMappable)
let toObjectType = SchemeUtility.objectTypeDescription(mirror: toObjectMirror)
nestedBindingResult.toObjectType = toObjectType
let result = SchemeUtility.processDataInNestedStructure(type: Mappable.self, value: fromValue) { mappable in
var bindingInfo = SchemeBindingInfo(fromObject: mappable, toObject: toMappable, toSwift: bindingValue.toSwift, prefix: bindingValue.prefix)
bindingInfo.typeInfo = bindingValue.typeInfo
return generateBinding(bindingInfo)
}
nestedBindingResult.nestedObjectType = result.nestedObjectType
var nestedBinding = ""
(result.data as? [String])?.forEach {nestedBinding += $0}
nestedBindingResult.nestedBinding = nestedBinding
return nestedBindingResult
}
// MARK: - Utility Help Function
fileprivate static func isNonNestedType(fromType: Any.Type, toType: Any.Type) -> (isTypeMatch: Bool, coalescing: String) {
var coalescing = ""
// Do type match check for swift data types that is identical
var nonNestedTypes = ["Int", "Int64", "Float", "Double", "Bool", "String"]
nonNestedTypes += ["Optional<Int>", "Optional<Int64>", "Optional<Float>", "Optional<Double>", "Optional<Bool>", "Optional<String>"]
nonNestedTypes += ["Date", "Optional<Date>"]
if fromType == toType && (nonNestedTypes.contains {$0 == "\(toType)"}) {
return (true, coalescing)
}
// Do type match check for swift data types that is compatiable (non-option and optional type)
let matchOptionalType: (Any.Type, Any.Type, String) -> Bool = { type, optionalType, defaultValue in
if toType == type && fromType == optionalType {
coalescing = " ?? " + defaultValue
return true
} else if toType == optionalType && fromType == type {
return true
} else {
return false
}
}
if matchOptionalType(Int.self, Optional<Int>.self, "0") == true ||
matchOptionalType(Int64.self, Optional<Int64>.self, "0") == true ||
matchOptionalType(Float.self, Optional<Float>.self, "0") == true ||
matchOptionalType(Double.self, Optional<Double>.self, "0") == true ||
matchOptionalType(Bool.self, Optional<Bool>.self, "false") == true ||
matchOptionalType(String.self, Optional<String>.self, "\"\"") == true {
return (true, coalescing)
}
return (false, coalescing)
}
fileprivate static func typeMatch(key: String, fromValue: Any, toValue: Any) -> TypeMatchResult {
let fromType = type(of: fromValue)
let toType = type(of: toValue)
let fromOptional = "\(fromType)".contains("Optional")
var coalescing = ""
// Do type match check for swift data types
let nonNestedTypeMatchResult = isNonNestedType(fromType: fromType, toType: toType)
var toOptional = nonNestedTypeMatchResult.coalescing.isEmpty == false
if nonNestedTypeMatchResult.isTypeMatch == true {
return TypeMatchResult(isTypeMatch: true,
coalescing: nonNestedTypeMatchResult.coalescing,
fromOptional: fromOptional,
toOptional: toOptional,
nestedObjectType: .nonNestedObject)
}
// Do type match check for object
let containArray = "\(toType)".contains("Array")
toOptional = "\(toType)".contains("Optional")
var fromRawType = removeSubStrings("\(fromType)", ["Optional", "<", ">"])
var toRawType = removeSubStrings("\(toType)", ["Optional", "<", ">"])
var fromCompareType = removeSubStrings("\(fromRawType)", ["OBJC"])
var toCompareType = removeSubStrings("\(toRawType)", ["OBJC"])
if containArray == false && fromCompareType == toCompareType {
coalescing = toOptional ? "" : "?? \(fromRawType)()"
return TypeMatchResult(isTypeMatch: true, coalescing: coalescing, fromOptional: fromOptional, toOptional: toOptional, nestedObjectType: .nestedObject)
}
// Do type match check for object array
fromRawType = removeSubStrings("\(fromRawType)", ["Array"])
toRawType = removeSubStrings("\(toRawType)", ["Array"])
fromCompareType = removeSubStrings("\(fromCompareType)", ["Array"])
toCompareType = removeSubStrings("\(toCompareType)", ["Array"])
if containArray == true && fromCompareType == toCompareType {
coalescing = toOptional ? "" : " ?? [\(toRawType)]()"
return TypeMatchResult(isTypeMatch: true, coalescing: coalescing, fromOptional: fromOptional, toOptional: toOptional, nestedObjectType: .nestedObjectArray)
}
return TypeMatchResult(isTypeMatch: false, coalescing: "", fromOptional: false, toOptional: false, nestedObjectType: .nonNestedObject)
}
fileprivate static func generateDocumentation(fromObjType: String, toObjType: String, fromObjInstance: String, toSwift: Bool) -> String {
let fromObjDescription = toSwift ? "objective-c compatible `\(fromObjType)` class object" : "`\(fromObjType)` struct"
let toObjDescription = toSwift ? "`\(toObjType)` struct" : "objective-c compatible `\(toObjType)` class object"
var documentation = tab() + "/// Init \(toObjDescription) from \(fromObjDescription)" + newLine()
documentation += tab() + "///" + newLine()
documentation += tab() + "/// - Parameter \(fromObjInstance): \(fromObjDescription)" + newLine()
return documentation
}
}
| mit | e8e9cda39447731820d4ca9dd45815b4 | 40.194118 | 167 | 0.635442 | 4.933427 | false | false | false | false |
zhaoxiangyulove/Zachary-s-Programs | Weather/Weather/libs/ElasticTransition/EdgePanTransition.swift | 2 | 8696 | /*
The MIT License (MIT)
Copyright (c) 2015 Luke Zhao <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
@available(iOS 7.0, *)
public class EdgePanTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerInteractiveTransitioning, UIViewControllerTransitioningDelegate, UINavigationControllerDelegate{
public var panThreshold:CGFloat = 0.2
public var edge:Edge = .Right
// private
var transitioning = false
var presenting = true
var interactive = false
var navigation = false
var transitionContext:UIViewControllerContextTransitioning!
var container:UIView!
var size:CGSize{
return container.bounds.size
}
var frontView:UIView{
return frontViewController.view
}
var backView:UIView{
return backViewController.view
}
var frontViewController: UIViewController{
return presenting ? toViewController : fromViewController
}
var backViewController: UIViewController{
return !presenting ? toViewController : fromViewController
}
var toView:UIView{
return toViewController.view
}
var fromView:UIView{
return fromViewController.view
}
var toViewController:UIViewController{
return transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
}
var fromViewController:UIViewController{
return transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
}
var currentPanGR: UIPanGestureRecognizer?
var translation:CGPoint = CGPointZero
var dragPoint:CGPoint = CGPointZero
func update(){}
func setup(){
transitioning = true
container.addSubview(backView)
container.addSubview(frontView)
}
func clean(finished: Bool){
if !navigation {
// bug: http://openradar.appspot.com/radar?id=5320103646199808
UIApplication.sharedApplication().keyWindow!.addSubview(finished ? toView : fromView)
}
if presenting && !interactive{
backViewController.viewWillAppear(true)
}
if(!presenting && finished || presenting && !finished){
frontView.removeFromSuperview()
backView.layer.transform = CATransform3DIdentity
// backView.frame = container.bounds
backViewController.viewDidAppear(true)
}
currentPanGR = nil
interactive = false
transitioning = false
navigation = false
transitionContext.completeTransition(finished)
}
func startInteractivePresent(fromViewController fromVC:UIViewController, toViewController toVC:UIViewController?, identifier:String?, pan:UIPanGestureRecognizer, presenting:Bool, completion:(() -> Void)? = nil){
interactive = true
currentPanGR = pan
if presenting{
if let identifier = identifier{
fromVC.performSegueWithIdentifier(identifier, sender: self)
}else if let toVC = toVC{
fromVC.presentViewController(toVC, animated: true, completion: nil)
}
}else{
if navigation{
fromVC.navigationController?.popViewControllerAnimated(true)
}else{
fromVC.dismissViewControllerAnimated(true, completion: completion)
}
}
translation = pan.translationInView(pan.view!)
dragPoint = pan.locationInView(pan.view!)
}
public func updateInteractiveTransition(gestureRecognizer pan:UIPanGestureRecognizer) -> Bool?{
if !transitioning{
return nil
}
if pan.state == .Changed{
translation = pan.translationInView(pan.view!)
dragPoint = pan.locationInView(pan.view!)
update()
return nil
}else{
return endInteractiveTransition()
}
}
public func startInteractiveTransition(fromViewController:UIViewController, segueIdentifier identifier:String, gestureRecognizer pan:UIPanGestureRecognizer){
self.startInteractivePresent(fromViewController:fromViewController, toViewController:nil, identifier:identifier, pan: pan, presenting: true)
}
public func startInteractiveTransition(fromViewController:UIViewController, toViewController:UIViewController, gestureRecognizer pan:UIPanGestureRecognizer){
self.startInteractivePresent(fromViewController:fromViewController, toViewController:toViewController, identifier:nil, pan: pan, presenting: true)
}
public func dissmissInteractiveTransition(viewController:UIViewController, gestureRecognizer pan:UIPanGestureRecognizer, completion:(() -> Void)?){
self.startInteractivePresent(fromViewController:viewController, toViewController:nil, identifier:nil, pan: pan, presenting: false, completion: completion)
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
self.container = transitionContext.containerView()
setup()
}
public func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning){
animateTransition(transitionContext)
}
func cancelInteractiveTransition(){
self.transitionContext.cancelInteractiveTransition()
}
func finishInteractiveTransition(){
if !presenting{
backViewController.viewWillAppear(true)
}
self.transitionContext.finishInteractiveTransition()
}
func endInteractiveTransition() -> Bool{
let finished:Bool
if let pan = currentPanGR{
let translation = pan.translationInView(pan.view!)
var progress:CGFloat
switch edge{
case .Left:
progress = translation.x / pan.view!.frame.width
case .Right:
progress = translation.x / pan.view!.frame.width * -1
case .Bottom:
progress = translation.y / pan.view!.frame.height * -1
case .Top:
progress = translation.y / pan.view!.frame.height
}
progress = presenting ? progress : -progress
if(progress > panThreshold){
finished = true
} else {
finished = false
}
}else{
finished = true
}
if finished{
finishInteractiveTransition()
}else{
cancelInteractiveTransition()
}
return finished
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.7
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
self.presenting = true
return self.interactive ? self : nil
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
self.presenting = false
return self.interactive ? self : nil
}
public func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return self.interactive ? self : nil
}
public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
navigation = true
presenting = operation == .Push
return self
}
}
| apache-2.0 | 49e00047c3b323326694025e60ff37f4 | 35.233333 | 286 | 0.75552 | 5.732367 | false | false | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/ViewControllers/ChatViewController/ChatViewController/Cells/Operator/WMOperatorMessageTableViewCell/WMOperatorMessageCell.swift | 1 | 2848 | //
// String.swift
// WMMessageTableViewCell.swift
// Webim.Ru
//
// Created by User on 25.08.2020.
// Copyright © 2020 _webim_. All rights reserved.
// Created by EVGENII Loshchenko on 01.03.2021.
// Copyright © 2021 _webim_. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
import WebimClientLibrary
class WMOperatorMessageCell: WMMessageTableCell {
@IBOutlet var messageTextView: UITextView!
override func setMessage(message: Message, tableView: UITableView) {
super.setMessage(message: message, tableView: tableView)
let checkLink = self.messageTextView.setTextWithReferences(message.getText(), alignment: .left)
if !cellMessageWasInited {
cellMessageWasInited = true
for recognizer in messageTextView.gestureRecognizers ?? [] {
if recognizer.isKind(of: UITapGestureRecognizer.self) && !checkLink {
recognizer.delegate = self
}
if recognizer.isKind(of: UIPanGestureRecognizer.self) {
recognizer.isEnabled = false
}
}
let longPressPopupGestureRecognizer = UILongPressGestureRecognizer(
target: self,
action: #selector(longPressAction)
)
longPressPopupGestureRecognizer.minimumPressDuration = 0.2
longPressPopupGestureRecognizer.cancelsTouchesInView = false
self.messageTextView.addGestureRecognizer(longPressPopupGestureRecognizer)
}
}
override func initialSetup() -> Bool {
let setup = super.initialSetup()
if setup {
self.sharpCorner(view: messageView, visitor: false)
}
return setup
}
}
| mit | 8c41f147217baa4cdf2ae30def8b519a | 40.246377 | 103 | 0.684118 | 4.915371 | false | false | false | false |
FoodForTech/Handy-Man | HandyMan/HandyMan/HandyManCore/Spring/AutoTextView.swift | 1 | 598 | //
// AutoTextView.swift
// SpringApp
//
// Created by Meng To on 2015-03-27.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
class AutoTextView: UITextView {
override var intrinsicContentSize : CGSize {
var size = self.sizeThatFits(CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
size.width = self.frame.size.width
if text.length == 0 {
size.height = 0
}
contentInset = UIEdgeInsetsMake(-4, -4, -4, -4)
layoutIfNeeded()
return size
}
}
| mit | 5fd741d6e164a7a4bf3fa7a3de7546ea | 22 | 115 | 0.598662 | 4.068027 | false | false | false | false |
MingLoan/SimpleTransition | Example/Tests/Tests.swift | 2 | 1183 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SimpleTransition
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 7b8adb48155d743b9e2e6af01a6b3421 | 22.54 | 63 | 0.367035 | 5.5 | false | false | false | false |
hwsyy/ruby-china-ios | RubyChina/Views/LoadingView.swift | 5 | 683 | //
// LoadingView.swift
// RubyChina
//
// Created by Jianqiu Xiao on 5/22/15.
// Copyright (c) 2015 Jianqiu Xiao. All rights reserved.
//
import UIKit
class LoadingView: UIActivityIndicatorView {
var refreshing: Bool {
get { return !hidden }
}
override func didMoveToSuperview() {
if superview == nil { return }
activityIndicatorViewStyle = .Gray
autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin
center = superview!.center
hidesWhenStopped = true
}
func show() {
startAnimating()
}
func hide() {
stopAnimating()
}
}
| mit | 620206e11fdc1dee76fcbdcc4207a51d | 19.088235 | 114 | 0.629575 | 4.878571 | false | false | false | false |
SheepYo/SheepYo | iOS/Sheep/ViewController.swift | 1 | 3683 | //
// ViewController.swift
// Sheep
//
// Created by mono on 7/24/14.
// Copyright (c) 2014 Sheep. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var tableView: UITableView!
var user: PFUser?
var users: Array<PFUser>?
override func viewDidLoad() {
super.viewDidLoad()
if Account.MR_countOfEntities() > 0 {
let account = Account.MR_findFirst() as Account
nameTextField.text = account.username
nameTextField.enabled = false
registerButton.enabled = false
PFUser.logInWithUsernameInBackground(account.username, password: "password", block: {user, error in
self.user = user
self.loadUsers()
})
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func loadUsers() {
let query = PFUser.query()
users = query.findObjects() as Array<PFUser>?
println(users)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerButtonDidTap(sender: UIButton) {
let user = PFUser()
let username = nameTextField.text
user.username = username
user.password = "password"
user.signUpInBackgroundWithBlock { succeeded, error in
if error {
println(error)
return;
}
let account = Account.MR_createEntity() as Account
account.username = username
account.save()
self.nameTextField.enabled = false
self.registerButton.enabled = false
let installation = PFInstallation.currentInstallation()
installation["user"] = PFUser.currentUser()
installation.saveInBackground()
self.loadUsers()
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
let count = users?.count
return count ? count! : 0
}
func numberOfSectionsInTableView(tableView: UITableView!) -> Int
{
return 1
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell
let user = users![indexPath.row]
cell.textLabel.text = user.username
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println(indexPath)
let user = users![indexPath.row]
let userQuery = PFUser.query()
userQuery.whereKey("username", equalTo: user.username)
let debug = userQuery.findObjects() as Array<PFUser>?
println(debug)
let pushQuery = PFInstallation.query()
pushQuery.whereKey("user", matchesQuery: userQuery)
let push = PFPush()
push.setQuery(pushQuery)
let data = ["alert": "( ´・‿・`)", "sound": "sheep.caf"]
// push.setMessage("( ´・‿・`)")
push.setData(data)
push.sendPushInBackground()
}
}
| mit | 5a7bc9a2ada59b655adc903b0b503304 | 31.6875 | 118 | 0.607211 | 5.192908 | false | false | false | false |
kwkhaw/SwiftAnyPic | SwiftAnyPic/PAPActivityCell.swift | 1 | 11878 | import UIKit
import FormatterKit
// FIXME: redeclaration!!!! var timeFormatter: TTTTimeIntervalFormatter?
private let nameMaxWidth: CGFloat = 200.0
class PAPActivityCell: PAPBaseTextCell {
/*! Private view components */
var activityImageView: PAPProfileImageView?
var activityImageButton: UIButton?
/*! Flag to remove the right-hand side image if not necessary */
var hasActivityImage: Bool = false
// MARK:- NSObject
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
horizontalTextSpace = Int(PAPActivityCell.horizontalTextSpaceForInsetWidth(0))
if timeFormatter == nil {
timeFormatter = TTTTimeIntervalFormatter()
}
// Create subviews and set cell properties
self.opaque = true
self.selectionStyle = UITableViewCellSelectionStyle.None
self.accessoryType = UITableViewCellAccessoryType.None
self.hasActivityImage = false //No until one is set
self.activityImageView = PAPProfileImageView()
self.activityImageView!.backgroundColor = UIColor.clearColor()
self.activityImageView!.opaque = true
self.mainView!.addSubview(self.activityImageView!)
self.activityImageButton = UIButton(type: UIButtonType.Custom)
self.activityImageButton!.backgroundColor = UIColor.clearColor()
self.activityImageButton!.addTarget(self, action: #selector(PAPActivityCell.didTapActivityButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.mainView!.addSubview(self.activityImageButton!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIView
override func layoutSubviews() {
super.layoutSubviews()
// Layout the activity image and show it if it is not nil (no image for the follow activity).
// Note that the image view is still allocated and ready to be dispalyed since these cells
// will be reused for all types of activity.
self.activityImageView!.frame = CGRectMake(UIScreen.mainScreen().bounds.size.width - 46.0, 13.0, 33.0, 33.0)
self.activityImageButton!.frame = CGRectMake(UIScreen.mainScreen().bounds.size.width - 46.0, 13.0, 33.0, 33.0)
// Add activity image if one was set
if self.hasActivityImage {
self.activityImageView!.hidden = false
self.activityImageButton!.hidden = false
} else {
self.activityImageView!.hidden = true
self.activityImageButton!.hidden = true
}
// Change frame of the content text so it doesn't go through the right-hand side picture
let contentSize: CGSize = self.contentLabel!.text!.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width - 72.0 - 46.0, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin, // wordwrap?
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size
self.contentLabel!.frame = CGRectMake(46.0, 16.0, contentSize.width, contentSize.height)
// Layout the timestamp label given new vertical
let timeSize: CGSize = self.timeLabel!.text!.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width - 72.0 - 46.0, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)],
context: nil).size
self.timeLabel!.frame = CGRectMake(46.0, self.contentLabel!.frame.origin.y + self.contentLabel!.frame.size.height + 7.0, timeSize.width, timeSize.height)
}
// MARK:- PAPActivityCell
/*!Set the new state. This changes the background of the cell. */
func setIsNew(isNew: Bool) {
if isNew {
self.mainView!.backgroundColor = UIColor(red: 29.0/255.0, green: 29.0/255.0, blue: 29.0/255.0, alpha: 1.0)
} else {
self.mainView!.backgroundColor = UIColor.blackColor()
}
}
/*!Setter for the activity associated with this cell */
var activity: PFObject? {
didSet {
if (activity!.objectForKey(kPAPActivityTypeKey) as! String) == kPAPActivityTypeFollow || (activity!.objectForKey(kPAPActivityTypeKey) as! String) == kPAPActivityTypeJoined {
self.setActivityImageFile(nil)
} else {
self.setActivityImageFile((activity!.objectForKey(kPAPActivityPhotoKey) as! PFObject).objectForKey(kPAPPhotoThumbnailKey) as? PFFile)
}
let activityString: String = PAPActivityFeedViewController.stringForActivityType(activity!.objectForKey(kPAPActivityTypeKey) as! String)!
self.user = activity!.objectForKey(kPAPActivityFromUserKey) as? PFUser
// Set name button properties and avatar image
if PAPUtility.userHasProfilePictures(self.user!) {
self.avatarImageView!.setFile(self.user!.objectForKey(kPAPUserProfilePicSmallKey) as? PFFile)
} else {
self.avatarImageView!.setImage(PAPUtility.defaultProfilePicture()!)
}
var nameString: String = NSLocalizedString("Someone", comment: "Text when the user's name is unknown")
if self.user?.objectForKey(kPAPUserDisplayNameKey)?.length > 0 {
nameString = self.user!.objectForKey(kPAPUserDisplayNameKey) as! String
}
self.nameButton!.setTitle(nameString, forState: UIControlState.Normal)
self.nameButton!.setTitle(nameString, forState: UIControlState.Highlighted)
// If user is set after the contentText, we reset the content to include padding
if self.contentLabel!.text?.length > 0 {
self.setContentText(self.contentLabel!.text!)
}
if self.user != nil {
let nameSize: CGSize = self.nameButton!.titleLabel!.text!.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)],
context: nil).size
let paddedString: String = PAPBaseTextCell.padString(activityString, withFont: UIFont.systemFontOfSize(13.0), toWidth: nameSize.width)
self.contentLabel!.text = paddedString
} else { // Otherwise we ignore the padding and we'll add it after we set the user
self.contentLabel!.text = activityString
}
self.timeLabel!.text = timeFormatter!.stringForTimeIntervalFromDate(NSDate(), toDate: activity!.createdAt!)
self.setNeedsDisplay()
}
}
override var cellInsetWidth: CGFloat {
get {
return super.cellInsetWidth
}
set {
super.cellInsetWidth = newValue
horizontalTextSpace = Int(PAPActivityCell.horizontalTextSpaceForInsetWidth(newValue))
}
}
// Since we remove the compile-time check for the delegate conforming to the protocol
// in order to allow inheritance, we add run-time checks.
// FIXME: Do we need this in Swift???
// - (id<PAPActivityCellDelegate>)delegate {
// return (id<PAPActivityCellDelegate>)_delegate;
// }
//
// - (void)setDelegate:(id<PAPActivityCellDelegate>)delegate {
// if(_delegate != delegate) {
// _delegate = delegate;
// }
// }
// MARK:- ()
override class func horizontalTextSpaceForInsetWidth(insetWidth: CGFloat) -> CGFloat {
return (UIScreen.mainScreen().bounds.size.width - (insetWidth * 2.0)) - 72.0 - 46.0
}
override class func heightForCellWithName(name: String, contentString content: String) -> CGFloat {
return self.heightForCellWithName(name, contentString: content, cellInsetWidth: 0.0)
}
override class func heightForCellWithName(name: String, contentString content: String, cellInsetWidth cellInset: CGFloat) -> CGFloat {
let nameSize: CGSize = name.boundingRectWithSize(CGSizeMake(200.0, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)],
context: nil).size
let paddedString: String = PAPBaseTextCell.padString(content, withFont: UIFont.systemFontOfSize(13.0), toWidth: nameSize.width)
let horizontalTextSpace: CGFloat = PAPActivityCell.horizontalTextSpaceForInsetWidth(cellInset)
let contentSize: CGSize = paddedString.boundingRectWithSize(CGSizeMake(horizontalTextSpace, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin, // wordwrap?
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size
let singleLineHeight: CGFloat = "Test".boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size.height
// Calculate the added height necessary for multiline text. Ensure value is not below 0.
let multilineHeightAddition: CGFloat = contentSize.height - singleLineHeight
return 58.0 + fmax(0.0, multilineHeightAddition)
}
func setActivityImageFile(imageFile: PFFile?) {
if imageFile != nil {
self.activityImageView!.setFile(imageFile)
self.hasActivityImage = true
} else {
self.hasActivityImage = false
}
}
func didTapActivityButton(sender: AnyObject) {
if self.delegate?.respondsToSelector(#selector(PAPActivityCellDelegate.cell(_:didTapActivityButton:))) != nil {
(self.delegate! as! PAPActivityCellDelegate).cell(self, didTapActivityButton: self.activity!)
}
}
}
@objc protocol PAPActivityCellDelegate: PAPBaseTextCellDelegate {
/*!
Sent to the delegate when the activity button is tapped
@param activity the PFObject of the activity that was tapped
*/
func cell(cellView: PAPActivityCell, didTapActivityButton activity: PFObject)
}
| cc0-1.0 | e9e0d3821511d557b4856df73bfff021 | 51.557522 | 202 | 0.60229 | 5.488909 | false | false | false | false |
Bartlebys/Bartleby | Bartleby.xOS/_generated/operations/ReadBoxesByIds.swift | 1 | 8970 |
//
// ReadBoxesByIds.swift
// Bartleby
//
// THIS FILE AS BEEN GENERATED BY BARTLEBYFLEXIONS for [Benoit Pereira da Silva] (https://pereira-da-silva.com/contact)
// DO NOT MODIFY THIS FILE YOUR MODIFICATIONS WOULD BE ERASED ON NEXT GENERATION!
//
// Copyright (c) 2016 [Bartleby's org] (https://bartlebys.org) All rights reserved.
//
import Foundation
#if !USE_EMBEDDED_MODULES
import Alamofire
#endif
@objc public class ReadBoxesByIdsParameters : ManagedModel {
// Universal type support
override open class func typeName() -> String {
return "ReadBoxesByIdsParameters"
}
//
public var ids:[String]?
//
public var result_fields:[String]?
// the sort (MONGO DB)
public var sort:[String:Int] = [String:Int]()
required public init(){
super.init()
}
// MARK: - Exposed (Bartleby's KVC like generative implementation)
/// Return all the exposed instance variables keys. (Exposed == public and modifiable).
override open var exposedKeys:[String] {
var exposed=super.exposedKeys
exposed.append(contentsOf:["ids","result_fields","sort"])
return exposed
}
/// Set the value of the given key
///
/// - parameter value: the value
/// - parameter key: the key
///
/// - throws: throws an Exception when the key is not exposed
override open func setExposedValue(_ value:Any?, forKey key: String) throws {
switch key {
case "ids":
if let casted=value as? [String]{
self.ids=casted
}
case "result_fields":
if let casted=value as? [String]{
self.result_fields=casted
}
case "sort":
if let casted=value as? [String:Int]{
self.sort=casted
}
default:
return try super.setExposedValue(value, forKey: key)
}
}
/// Returns the value of an exposed key.
///
/// - parameter key: the key
///
/// - throws: throws Exception when the key is not exposed
///
/// - returns: returns the value
override open func getExposedValueForKey(_ key:String) throws -> Any?{
switch key {
case "ids":
return self.ids
case "result_fields":
return self.result_fields
case "sort":
return self.sort
default:
return try super.getExposedValueForKey(key)
}
}
// MARK: - Codable
public enum CodingKeys: String,CodingKey{
case ids
case result_fields
case sort
}
required public init(from decoder: Decoder) throws{
try super.init(from: decoder)
try self.quietThrowingChanges {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.ids = try values.decodeIfPresent([String].self,forKey:.ids)
self.result_fields = try values.decodeIfPresent([String].self,forKey:.result_fields)
self.sort = try values.decode([String:Int].self,forKey:.sort)
}
}
override open func encode(to encoder: Encoder) throws {
try super.encode(to:encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.ids,forKey:.ids)
try container.encodeIfPresent(self.result_fields,forKey:.result_fields)
try container.encode(self.sort,forKey:.sort)
}
}
@objc(ReadBoxesByIds) open class ReadBoxesByIds : ManagedModel{
// Universal type support
override open class func typeName() -> String {
return "ReadBoxesByIds"
}
public static func execute(from documentUID:String,
parameters:ReadBoxesByIdsParameters,
sucessHandler success:@escaping(_ boxes:[Box])->(),
failureHandler failure:@escaping(_ context:HTTPContext)->()){
if let document = Bartleby.sharedInstance.getDocumentByUID(documentUID) {
let pathURL=document.baseURL.appendingPathComponent("boxes")
let dictionary:[String:Any]? = parameters.dictionaryRepresentation()
let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:document.UID,withActionName:"ReadBoxesByIds" ,forMethod:"GET", and: pathURL)
do {
let r=try URLEncoding().encode(urlRequest,with:dictionary)
request(r).responseData(completionHandler: { (response) in
let request=response.request
let result=response.result
let timeline=response.timeline
let statusCode=response.response?.statusCode ?? 0
let context = HTTPContext( code: 3862038994,
caller: "ReadBoxesByIds.execute",
relatedURL:request?.url,
httpStatusCode: statusCode)
if let request=request{
context.request=HTTPRequest(urlRequest: request)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
context.responseString=utf8Text
}
let metrics=Metrics()
metrics.httpContext=context
metrics.operationName="ReadBoxesByIds"
metrics.latency=timeline.latency
metrics.requestDuration=timeline.requestDuration
metrics.serializationDuration=timeline.serializationDuration
metrics.totalDuration=timeline.totalDuration
document.report(metrics)
// React according to the situation
var reactions = Array<Reaction> ()
if result.isFailure {
let failureReaction = Reaction.dispatchAdaptiveMessage(
context: context,
title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"),
body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))",
transmit:{ (selectedIndex) -> () in
})
reactions.append(failureReaction)
failure(context)
}else{
if 200...299 ~= statusCode {
do{
if let data = response.data{
let instance = try JSON.decoder.decode([Box].self,from:data)
success(instance)
}else{
throw BartlebyOperationError.dataNotFound
}
}catch{
let failureReaction = Reaction.dispatchAdaptiveMessage(
context: context,
title:"\(error)",
body: "\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))",
transmit: { (selectedIndex) -> () in
})
reactions.append(failureReaction)
failure(context)
}
}else{
// Bartlby does not currenlty discriminate status codes 100 & 101
// and treats any status code >= 300 the same way
// because we consider that failures differentiations could be done by the caller.
let failureReaction = Reaction.dispatchAdaptiveMessage(
context: context,
title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"),
body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))",
transmit:{ (selectedIndex) -> () in
})
reactions.append(failureReaction)
failure(context)
}
}
//Let s react according to the context.
document.perform(reactions, forContext: context)
})
}catch{
let context = HTTPContext( code:2 ,
caller: "ReadBoxesByIds.execute",
relatedURL:nil,
httpStatusCode:500)
failure(context)
}
}else{
let context = HTTPContext( code: 1,
caller: "ReadBoxesByIds.execute",
relatedURL:nil,
httpStatusCode: 417)
failure(context)
}
}
}
| apache-2.0 | e8331ca957403acdb92a403ed43080d4 | 38.170306 | 150 | 0.53757 | 5.105293 | false | false | false | false |
khizkhiz/swift | test/Constraints/associated_self_types.swift | 1 | 789 | // RUN: %target-parse-verify-swift
protocol P : Collection {
init()
}
postfix operator ~>> {}
postfix func ~>> <_Self : Sequence, A : P where _Self.Iterator.Element == A.Iterator.Element>(_:_Self) -> A {
return A()
}
protocol _ExtendedSequence : Sequence {
postfix func ~>> <A : P where Self.Iterator.Element == A.Iterator.Element>(s: Self) -> A
}
extension Range : _ExtendedSequence {
}
protocol Q : Sequence {
func f<QS : Sequence where QS.Iterator.Element == Self.Iterator.Element>(x: QS)
}
struct No<NT> : IteratorProtocol {
func next() -> NT? {
return .none
}
}
class X<XT> : Q {
typealias Iterator = No<XT>
func f<SX : Sequence where SX.Iterator.Element == X.Iterator.Element>(x: SX) {
}
func makeIterator() -> No<XT> {
return No<XT>()
}
}
| apache-2.0 | eed9c67ce5ddd84f85e8ef33043c25c0 | 19.763158 | 109 | 0.632446 | 3.246914 | false | false | false | false |
tkremenek/swift | test/IRGen/objc_extensions.swift | 12 | 9790 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-objc-attr-requires-foundation-module -emit-module %S/Inputs/objc_extension_base.swift -o %t
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -g | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
import objc_extension_base
// Check that metadata for nested enums added in extensions to imported classes
// gets emitted concretely.
// CHECK: [[CATEGORY_NAME:@.*]] = private constant [16 x i8] c"objc_extensions\00"
// CHECK: [[METHOD_TYPE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK-LABEL: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions" = internal constant
// CHECK-SAME: i64 1,
// CHECK-SAME: @_PROTOCOL__TtP15objc_extensions11NewProtocol_
// CHECK-LABEL: @"_CATEGORY_Gizmo_$_objc_extensions" = internal constant
// CHECK-SAME: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0),
// CHECK-SAME: %objc_class* @"OBJC_CLASS_$_Gizmo",
// CHECK-SAME: @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions",
// CHECK-SAME: @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions",
// CHECK-SAME: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions",
// CHECK-SAME: i8* null
// CHECK-SAME: }, section "__DATA, {{.*}}", align 8
@objc protocol NewProtocol {
func brandNewInstanceMethod()
}
extension NSObject {
@objc func someMethod() -> String { return "Hello" }
}
extension Gizmo: NewProtocol {
@objc func brandNewInstanceMethod() {
}
@objc class func brandNewClassMethod() {
}
// Overrides an instance method of NSObject
override func someMethod() -> String {
return super.someMethod()
}
// Overrides a class method of NSObject
@objc override class func hasOverride() {}
}
/*
* Make sure that two extensions of the same ObjC class in the same module can
* coexist by having different category names.
*/
// CHECK: [[CATEGORY_NAME_1:@.*]] = private unnamed_addr constant [17 x i8] c"objc_extensions1\00"
// CHECK: @"_CATEGORY_Gizmo_$_objc_extensions1" = internal constant
// CHECK: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[CATEGORY_NAME_1]], i64 0, i64 0),
// CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo",
// CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions1",
// CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions1",
// CHECK: i8* null,
// CHECK: i8* null
// CHECK: }, section "__DATA, {{.*}}", align 8
extension Gizmo {
@objc func brandSpankingNewInstanceMethod() {
}
@objc class func brandSpankingNewClassMethod() {
}
}
/*
* Check that extensions of Swift subclasses of ObjC objects get categories.
*/
class Hoozit : NSObject {
}
// CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant
// CHECK: i32 24,
// CHECK: i32 1,
// CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blibble)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR:@.*]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:%.*]]*, i8*)* @"$s15objc_extensions6HoozitC7blibbleyyFTo" to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, {{.*}}", align 8
// CHECK-LABEL: @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant
// CHECK: i32 24,
// CHECK: i32 1,
// CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blobble)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*)* @"$s15objc_extensions6HoozitC7blobbleyyFZTo" to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, {{.*}}", align 8
// CHECK-LABEL: @"_CATEGORY__TtC15objc_extensions6Hoozit_$_objc_extensions" = internal constant
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0),
// CHECK: %swift.type* {{.*}} @"$s15objc_extensions6HoozitCMf",
// CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions",
// CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions",
// CHECK: i8* null,
// CHECK: i8* null
// CHECK: }, section "__DATA, {{.*}}", align 8
extension Hoozit {
@objc func blibble() { }
@objc class func blobble() { }
}
class SwiftOnly { }
// CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions9SwiftOnly_$_objc_extensions" = internal constant
// CHECK: i32 24,
// CHECK: i32 1,
// CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wibble)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*)* @"$s15objc_extensions9SwiftOnlyC6wibbleyyFTo" to i8*)
// CHECK: }] }, section "__DATA, {{.*}}", align 8
extension SwiftOnly {
@objc func wibble() { }
}
class Wotsit: Hoozit {}
extension Hoozit {
@objc func overriddenByExtensionInSubclass() {}
}
extension Wotsit {
@objc override func overriddenByExtensionInSubclass() {}
}
extension NSObject {
private enum SomeEnum { case X }
@objc public func needMetadataOfSomeEnum() {
print(NSObject.SomeEnum.X)
}
@objc class func hasOverride() {}
}
// CHECK-LABEL: @"_CATEGORY__TtCC15objc_extensions5Outer5Inner_$_objc_extensions" = internal constant
// CHECK-SAME: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0),
// CHECK-SAME: @"_CATEGORY_INSTANCE_METHODS__TtCC15objc_extensions5Outer5Inner_$_objc_extensions",
// CHECK-SAME: i8* null
// CHECK-SAME: }, section "__DATA, {{.*}}", align 8
class Outer : NSObject {
class Inner : NSObject {}
}
extension Outer.Inner {
@objc func innerExtensionMethod() {}
}
/*
* Make sure that @NSManaged causes a category to be generated.
*/
class NSDogcow : NSObject {}
// CHECK: [[NAME:@.*]] = private unnamed_addr constant [5 x i8] c"woof\00"
// CHECK: [[ATTR:@.*]] = private unnamed_addr constant [7 x i8] c"Tq,N,D\00"
// CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_extensions8NSDogcow_$_objc_extensions" = internal constant {{.*}} [[NAME]], {{.*}} [[ATTR]], {{.*}}, section "__DATA, {{.*}}", align 8
extension NSDogcow {
@NSManaged var woof: Int
}
// CHECK: @"$sSo8NSObjectC15objc_extensionsE8SomeEnum33_1F05E59585E0BB585FCA206FBFF1A92DLLOSQACMc" =
class SwiftSubGizmo : SwiftBaseGizmo {
// Don't crash on this call. Emit an objC method call to super.
//
// CHECK-LABEL: define {{.*}} @"$s15objc_extensions13SwiftSubGizmoC4frobyyF"
// CHECK: $s15objc_extensions13SwiftSubGizmoCMa
// CHECK: objc_msgSendSuper2
// CHECK: ret
public override func frob() {
super.frob()
}
}
@inline(never) func opaquePrint(_ value: Any) { print(value) }
/*
* Check that we can extend ObjC generics and use both the type and metatype of
* the generic parameter. Specifically, we're checking that we emit debug info
* if we look up the existential bound, and that we derive the argument to
* `opaquePrint(_:)` from the actual parameter, not just the fixed metadata.
*/
extension FungingArray {
// CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsEyAByxGxcfC"
// CHECK-SAME: (%objc_object* %0, %swift.type* swiftself %1)
// CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_XlMD"{{.*}}!dbg
// CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsEyAByxGxcfc"
// CHECK-SAME: (%objc_object* %0, %TSo12FungingArrayC* swiftself %1)
// CHECK: [[ALLOCA:%[^, =]+]] = alloca %Any, align 8
// CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_XlMD"{{.*}}!dbg
// CHECK: {{%[^, =]+}} = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0
// CHECK: [[ANYBUF:%[^, =]+]] = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0
// CHECK: [[BUFPTR:%[^, =]+]] = {{.*}} [[ANYBUF]]
// CHECK: [[BUF_0:%[^, =]+]] = {{.*}} [[BUFPTR]]
// CHECK: store {{.*}} %0, {{.*}} [[BUF_0]]
// CHECK: call swiftcc void @"$s15objc_extensions11opaquePrintyyypF"(%Any* {{.*}} [[ALLOCA]])
@objc public convenience init(_ elem: Element) {
opaquePrint(elem)
self.init()
}
// CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsE7pinningAByxGxm_tcfC"
// CHECK-SAME: (%swift.type* %0, %swift.type* swiftself %1)
// CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_XlMD"{{.*}}!dbg
// CHECK-LABEL: define {{.*}} @"$sSo12FungingArrayC15objc_extensionsE7pinningAByxGxm_tcfc"
// CHECK-SAME: (%swift.type* %0, %TSo12FungingArrayC* swiftself %1)
// CHECK: [[ALLOCA:%[^, =]+]] = alloca %Any, align 8
// CHECK: @__swift_instantiateConcreteTypeFromMangledName{{.*}}@"$sSo9NSFunging_XlMD"{{.*}}!dbg
// CHECK: [[OBJC_CLASS:%[^, =]+]] = call %objc_class* @swift_getObjCClassFromMetadata(%swift.type* %0)
// CHECK: [[OBJC_CLASS_OBJ:%[^, =]+]] = bitcast %objc_class* [[OBJC_CLASS]]
// CHECK: {{%[^, =]+}} = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0
// CHECK: [[ANYBUF:%[^, =]+]] = getelementptr inbounds %Any, %Any* [[ALLOCA]], i32 0, i32 0
// CHECK: [[BUFPTR:%[^, =]+]] = {{.*}} [[ANYBUF]]
// CHECK: [[BUF_0:%[^, =]+]] = {{.*}} [[BUFPTR]]
// CHECK: store {{.*}} [[OBJC_CLASS_OBJ]], {{.*}} [[BUF_0]]
// CHECK: call swiftcc void @"$s15objc_extensions11opaquePrintyyypF"(%Any* {{.*}} [[ALLOCA]])
@objc public convenience init(pinning: Element.Type) {
opaquePrint(pinning as AnyObject)
self.init()
}
}
| apache-2.0 | 631c1f594c966858c9c6ed7cd68848dc | 38.796748 | 178 | 0.64525 | 3.278634 | false | false | false | false |
Zovfreullia/unit-4-assignments | HWfrom1-09-16(SwiftIntro).playground/Contents.swift | 1 | 1725 | //: 01-09 Saturday Homework - Instructor: Linus
/*:
Use the link here to get the questions. Then code your solutions below. If it does not require code, just write your answer in comments.
https://docs.google.com/document/d/1DQ2aCJ_yUZtazzCfb0PaS81bg61V2ZOSxpABh981xSo/edit
*/
//: ### 1
func findMissingNumber(N: Int, list: [Int]) -> Int {
list.sort({$0 < $1})
var j = 0
var missingNum = 0
for i in (0..<list.count) {
j = i + 1
if(j-1 != 1) {
missingNum = i+1
}
}
return missingNum
}
//: ### 2
var arrExample = [1,2,5,7,11,4,8,2,8,9,3,12,5]
func hasDuplicates(arr:[Int]){
let sortedArr = arr.sort()
for (var i = 0; i < sortedArr.count; i++){
let j = i + 1
if (i != sortedArr.count - 1){
if (sortedArr[i] == sortedArr[j]){
print(sortedArr[i])
}
}
}
}
//: ### 3
func smallestNum(listOne: [Int], listTwo: [Int]) -> Int? {
let setOne = Set(listOne)
let setTwo = Set(listTwo)
let num = setOne.intersect(setTwo).minElement()
return num
}
//: ### 4
struct Stack<T> {
private var items:[T]
var count: Int {
get {
return items.count
}
}
mutating func push(element: T) {
items.append(element)
}
mutating func pop() -> T {
return items.removeLast()
}
}
func isPalindrome(word: String) -> Bool {
var stack = Stack<Character>(items: Array(word.characters))
var reverseStack = Stack<Character>(items: Array(word.characters).reverse())
for _ in 0..<stack.count {
if stack.pop() != reverseStack.pop() {
return false
}
}
return true
}
| mit | 0f059bd04225d874c325899cc75f6a9e | 19.783133 | 138 | 0.550145 | 3.254717 | false | false | false | false |
ashfurrow/Nimble-Snapshots | Nimble_Snapshots/DynamicType/NBSMockedApplication.swift | 2 | 5662 | import Foundation
import UIKit
public class NBSMockedApplication {
private var isSwizzled: Bool = false
public init() {}
deinit {
stopMockingPreferredContentSizeCategory()
}
// swiftlint:disable line_length
/* On iOS 9, UIFont.preferredFont(forTextStyle:) uses UIApplication.shared.preferredContentSizeCategory
to get the content size category. However, this changed on iOS 10. While I haven't found what UIFont uses to get
the current category, swizzling preferredFontForTextStyle: to use UIFont.preferredFont(forTextStyle:compatibleWith:)
(only available on iOS >= 10), passing an UITraitCollection with the desired contentSizeCategory.
*/
// swiftlint:enable line_length
public func mockPreferredContentSizeCategory(_ category: UIContentSizeCategory) {
UIApplication.shared.nbs_preferredContentSizeCategory = category
if !isSwizzled {
UIApplication.nbs_swizzle()
UIFont.nbs_swizzle()
UITraitCollection.nbs_swizzle()
isSwizzled = true
}
NotificationCenter.default.post(name: UIContentSizeCategory.didChangeNotification,
object: UIApplication.shared,
userInfo: [UIContentSizeCategory.newValueUserInfoKey: category])
}
public func stopMockingPreferredContentSizeCategory() {
if isSwizzled {
UIApplication.nbs_swizzle()
UIFont.nbs_swizzle()
UITraitCollection.nbs_swizzle()
isSwizzled = false
}
}
}
extension UIFont {
static func nbs_swizzle() {
if !UITraitCollection.instancesRespond(to: #selector(getter: UIApplication.preferredContentSizeCategory)) {
return
}
let selector = #selector(UIFont.preferredFont(forTextStyle:))
let replacedSelector = #selector(nbs_preferredFont(for:))
let originalMethod = class_getClassMethod(self, selector)
let extendedMethod = class_getClassMethod(self, replacedSelector)
if let originalMethod = originalMethod, let extendedMethod = extendedMethod {
method_exchangeImplementations(originalMethod, extendedMethod)
}
}
@objc
static func nbs_preferredFont(for style: UIFont.TextStyle) -> UIFont? {
let category = UIApplication.shared.preferredContentSizeCategory
if #available(iOS 10.0, tvOS 10.0, *) {
let categoryTrait = UITraitCollection(preferredContentSizeCategory: category)
return UIFont.preferredFont(forTextStyle: style, compatibleWith: categoryTrait)
}
return UIFont.preferredFont(forTextStyle: style)
}
}
extension UIApplication {
enum AssociatedKeys {
static var contentSizeCategory: UInt8 = 0
}
@objc var nbs_preferredContentSizeCategory: UIContentSizeCategory? {
get {
return objc_getAssociatedObject(self,
&AssociatedKeys.contentSizeCategory) as? UIContentSizeCategory
}
set {
objc_setAssociatedObject(self,
&AssociatedKeys.contentSizeCategory,
newValue,
.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
static func nbs_swizzle() {
let selector = #selector(getter: UIApplication.preferredContentSizeCategory)
let replacedSelector = #selector(getter: self.nbs_preferredContentSizeCategory)
let originalMethod = class_getInstanceMethod(self, selector)
let extendedMethod = class_getInstanceMethod(self, replacedSelector)
if let originalMethod = originalMethod, let extendedMethod = extendedMethod {
method_exchangeImplementations(originalMethod, extendedMethod)
}
}
}
extension UITraitCollection {
@objc
func nbs_preferredContentSizeCategory() -> UIContentSizeCategory {
return UIApplication.shared.preferredContentSizeCategory
}
@objc
func nbs__changedContentSizeCategory(fromTraitCollection arg: Any?) -> Bool {
return true
}
static func nbs_swizzlePreferredContentSizeCategory() {
let selector = #selector(getter: UIApplication.preferredContentSizeCategory)
if !self.instancesRespond(to: selector) {
return
}
let replacedSelector = #selector(getter: UIApplication.nbs_preferredContentSizeCategory)
let originalMethod = class_getInstanceMethod(self, selector)
let extendedMethod = class_getInstanceMethod(self, replacedSelector)
if let originalMethod = originalMethod, let extendedMethod = extendedMethod {
method_exchangeImplementations(originalMethod, extendedMethod)
}
}
static func nbs_swizzleChangedContentSizeCategoryFromTraitCollection() {
let selector = sel_registerName("_changedContentSizeCategoryFromTraitCollection:")
if !self.instancesRespond(to: selector) {
return
}
let replacedSelector = #selector(nbs__changedContentSizeCategory(fromTraitCollection:))
let originalMethod = class_getInstanceMethod(self, selector)
let extendedMethod = class_getInstanceMethod(self, replacedSelector)
if let originalMethod = originalMethod, let extendedMethod = extendedMethod {
method_exchangeImplementations(originalMethod, extendedMethod)
}
}
static func nbs_swizzle() {
nbs_swizzlePreferredContentSizeCategory()
nbs_swizzleChangedContentSizeCategoryFromTraitCollection()
}
}
| mit | 6f7dca229cd08396ff14f5d9e6d2fe33 | 35.529032 | 121 | 0.67485 | 5.80123 | false | false | false | false |
fbernardo/POPChatHeads | POPChatHeads/Sources/Views/ChatHeadView.swift | 1 | 2234 | //
// ChatHeadView.swift
// POPChatHeads
//
// Created by Fábio Bernardo on 08/12/14.
// Copyright (c) 2014 fbernardo. All rights reserved.
//
import UIKit
class ChatHeadView : UIControl {
var image : UIImage? {
didSet {
self.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 2)
self.layer.shadowRadius = 2
self.layer.shadowOpacity = 0.7
}
convenience init(image : UIImage) {
var rect = CGRectZero
rect.size = image.size
self.init(frame: rect)
self.image = image
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 2)
self.layer.shadowRadius = 2
self.layer.shadowOpacity = 0.7
}
override func drawRect(rect: CGRect) {
// Drawing code
let bounds = self.bounds
let ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
let circlePath = CGPathCreateWithEllipseInRect(bounds, nil);
let inverseCirclePath = CGPathCreateMutableCopy(circlePath)
CGPathAddRect(inverseCirclePath, nil, CGRectInfinite);
CGContextSaveGState(ctx);
CGContextBeginPath(ctx);
CGContextAddPath(ctx, circlePath);
CGContextClip(ctx);
image?.drawInRect(bounds)
CGContextRestoreGState(ctx);
CGContextSaveGState(ctx);
CGContextBeginPath(ctx);
CGContextAddPath(ctx, circlePath);
CGContextClip(ctx);
let shadowColor = UIColor(red: 0.994, green: 0.989, blue: 1, alpha: 1).CGColor
CGContextSetShadowWithColor(ctx, CGSizeMake(0, 0), 3.0, shadowColor);
CGContextBeginPath(ctx);
CGContextAddPath(ctx, inverseCirclePath);
CGContextEOFillPath(ctx);
CGContextRestoreGState(ctx);
CGContextRestoreGState(ctx);
}
}
| mit | 0d648544e13f798a6b6d74a983d7cd86 | 26.231707 | 86 | 0.598746 | 4.92936 | false | false | false | false |
nikita-leonov/boss-client | BoSS/Discover/DiscoverViewController.swift | 1 | 3408 | //
// DiscoverViewController.swift
// BoSS
//
// Created by Nikita Leonov on 2/28/15.
// Copyright (c) 2015 Bureau of Street Services. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class DiscoverViewController: UIViewController {
@IBOutlet private var snap: UIButton!
@IBOutlet private var map: MKMapView!
private var viewModel: DiscoverViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = DiscoverViewModel(submissionsService: ServiceLocator.getService())
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
viewModel.readSubmissions().subscribeNextAs { [weak self] (submissions: [Submission]) in
if let map = self?.map {
map.removeAnnotations(map.annotations)
map.addAnnotations(submissions)
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
snap.rac_command = RACCommand(signalBlock: { [weak self] (value) -> RACSignal! in
RACSignal.createSignal({ [weak self] (subscriber) -> RACDisposable! in
if let strongSelf = self {
let viewModel = ImagePickerViewModel()
let imagePickerController: ImagePickerController = ImagePickerController()
imagePickerController.sourceType = UIImagePickerController.isSourceTypeAvailable(.Camera) ? .Camera : .PhotoLibrary
imagePickerController.viewModel = viewModel
viewModel.imageSelected!.subscribeNext({ (image) -> Void in
if let image = image as? UIImage {
let locationService: LocationServiceProtocol = ServiceLocator.getService()
let submissionsService: SubmissionsServiceProtocol = ServiceLocator.getService()
let submissionModel = SubmissionViewModel(image: image, locationService: locationService, submissionsService: submissionsService)
let submissionViewController = strongSelf.storyboard!.instantiateViewControllerWithIdentifier("submissionViewController") as! SubmissionViewController
submissionViewController.viewModel = submissionModel
imagePickerController.pushViewController(submissionViewController, animated: true)
}
}, completed: { [weak self] _ in
_ = self?.dismissViewControllerAnimated(true, completion: nil)
})
strongSelf.navigationController!.presentViewController(imagePickerController, animated: true, completion: { [weak subscriber] _ in
_ = subscriber?.sendCompleted()
})
}
return RACDisposable {}
})
})
}
}
extension DiscoverViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
var span = MKCoordinateSpanMake(0.01, 0.01)
var region = MKCoordinateRegionMake(userLocation.location.coordinate, span)
mapView.setRegion(region, animated: false)
}
}
| mit | 09c96c9855cceb686353ae2682caea6f | 41.6 | 178 | 0.615023 | 6.32282 | false | false | false | false |
encero/heurary | heurary/Dashboard/DashboardViewController.swift | 1 | 1066 | //
// DashboardViewController.swift
// heurary
//
// Created by matous on 16/04/16.
//
//
import Foundation
import UIKit
class DashboardViewController: UIViewController {
override func loadView() {
super.loadView()
title = "Dashboard"
self.view.backgroundColor = .whiteColor()
// Borrow button
let borrowButton = UIButton(type: .System)
borrowButton.setTitle("vypujcit / vratit", forState: .Normal)
borrowButton.layer.borderWidth = 1.0
borrowButton.layer.borderColor = borrowButton.tintColor.CGColor
borrowButton.layer.cornerRadius = 5
borrowButton.addTarget(self, action: #selector(DashboardViewController.actionBorrowReturn), forControlEvents: .TouchUpInside)
view.addSubview(borrowButton)
borrowButton.snp_makeConstraints(closure: { make in
make.top.equalTo(snp_topLayoutGuideBottom).offset(20)
make.leading.equalTo(20)
make.trailing.equalTo(-20)
make.height.equalTo(44)
})
}
func actionBorrowReturn(sender: UIButton) {
navigationController?.pushViewController(BorrowViewController(), animated: true)
}
}
| mit | e53183550807a2b399dee32010eb326c | 23.227273 | 127 | 0.757036 | 3.675862 | false | false | false | false |
ZamzamInc/SwiftyPress | Sources/SwiftyPress/Data/Models/SeedPayload.swift | 1 | 819 | //
// SeedPayload.swift
// SwiftyPress
//
// Created by Basem Emara on 2018-06-12.
// Copyright © 2019 Zamzam Inc. All rights reserved.
//
public struct SeedPayload: Codable, Equatable {
public let posts: [Post]
public let authors: [Author]
public let media: [Media]
public let terms: [Term]
init(
posts: [Post] = [],
authors: [Author] = [],
media: [Media] = [],
terms: [Term] = []
) {
self.posts = posts
self.authors = authors
self.media = media
self.terms = terms
}
}
public extension SeedPayload {
/// A Boolean value indicating whether the instance is empty.
var isEmpty: Bool {
posts.isEmpty
&& authors.isEmpty
&& media.isEmpty
&& terms.isEmpty
}
}
| mit | 1a9e5ad11550758a49292fb42cdf08ec | 21.108108 | 65 | 0.555012 | 4.049505 | false | false | false | false |
Roommate-App/roomy | roomy/roomy/R.swift | 1 | 1816 | //
// R.swift
// roomy
//
// Created by Ryan Liszewski on 4/11/17.
// Copyright © 2017 Poojan Dave. All rights reserved.
//
struct R {
struct Parse {
struct Key{
static let StatusMessage = "status_message"
}
}
struct Header {
static let home = "Home"
static let notHome = "Not Home"
}
struct Identifier {
struct Cell {
static let homeTableViewCell = "HomeTableViewCell"
static let homeCollectionViewCell = "HomeCollectionViewCell"
static let StatusTableViewCell = "StatusTableViewCell"
}
struct Storyboard {
static let loginAndSignUp = "Main"
static let tabBar = "TabBar"
static let messaging = "Messaging"
static let Status = "Status"
}
struct ViewController {
static let tabBarViewController = "TabBarController"
static let updateStatusViewController = "UpdateStatusViewController"
static let UserSignUpViewController = "UserSignUpViewController"
static let UserLoginInViewController = "UserLoginViewController"
static let HouseLoginViewController = "HouseLoginViewController"
static let CreatHouseViewController = "CreatHouseViewController"
}
struct Segue {
static let WelcomeToRoomySegue = "WelcomeToRoomySegue"
static let TabBarController = "TabBarControllerSegue"
static let SettingsSegue = "SettingsControllerSegue"
}
}
struct TabBarController {
struct SelectedIndex {
static let messagingViewController = 1
}
}
struct Notifications {
struct Messages {
static let title = "Messages"
}
}
}
| mit | 2a3ccb72bf76913ab4af8c80a37b4a61 | 29.25 | 80 | 0.609917 | 5.516717 | false | false | false | false |
DominikBucher12/BEExtension | BEExtension/SourceEditorCommand+Extensions.swift | 1 | 2439 | //
// SourceEditorCommand+Extensions.swift
// BEExtension
//
// Created by Dominik Bucher on 12/11/2017.
// Copyright © 2017 Dominik Bucher. All rights reserved.
//
import Foundation
import XcodeKit
extension SourceEditorCommand {
/// This method should be universal and implemented right from Apple. (excluding the condition for case OC)
/// gets specified text from line indexes
///
/// - Parameters:
/// - buffer: buffer to work with(usually the same instance as in all other functions)
/// - Returns: returns array of texts on specific lines
func getSelectedLinesText(withBuffer buffer: XCSourceTextBuffer) throws -> [String] {
guard let selectedRange = buffer.selections as? [XCSourceTextRange],
let firstRange = selectedRange.first
else { throw NSError() } // You can handle the completion handler here, something like no selection or something like that...
let indexes = Array(firstRange.start.line...firstRange.end.line)
return indexes.map({ buffer.lines[$0] as? String }).compactMap({$0})
}
}
// MARK: Inserting methods
extension SourceEditorCommand {
/// returns index of last selected line from buffer
///
/// - Parameter buffer: The only buffer we get
/// - Returns: index of last line we selected
func lastSelectedLine(fromBuffer buffer: XCSourceTextBuffer) -> Int? {
return (buffer.selections.lastObject as? XCSourceTextRange)?.end.line ?? nil
}
/// Returns lines below our selected text (to be a bit idiotproof, but not too much) - if we find something in our way,
/// we simply skip that or break on next var, enum end or next enum in enum...
///
/// - Parameters:
/// - line: the last line we selected
/// - buffer: text buffer upon we are working
/// - Returns: returns how many lines from selected text we need to skip to extract nice piece of code...
func linesAhead(lastSelectedline line: Int, withBuffer buffer: XCSourceTextBuffer) -> Int {
var linesAhead = 0
for index in line...buffer.lines.count {
if let line = buffer.lines[index] as? String {
if line.contains("case") {
linesAhead += 1
}
else {
buffer.lines.insert("\n", at: index)
break
}
}
}
return linesAhead
}
}
| mit | 7a50724d6d3ce69027605929a34b7d3a | 35.939394 | 133 | 0.635767 | 4.6 | false | false | false | false |
mnisn/zhangchu | zhangchu/Pods/SnapKit/Source/Constraint.swift | 17 | 21750 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose API's for a Constraint
*/
public class Constraint {
public func install() -> [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") }
public func uninstall() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func activate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func deactivate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGPoint) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGSize) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateInsets(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityRequired() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public var layoutConstraints: [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") }
internal var makerFile: String = "Unknown"
internal var makerLine: UInt = 0
}
/**
Used internally to implement a ConcreteConstraint
*/
internal class ConcreteConstraint: Constraint {
internal override func updateOffset(amount: Float) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: Double) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGFloat) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: Int) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: UInt) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGPoint) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: CGSize) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: EdgeInsets) -> Void {
self.constant = amount
}
internal override func updateInsets(amount: EdgeInsets) -> Void {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
}
internal override func updatePriority(priority: Float) -> Void {
self.priority = priority
}
internal override func updatePriority(priority: Double) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: CGFloat) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: UInt) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: Int) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriorityRequired() -> Void {
self.updatePriority(Float(1000.0))
}
internal override func updatePriorityHigh() -> Void {
self.updatePriority(Float(750.0))
}
internal override func updatePriorityMedium() -> Void {
#if os(iOS) || os(tvOS)
self.updatePriority(Float(500.0))
#else
self.updatePriority(Float(501.0))
#endif
}
internal override func updatePriorityLow() -> Void {
self.updatePriority(Float(250.0))
}
internal override func install() -> [LayoutConstraint] {
return self.installOnView(updateExisting: false, file: self.makerFile, line: self.makerLine)
}
internal override func uninstall() -> Void {
self.uninstallFromView()
}
internal override func activate() -> Void {
guard self.installInfo != nil else {
self.install()
return
}
#if SNAPKIT_DEPLOYMENT_LEGACY
guard #available(iOS 8.0, OSX 10.10, *) else {
self.install()
return
}
#endif
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.activateConstraints(layoutConstraints)
}
}
internal override func deactivate() -> Void {
guard self.installInfo != nil else {
return
}
#if SNAPKIT_DEPLOYMENT_LEGACY
guard #available(iOS 8.0, OSX 10.10, *) else {
return
}
#endif
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.deactivateConstraints(layoutConstraints)
}
}
private let fromItem: ConstraintItem
private let toItem: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: Float
private var constant: Any {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
let attribute = (layoutConstraint.secondAttribute == .NotAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = attribute.snp_constantForValue(self.constant)
}
}
}
}
private var priority: Float {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
layoutConstraint.priority = self.priority
}
}
}
}
private let label: String?
private var installInfo: ConcreteConstraintInstallInfo? = nil
override var layoutConstraints: [LayoutConstraint] {
if installInfo == nil {
install()
}
guard let installInfo = installInfo else {
return []
}
return installInfo.layoutConstraints.allObjects as! [LayoutConstraint]
}
internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float, label: String? = nil) {
self.fromItem = fromItem
self.toItem = toItem
self.relation = relation
self.constant = constant
self.multiplier = multiplier
self.priority = priority
self.label = label
}
internal func installOnView(updateExisting updateExisting: Bool = false, file: String? = nil, line: UInt? = nil) -> [LayoutConstraint] {
var installOnView: View? = nil
if self.toItem.view != nil {
installOnView = closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
} else {
if self.fromItem.attributes.isSubsetOf(ConstraintAttributes.Width.union(.Height)) {
installOnView = self.fromItem.view
} else {
installOnView = self.fromItem.view?.superview
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "Missing superview (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
}
}
if let installedOnView = self.installInfo?.view {
if installedOnView != installOnView {
NSException(name: "Cannot Install Constraint", reason: "Already installed on different view. (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? []
}
var newLayoutConstraints = [LayoutConstraint]()
let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
let layoutToAttributes = self.toItem.attributes.layoutAttributes
// get layout from
let layoutFrom: View? = self.fromItem.view
// get layout relation
let layoutRelation: NSLayoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
// get layout constant
let layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
// get layout to
#if os(iOS) || os(tvOS)
var layoutTo: AnyObject? = self.toItem.view ?? self.toItem.layoutSupport
#else
var layoutTo: AnyObject? = self.toItem.view
#endif
if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height {
layoutTo = installOnView
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom!,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: CGFloat(self.multiplier),
constant: layoutConstant)
layoutConstraint.identifier = self.label
// set priority
layoutConstraint.priority = self.priority
// set constraint
layoutConstraint.snp_constraint = self
newLayoutConstraints.append(layoutConstraint)
}
// special logic for updating
if updateExisting {
// get existing constraints for this view
let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse()
// array that will contain only new layout constraints to keep
var newLayoutConstraintsToKeep = [LayoutConstraint]()
// begin looping
for layoutConstraint in newLayoutConstraints {
// layout constraint that should be updated
var updateLayoutConstraint: LayoutConstraint? = nil
// loop through existing and check for match
for existingLayoutConstraint in existingLayoutConstraints {
if existingLayoutConstraint == layoutConstraint {
updateLayoutConstraint = existingLayoutConstraint
break
}
}
// if we have existing one lets just update the constant
if updateLayoutConstraint != nil {
updateLayoutConstraint!.constant = layoutConstraint.constant
}
// otherwise add this layout constraint to new keep list
else {
newLayoutConstraintsToKeep.append(layoutConstraint)
}
}
// set constraints to only new ones
newLayoutConstraints = newLayoutConstraintsToKeep
}
// add constraints
#if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
if #available(iOS 8.0, *) {
NSLayoutConstraint.activateConstraints(newLayoutConstraints)
} else {
installOnView!.addConstraints(newLayoutConstraints)
}
#else
NSLayoutConstraint.activateConstraints(newLayoutConstraints)
#endif
// set install info
self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
// store which layout constraints are installed for this constraint
for layoutConstraint in newLayoutConstraints {
self.installInfo!.layoutConstraints.addObject(layoutConstraint)
}
// store the layout constraints against the layout from view
layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
// return the new constraints
return newLayoutConstraints
}
internal func uninstallFromView() {
if let installInfo = self.installInfo,
let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
if installedLayoutConstraints.count > 0 {
// remove the constraints from the UIView's storage
#if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
if #available(iOS 8.0, *) {
NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
} else if let installedOnView = installInfo.view {
installedOnView.removeConstraints(installedLayoutConstraints)
}
#else
NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
#endif
// remove the constraints from the from item view
if let fromView = self.fromItem.view {
fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
return !installedLayoutConstraints.contains($0)
}
}
}
}
self.installInfo = nil
}
}
private struct ConcreteConstraintInstallInfo {
weak var view: View? = nil
let layoutConstraints: NSHashTable
}
private extension NSLayoutAttribute {
private func snp_constantForValue(value: Any?) -> CGFloat {
// Float
if let float = value as? Float {
return CGFloat(float)
}
// Double
else if let double = value as? Double {
return CGFloat(double)
}
// UInt
else if let int = value as? Int {
return CGFloat(int)
}
// Int
else if let uint = value as? UInt {
return CGFloat(uint)
}
// CGFloat
else if let float = value as? CGFloat {
return float
}
// CGSize
else if let size = value as? CGSize {
if self == .Width {
return size.width
} else if self == .Height {
return size.height
}
}
// CGPoint
else if let point = value as? CGPoint {
#if os(iOS) || os(tvOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .LastBaseline, .FirstBaseline: return point.y
case .Right, .RightMargin: return point.x
case .Bottom, .BottomMargin: return point.y
case .Leading, .LeadingMargin: return point.x
case .Trailing, .TrailingMargin: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return point.x
case .Top, .CenterY, .LastBaseline: return point.y
case .Right: return point.x
case .Bottom: return point.y
case .Leading: return point.x
case .Trailing: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return point.y
}
#endif
}
// EdgeInsets
else if let insets = value as? EdgeInsets {
#if os(iOS) || os(tvOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .LastBaseline, .FirstBaseline: return insets.top
case .Right, .RightMargin: return insets.right
case .Bottom, .BottomMargin: return insets.bottom
case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width: return -insets.left + insets.right
case .Height: return -insets.top + insets.bottom
case .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return insets.left
case .Top, .CenterY, .LastBaseline: return insets.top
case .Right: return insets.right
case .Bottom: return insets.bottom
case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width: return -insets.left + insets.right
case .Height: return -insets.top + insets.bottom
case .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return insets.bottom
}
#endif
}
return CGFloat(0);
}
}
private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
var views = Set<View>()
var fromView = fromView
var toView = toView
repeat {
if let view = toView {
if views.contains(view) {
return view
}
views.insert(view)
toView = view.superview
}
if let view = fromView {
if views.contains(view) {
return view
}
views.insert(view)
fromView = view.superview
}
} while (fromView != nil || toView != nil)
return nil
}
private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
return (left.fromItem == right.fromItem &&
left.toItem == right.toItem &&
left.relation == right.relation &&
left.multiplier == right.multiplier &&
left.priority == right.priority)
}
| mit | be0a4dfe607fcd2748a0f581606ac16c | 41.069632 | 172 | 0.606575 | 5.410448 | false | false | false | false |
milseman/swift | stdlib/public/SDK/Intents/INBooleanResolutionResult.swift | 42 | 908 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
@available(iOS 10.0, watchOS 3.2, *)
extension INBooleanResolutionResult {
@nonobjc public
static func confirmationRequired(with valueToConfirm: Bool?) -> Self {
let number = valueToConfirm.map { NSNumber(value: $0) }
return __confirmationRequiredWithValue(toConfirm: number)
}
}
#endif
| apache-2.0 | 9ad358df09e19b5c6dd8474ac93fc70b | 33.923077 | 80 | 0.595815 | 4.729167 | false | false | false | false |
krishnagawade/Core-Data-Helper | Notes-Swift/Notes-Swift/Note.swift | 1 | 1121 | //
// Note.swift
// Notes-Swift
//
// Created by Krishna Gawade on 17/11/15.
// Copyright (c) 2015 MakeSchool. All rights reserved.
//
import UIKit
import CoreData
@objc(Note)
class Note: NSManagedObject
{
@NSManaged var title: String?
@NSManaged var detail: String?
@NSManaged var date: NSDate?
override func awakeFromInsert()
{
self.date = NSDate()
}
class func entityName() -> NSString
{
return "Note"
}
class func insertNewObjectIntoContext(context : NSManagedObjectContext) -> Note
{
let note = NSEntityDescription.insertNewObjectForEntityForName(self.entityName() as String, inManagedObjectContext:context) as! Note;
return note
}
class func fetchRequest() -> NSFetchRequest
{
let request: NSFetchRequest = NSFetchRequest(entityName: "Note")
let sorter: NSSortDescriptor = NSSortDescriptor(key: "title" , ascending: true)
request.sortDescriptors = [sorter]
request.returnsObjectsAsFaults = false
return request
}
}
| unlicense | 8386efffc1471bb09fcca3f37ae315a7 | 21.877551 | 141 | 0.633363 | 4.811159 | false | false | false | false |
lokinfey/MyPerfectframework | PerfectLib/Routing.swift | 1 | 11451 | //
// Routing.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-11.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
public typealias RequestHandlerGenerator = PageHandlerRegistry.RequestHandlerGenerator
/// Holds the registered routes.
public struct RouteMap: CustomStringConvertible {
/// Pretty prints all route information.
public var description: String {
var s = self.root.description
for (method, root) in self.methodRoots {
s.appendContentsOf("\n" + method + ":\n" + root.description)
}
return s
}
private var root = RouteNode() // root node for any request method
private var methodRoots = [String:RouteNode]() // by convention, use all upper cased method names for inserts/lookups
/// Lookup a route based on the URL path.
/// Returns the handler generator if found.
subscript(path: String, webResponse: WebResponse) -> RequestHandlerGenerator? {
get {
let components = path.lowercaseString.pathComponents
var g = components.generate()
let _ = g.next() // "/"
let method = webResponse.request.requestMethod().uppercaseString
if let root = self.methodRoots[method] {
if let handler = root.findHandler("", generator: g, webResponse: webResponse) {
return handler
}
}
return self.root.findHandler("", generator: g, webResponse: webResponse)
}
}
/// Add a route to the system.
/// `Routing.Routes["/foo/*/baz"] = { _ in return ExampleHandler() }`
public subscript(path: String) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
self.root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
}
}
/// Add an array of routes for a given handler.
/// `Routing.Routes[ ["/", "index.html"] ] = { _ in return ExampleHandler() }`
public subscript(paths: [String]) -> RequestHandlerGenerator? {
get {
return nil
}
set {
for path in paths {
self[path] = newValue
}
}
}
/// Add a route to the system using the indicated HTTP request method.
/// `Routing.Routes["GET", "/foo/*/baz"] = { _ in return ExampleHandler() }`
public subscript(method: String, path: String) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
let uppered = method.uppercaseString
if let root = self.methodRoots[uppered] {
root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
} else {
let root = RouteNode()
self.methodRoots[uppered] = root
root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
}
}
}
/// Add an array of routes for a given handler using the indicated HTTP request method.
/// `Routing.Routes["GET", ["/", "index.html"] ] = { _ in return ExampleHandler() }`
public subscript(method: String, paths: [String]) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
for path in paths {
self[method, path] = newValue
}
}
}
}
/// This wraps up the routing related functionality.
/// Enable the routing system by calling:
/// ```
/// Routing.Handler.registerGlobally()
/// ```
/// This should be done in your `PerfectServerModuleInit` function.
/// The system supports HTTP method based routing, wildcards and variables.
///
/// Add routes in the following manner:
/// ```
/// Routing.Routes["GET", ["/", "index.html"] ] = { (_:WebResponse) in return IndexHandler() }
/// Routing.Routes["/foo/*/baz"] = { _ in return EchoHandler() }
/// Routing.Routes["/foo/bar/baz"] = { _ in return EchoHandler() }
/// Routing.Routes["GET", "/user/{id}/baz"] = { _ in return Echo2Handler() }
/// Routing.Routes["POST", "/user/{id}/baz"] = { _ in return Echo3Handler() }
/// ```
/// The closure you provide should return an instance of `PageHandler`. It is provided the WebResponse object to permit further customization.
/// Variables set by the routing process can be accessed through the `WebRequest.urlVariables` dictionary.
/// Note that a PageHandler *MUST* call `WebResponse.requestCompletedCallback()` when the request has completed.
/// This does not need to be done within the `handleRequest` method.
public class Routing {
/// The routes which have been configured.
static public var Routes = RouteMap()
private init() {}
/// This is the main handler for the logic of the URL routing system.
/// If must be enabled by calling `Routing.Handler.registerGlobally`
public class Handler: RequestHandler {
/// Install the URL routing system.
/// This is required if this system is to be utilized, otherwise it will not be available.
static public func registerGlobally() {
PageHandlerRegistry.addRequestHandler { (_:WebResponse) -> RequestHandler in
return Routing.Handler()
}
}
/// Handle the request, triggering the routing system.
/// If a route is discovered the request is sent to the new handler.
public func handleRequest(request: WebRequest, response: WebResponse) {
let pathInfo = request.requestURI().characters.split("?").map { String($0) }.first ?? "/"
if let handler = Routing.Routes[pathInfo, response] {
handler(response).handleRequest(request, response: response)
} else {
response.setStatus(404, message: "NOT FOUND")
response.appendBodyString("The file \(pathInfo) was not found.")
response.requestCompletedCallback()
}
}
}
}
class RouteNode: CustomStringConvertible {
typealias ComponentGenerator = IndexingGenerator<[String]>
var description: String {
return self.descriptionTabbed(0)
}
private func putTabs(count: Int) -> String {
var s = ""
for _ in 0..<count {
s.appendContentsOf("\t")
}
return s
}
func descriptionTabbedInner(tabCount: Int) -> String {
var s = ""
for (_, node) in self.subNodes {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
for node in self.variables {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
if let node = self.wildCard {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
return s
}
func descriptionTabbed(tabCount: Int) -> String {
var s = ""
if let _ = self.handlerGenerator {
s.appendContentsOf("/+h\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var handlerGenerator: RequestHandlerGenerator?
var wildCard: RouteNode?
var variables = [RouteNode]()
var subNodes = [String:RouteNode]()
func findHandler(currentComponent: String, generator: ComponentGenerator, webResponse: WebResponse) -> RequestHandlerGenerator? {
var m = generator
if let p = m.next() where p != "/" {
// variables
for node in self.variables {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
// paths
if let node = self.subNodes[p] {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
// wildcards
if let node = self.wildCard {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
} else if self.handlerGenerator != nil {
return self.handlerGenerator
} else {
// wildcards
if let node = self.wildCard {
if let h = node.findHandler("", generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute("", handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
}
return nil
}
func successfulRoute(currentComponent: String, handler: RequestHandlerGenerator, webResponse: WebResponse) -> RequestHandlerGenerator {
return handler
}
func addPathSegments(g: ComponentGenerator, h: RequestHandlerGenerator) {
var m = g
if let p = m.next() {
if p == "/" {
self.addPathSegments(m, h: h)
} else {
self.addPathSegment(p, g: m, h: h)
}
} else {
self.handlerGenerator = h
}
}
private func addPathSegment(component: String, g: ComponentGenerator, h: RequestHandlerGenerator) {
if let node = self.nodeForComponent(component) {
node.addPathSegments(g, h: h)
}
}
private func nodeForComponent(component: String) -> RouteNode? {
guard !component.isEmpty else {
return nil
}
if component == "*" {
if self.wildCard == nil {
self.wildCard = RouteWildCard()
}
return self.wildCard
}
if component.characters.count >= 3 && component[component.startIndex] == "{" && component[component.endIndex.predecessor()] == "}" {
let node = RouteVariable(name: component.substringWith(Range(start: component.startIndex.successor(), end: component.endIndex.predecessor())))
self.variables.append(node)
return node
}
if let node = self.subNodes[component] {
return node
}
let node = RoutePath(name: component)
self.subNodes[component] = node
return node
}
}
class RoutePath: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/\(self.name)"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var name = ""
init(name: String) {
self.name = name
}
// RoutePaths don't need to perform any special checking.
// Their path is validated by the fact that they exist in their parent's `subNodes` dict.
}
class RouteWildCard: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/*"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
}
class RouteVariable: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/{\(self.name)}"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var name = ""
init(name: String) {
self.name = name
}
override func successfulRoute(currentComponent: String, handler: RequestHandlerGenerator, webResponse: WebResponse) -> RequestHandlerGenerator {
if let decodedComponent = currentComponent.stringByDecodingURL {
webResponse.request.urlVariables[self.name] = decodedComponent
} else {
webResponse.request.urlVariables[self.name] = currentComponent
}
return handler
}
}
| apache-2.0 | 3676d1613a092a7085807aedb16483d7 | 29.614973 | 149 | 0.680262 | 3.809049 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/TwitterCell.swift | 1 | 4991 | // Copyright (c) 2016, UWF
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of UWF nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// TwitterCell.swift
// Agenda1
//
// Created by Felipe Neves Brito on 5/12/16.
import UIKit
import Haneke
class TwitterCell: UITableViewCell {
var tweet:FNBJSocialFeedTwitterTweet!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var tweetText: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var userScreenNameLabel: UILabel!
@IBOutlet weak var profileImageLabel: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
///Callback function to show the keyboard on the tableview
var showKeyboard : (feed: FNBJSocialFeedFeedObject, indexPath: NSIndexPath) -> Void = { arg in }
// Cell's actual indexPath on the tableview
var indexPath = NSIndexPath()
@IBAction func retweetAction(sender: AnyObject) {
let count = self.tweet.retweetCount + 1
self.retweetButton.setTitle("Retweet \(count)", forState: .Normal)
let twtController = FNBJSocialFeedTwitterController(hashtag: "#itenwired16")
twtController.retweet(self.tweet) { (tweet) in
}
}
@IBAction func favoriteAction(sender: AnyObject) {
let count = self.tweet.favoriteCount + 1
self.favoriteButton.setTitle("Favourite \(count)", forState: .Normal)
let twtController = FNBJSocialFeedTwitterController(hashtag: "#itenwired16")
twtController.favorite(self.tweet) {
}
}
@IBAction func replyAction(sender: AnyObject) {
let feed = FNBJSocialFeedFeedObject()
feed.feed = tweet
feed.date = tweet.date
self.showKeyboard(feed: feed, indexPath: self.indexPath)
}
internal func setProfileImage(url:String){
let urlNS = NSURL(string: url)
let data = NSData(contentsOfURL: urlNS!)
self.profileImageLabel.image = UIImage(data: data!)
}
func build(tweet: FNBJSocialFeedTwitterTweet, indexPath: NSIndexPath, callback: (feed: FNBJSocialFeedFeedObject, indexPath: NSIndexPath)->Void){
self.showKeyboard = callback
self.indexPath = indexPath
self.tweet = tweet
if self.tweet.retweetCount > 0{
self.retweetButton.setTitle("Retweet \(self.tweet.retweetCount)", forState: .Normal)
}else{
self.retweetButton.setTitle("Retweet", forState: .Normal)
}
if self.tweet.favoriteCount > 0 {
self.favoriteButton.setTitle("Favorite \(self.tweet.favoriteCount)", forState: .Normal)
}else{
self.favoriteButton.setTitle("Favorite", forState: .Normal)
}
self.tweetText.text = tweet.text
self.userNameLabel.text = tweet.user.name
self.userScreenNameLabel.text = "@\(tweet.user.screenName)"
let URL = NSURL(string: tweet.user.profileImage)
self.profileImageLabel.hnk_setImageFromURL(URL!)
self.profileImageLabel.layer.cornerRadius = self.profileImageLabel.frame.size.width / 4
self.profileImageLabel.clipsToBounds = true
self.date.text = tweet.date.stringDateSinceNow()
}
} | bsd-2-clause | 1d5775fa857eb223516158c98c143e1a | 34.913669 | 148 | 0.662593 | 4.840931 | false | false | false | false |
jaropawlak/Signal-iOS | Signal/src/environment/ExperienceUpgrades/ExperienceUpgrade.swift | 1 | 2562 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
class ExperienceUpgrade: TSYapDatabaseObject {
let title: String
let body: String
let image: UIImage?
required init(uniqueId: String, title: String, body: String, image: UIImage) {
self.title = title
self.body = body
self.image = image
super.init(uniqueId: uniqueId)
}
override required init(uniqueId: String?) {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
super.init(uniqueId: uniqueId)
}
required init!(coder: NSCoder!) {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
super.init(coder: coder)
}
required init(dictionary dictionaryValue: [AnyHashable : Any]!) throws {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
try super.init(dictionary: dictionaryValue)
}
override class func storageBehaviorForProperty(withKey propertyKey: String) -> MTLPropertyStorage {
// These exist in a hardcoded set - no need to save them, plus it allows us to
// update copy/image down the line if there was a typo and we want to re-expose
// these models in a "change log" archive.
if propertyKey == "title" || propertyKey == "body" || propertyKey == "image" {
return MTLPropertyStorageNone
} else if propertyKey == "uniqueId" || propertyKey == "seenAt" {
return super.storageBehaviorForProperty(withKey: propertyKey)
} else {
// Being conservative here in case we rename a property.
owsFail("unknown property \(propertyKey)")
return super.storageBehaviorForProperty(withKey: propertyKey)
}
}
}
| gpl-3.0 | ef92410660c9cb938b777c3a4c633e99 | 39.666667 | 103 | 0.64598 | 4.558719 | false | false | false | false |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerApp/Models/EYEPopularModel.swift | 1 | 2190 | //
// EYEPopularModel.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/20.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
struct EYEPopularModel {
var videoList : [VideoModel] = [VideoModel]()
/// 数量
var count : Int!
var nextPageUrl : String!
init(dict : NSDictionary) {
self.count = dict["count"] as? Int ?? 0
let videoList : NSArray = dict["videoList"] as! NSArray
self.videoList = videoList.map { (dict) -> VideoModel in
return VideoModel(dict: dict as! NSDictionary)
}
}
struct VideoModel {
var id : Int!
// 日期
var date : Int32!
// 行数
var idx : Int!
// 标题
var title : String!
// 详情
var description : String!
// 播放地址
var playUrl : String!
// 收藏数
var collectionCount : Int!
// 分享数
var shareCount : Int!
// 评论数
var replyCount : Int!
/// 背景图
var feed : String!
/// 模糊背景
var blurred : String!
init(dict : NSDictionary) {
self.id = dict["id"] as? Int ?? 0
self.date = dict["date"] as? Int32 ?? 0
self.idx = dict["idx"] as? Int ?? 0
self.title = dict["title"] as? String ?? ""
self.description = dict["description"] as? String ?? ""
self.playUrl = dict["playUrl"] as? String ?? ""
let consumptionDic = dict["consumption"] as? NSDictionary
if let consumption = consumptionDic {
self.collectionCount = consumption["collectionCount"] as? Int ?? 0
self.shareCount = consumption["shareCount"] as? Int ?? 0
self.replyCount = consumption["replyCount"] as? Int ?? 0
}
let coverDic = dict["cover"] as? NSDictionary
if let cover = coverDic {
self.feed = cover["feed"] as? String ?? ""
self.blurred = cover["blurred"] as? String ?? ""
}
}
}
} | mit | 75e2fcb7f531ea34a73f2ba4742de4fa | 26.921053 | 82 | 0.49505 | 4.284848 | false | false | false | false |
asurinsaka/swift_examples_2.1 | fetchQuote/fetchQuote/main.swift | 1 | 5631 | //
// main.swift
// fetchQuote
//
// Created by larryhou on 4/11/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import Foundation
var ticket:String = "0700.HK"
var zone:String = "+0800"
var related:NSDate?
var verbose = false
var automated = false
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd Z"
var timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "YYYY-MM-dd,HH:mm:ss Z"
func judge(@autoclosure condition:()->Bool, message:String)
{
if !condition()
{
println("ERR: " + message)
exit(1)
}
}
if Process.arguments.filter({$0 == "-h"}).count == 0
{
let count = Process.arguments.filter({$0 == "-t"}).count
judge(count >= 1, "[-t STOCK_TICKET] MUST be provided")
judge(count == 1, "[-t STOCK_TICKET] has been set \(count) times")
judge(Process.argc >= 3, "Unenough Parameters")
}
var skip:Bool = false
for i in 1..<Int(Process.argc)
{
let option = Process.arguments[i]
if skip
{
skip = false
continue
}
switch option
{
case "-t":
judge(Process.arguments.count > i + 1, "-t lack of parameter")
ticket = Process.arguments[i + 1]
skip = true
break
case "-d":
judge(Process.arguments.count > i + 1, "-d lack of parameter")
related = dateFormatter.dateFromString(Process.arguments[i + 1] + " \(zone)")
judge(related != nil, "Unsupported date format:\(Process.arguments[i + 1]), e.g.2015-04-09")
skip = true
break
case "-z":
judge(Process.arguments.count > i + 1, "-z lack of parameter")
zone = Process.arguments[i + 1]
let regex = NSPredicate(format: "SELF MATCHES %@", "[+-]\\d{4}")
judge(regex.evaluateWithObject(zone), "Unsupported time zone format:\(zone), e.g. +0800")
skip = true
break
case "-v":
verbose = true
break
case "-a":
automated = true
break
case "-h":
let msg = Process.arguments[0] + " -t STOCK_TICKET [-z TIME_ZONE] [-d DATE]"
println(msg)
exit(0)
break
default:
println("Unsupported arguments: " + Process.arguments[i])
exit(2)
}
}
func getQuotesURL(var date:NSDate?)->NSURL
{
if date == nil
{
date = NSDate()
}
let text = dateFormatter.stringFromDate(date!).componentsSeparatedByString(" ").first!
date = timeFormatter.dateFromString("\(text),06:00:00 \(zone)")
let refer = timeFormatter.dateFromString("\(text),20:00:00 \(zone)")!
let s = UInt(date!.timeIntervalSince1970)
let e = UInt(refer.timeIntervalSince1970)
let url = "http://finance.yahoo.com/_td_charts_api/resource/charts;comparisonTickers=;events=div%7Csplit%7Cearn;gmtz=8;indicators=quote;period1=\(s);period2=\(e);queryString=%7B%22s%22%3A%22\(ticket)%2BInteractive%22%7D;range=1d;rangeSelected=undefined;ticker=\(ticket);useMock=false?crumb=a6xbm2fVIlt"
return NSURL(string: url)!
}
class QuoteSpliter:Printable
{
let date:NSDate
let ratios:[Int]
init(date:NSDate, ratios:[Int])
{
self.date = date
self.ratios = ratios
}
var description:String
{
return dateFormatter.stringFromDate(date) + ", " + "/".join(ratios.map({"\($0)"}))
}
}
func formatQuote(value:AnyObject, format:String = "%6.2f")->String
{
return String(format:format, value as! Double)
}
func fetchQuoteOn(date:NSDate?)
{
let url = getQuotesURL(date)
if verbose
{
println(url)
}
var response:NSURLResponse?
var error:NSError?
var spliters:[QuoteSpliter] = []
let data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: url), returningResponse: &response, error: &error)
if data != nil
{
error = nil
var result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error)
if error == nil
{
let json = result as! NSDictionary
let map = json.valueForKeyPath("data.events.splits") as? [String:[String:AnyObject]]
if map != nil
{
for (key, item) in map!
{
let time = NSString(string: key).integerValue
let date = NSDate(timeIntervalSince1970: NSTimeInterval(time))
let ratios = (item["splitRatio"] as! String).componentsSeparatedByString("/").map({$0.toInt()!})
spliters.append(QuoteSpliter(date: date, ratios: ratios))
}
}
let quotes = (json.valueForKeyPath("data.indicators.quote") as! [[String:[AnyObject]]]).first!
let stamps = json.valueForKeyPath("data.timestamp") as! [UInt]
let OPEN = "open",HIGH = "high",LOW = "low",CLOSE = "close"
let VOLUME = "volume"
var list:[String] = []
for i in 0..<stamps.count
{
var item:[String] = []
var date = NSDate(timeIntervalSince1970: NSTimeInterval(stamps[i]))
if quotes[OPEN]![i] is NSNull
{
continue
}
item.append(timeFormatter.stringFromDate(date).componentsSeparatedByString(" ").first!)
item.append(formatQuote(quotes[OPEN]![i]))
item.append(formatQuote(quotes[HIGH]![i]))
item.append(formatQuote(quotes[LOW ]![i]))
item.append(formatQuote(quotes[CLOSE]![i]))
item.append("\(quotes[VOLUME]![i])")
list.append(",".join(item))
}
if spliters.count > 0
{
println(spliters)
}
println("\n".join(list))
}
else
{
if verbose
{
println(NSString(data: data!, encoding: NSUTF8StringEncoding)!)
}
}
}
else
{
if verbose
{
if response != nil
{
println(response!)
}
println(error!)
}
exit(202)
}
}
if !automated
{
fetchQuoteOn(related)
}
else
{
let DAY:NSTimeInterval = 24 * 3600
related = NSDate(timeIntervalSince1970: NSDate().timeIntervalSince1970 + DAY)
for i in 0...50
{
fetchQuoteOn(NSDate(timeIntervalSince1970: related!.timeIntervalSince1970 - NSTimeInterval(i) * DAY))
}
}
| mit | e88b644069a0272bc72982b4d748c281 | 22.4625 | 303 | 0.660096 | 3.152856 | false | false | false | false |
CoderZZF/DYZB | DYZB/DYZB/Classes/Tools/NetworkTools.swift | 1 | 1822 | //
// NetworkTools.swift
// Alamofire测试
//
// Created by zhangzhifu on 2017/3/17.
// Copyright © 2017年 seemygo. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
/*
一个零件的组装操作有三个步骤,需要两个人(外部A和内部B)执行完成,顺序是A将原料传递给B,B初步组装后再传递给A,A进行最后一步组装,任务完成.
B有时会被别人叫走,不能确定何时有空,才能完成第二步组装,为了及时完成整体组装任务,B和A说:"我把第二步组装完成后的模型给你,你据此完成第三步,然后把成品给我,等我有空把第二步完成后再将实物替换之前给你的模型,这样你不需要等待咱们也能在第一时间完成整体的组装任务了
*/
/*
内部定义闭包:老公和老婆说:"我今天接了一个活儿,事成之后能赚一笔钱,你这几天没事可以去商场里转转,有看上的衣服记下来,回头钱下来给你买.
外部实现闭包:老婆告诉老公想买什么.
内部调用闭包:钱下来后,老公带着老婆去买衣服.
*/
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallBack : @escaping (_ result : Any)-> ()) {
// 1. 获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2. 发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3. 获取结果
guard let result = response.result.value else {
print(response.result.error)
return
}
// 4. 将结果回调出去
finishedCallBack(result)
}
}
}
| apache-2.0 | 90f8fa27701b01d540635d05857d2832 | 26.795455 | 157 | 0.64677 | 2.580169 | false | false | false | false |
zhangliangzhi/iosStudyBySwift | xxcolor/Pods/SwiftyStoreKit/SwiftyStoreKit/InAppReceiptRefreshRequest.swift | 2 | 2812 | //
// InAppReceiptRefreshRequest.swift
// SwiftyStoreKit
//
// Created by phimage on 23/12/15.
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import StoreKit
import Foundation
class InAppReceiptRefreshRequest: NSObject, SKRequestDelegate {
enum ResultType {
case success
case error(e: Error)
}
typealias RequestCallback = (ResultType) -> Void
class func refresh(_ receiptProperties: [String : Any]? = nil, callback: @escaping RequestCallback) -> InAppReceiptRefreshRequest {
let request = InAppReceiptRefreshRequest(receiptProperties: receiptProperties, callback: callback)
request.start()
return request
}
let refreshReceiptRequest: SKReceiptRefreshRequest
let callback: RequestCallback
deinit {
refreshReceiptRequest.delegate = nil
}
private init(receiptProperties: [String : Any]? = nil, callback: @escaping RequestCallback) {
self.callback = callback
self.refreshReceiptRequest = SKReceiptRefreshRequest(receiptProperties: receiptProperties)
super.init()
self.refreshReceiptRequest.delegate = self
}
func start() {
self.refreshReceiptRequest.start()
}
func requestDidFinish(_ request: SKRequest) {
/*if let resoreRequest = request as? SKReceiptRefreshRequest {
let receiptProperties = resoreRequest.receiptProperties ?? [:]
for (k, v) in receiptProperties {
print("\(k): \(v)")
}
}*/
callback(.success)
}
func request(_ request: SKRequest, didFailWithError error: Error) {
// XXX could here check domain and error code to return typed exception
callback(.error(e: error))
}
}
| mit | 4356f3d305ad68df865eeca9ac01c79c | 36 | 135 | 0.709104 | 4.831615 | false | false | false | false |
PJayRushton/stats | Stats/SettingsViewController.swift | 1 | 6400 | //
// SettingsViewController.swift
// Stats
//
// Created by Parker Rushton on 4/1/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
class SettingsViewController: Component, AutoStoryboardInitializable {
// MARK: - Types
enum SettingsSection: Int {
case profile
case teams
var rows: [SettingsRow] {
switch self {
case .profile:
return [.email]
case .teams:
return [.manageTeams, .switchTeam, .seasons]
}
}
var title: String? {
switch self {
case .profile:
return NSLocalizedString("Profile", comment: "")
case .teams:
return NSLocalizedString("Team Management", comment: "")
}
}
static let allValues = [SettingsSection.profile, .teams]
}
enum SettingsRow: Int {
case email
case manageTeams
case switchTeam
case seasons
var title: String {
switch self {
case .email:
return NSLocalizedString("Email", comment: "")
case .manageTeams:
return NSLocalizedString("Manage Teams", comment: "")
case .switchTeam:
return NSLocalizedString("Switch Team", comment: "")
case .seasons:
return NSLocalizedString("Manage Seasons", comment: "")
}
}
var accessory: UITableViewCellAccessoryType {
switch self {
case .email:
return .none
case .manageTeams, .switchTeam, .seasons:
return .disclosureIndicator
}
}
}
// MARK: - IBActions
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
// MARK: - Constants
fileprivate let settingsCellId = "SettingsCell"
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor.mainNavBarColor
navigationItem.leftBarButtonItem?.tintColor = .white
Appearance.setUp(navTextColor: .white)
tableView.sectionHeaderHeight = 32
registerCells()
var versionString = ""
if let version = Bundle.main.releaseVersionNumber {
versionString = "Version: \(version)"
}
if let buildString = Bundle.main.buildVersionNumber {
versionString += " (\(buildString))"
}
versionLabel.text = versionString
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Appearance.setUp()
}
// MARK: - IBActions
@IBAction func dismissButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
// MARK: - Subscriber
override func update(with: AppState) {
tableView.reloadData()
}
}
// MARK: - Fileprivate
extension SettingsViewController {
fileprivate func registerCells() {
let headerNib = UINib(nibName: BasicHeaderCell.reuseIdentifier, bundle: nil)
tableView.register(headerNib, forCellReuseIdentifier: BasicHeaderCell.reuseIdentifier)
}
}
// MARK: - TableView
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return SettingsSection.allValues.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = SettingsSection(rawValue: section)!
return section.rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = SettingsSection(rawValue: indexPath.section)!
let theRow = section.rows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: settingsCellId, for: indexPath)
cell.textLabel?.text = theRow.title
cell.accessoryType = theRow.accessory
cell.detailTextLabel?.text = detail(for: theRow)
return cell
}
fileprivate func detail(for row: SettingsRow) -> String? {
switch row {
case .email:
return core.state.userState.currentUser?.email
case .manageTeams:
return nil
case .switchTeam:
return core.state.teamState.currentTeam?.name
case .seasons:
return core.state.teamState.currentTeam?.currentSeason?.name
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let theSection = SettingsSection(rawValue: section)!
let header = tableView.dequeueReusableCell(withIdentifier: BasicHeaderCell.reuseIdentifier) as! BasicHeaderCell
guard let title = theSection.title else { return nil }
header.update(with: title)
return header
}
}
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let section = SettingsSection(rawValue: indexPath.section)!
let theRow = section.rows[indexPath.row]
switch theRow {
case .email:
break // TODO: edit email
case .manageTeams:
let teamManagerVC = TeamListViewController.initializeFromStoryboard()
teamManagerVC.isDismissable = false
teamManagerVC.isSwitcher = false
navigationController?.pushViewController(teamManagerVC, animated: true)
case .switchTeam:
let teamSwitcherVC = TeamListViewController.initializeFromStoryboard()
teamSwitcherVC.isDismissable = false
teamSwitcherVC.isSwitcher = true
navigationController?.pushViewController(teamSwitcherVC, animated: true)
case .seasons:
let seasonsVC = SeasonsViewController.initializeFromStoryboard()
seasonsVC.isModal = false
navigationController?.pushViewController(seasonsVC, animated: true)
}
}
}
| mit | ead66ecc9dae67417ebb1bdc85d19157 | 29.327014 | 119 | 0.611189 | 5.487993 | false | false | false | false |
jevy-wangfei/FeedMeIOS | OrderDetailTableViewController.swift | 2 | 3892 | //
// TrackingOrderTableViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 15/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class OrderDetailTableViewController: UITableViewController {
var dishes: [Dish]!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
if Reachability.isConnectedToNetwork() {
self.dishes = FeedMe.Variable.order!.dishesList()
} else {
Reachability.alertNoInternetConnection(self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ContactRestaurantButtonClicked(sender: UIButton) {
let phone = 0416354917
if let url = NSURL(string: "tel://\(phone)") {
UIApplication.sharedApplication().openURL(url)
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dishes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "OrderDetailTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! OrderDetailTableViewCell
// Configure the cell...
let dish = self.dishes[indexPath.row]
cell.dishNameLabel.text = dish.name
cell.dishUnitPriceLabel.text = String(dish.price)
cell.dishQtyLabel.text = String(FeedMe.Variable.order!.dishQty(dish))
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0ac793b1c07b109276067489fa2b1191 | 33.433628 | 157 | 0.678232 | 5.389197 | false | false | false | false |
yanif/circator | MetabolicCompass/View Controller/TabController/MainTabController.swift | 1 | 9054 | //
// MainTabController.swift
// MetabolicCompass
//
// Created by Inaiur on 5/5/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
import Async
import MetabolicCompassKit
class MainTabController: UITabBarController, UITabBarControllerDelegate, ManageEventMenuDelegate {
private var overlayView: UIVisualEffectView? = nil
private var menu: ManageEventMenu? = nil
private var lastMenuUseAddedEvents = false
private var dailyProgressVC: DailyProgressViewController? = nil
//MARK: View life circle
override func viewDidLoad() {
super.viewDidLoad()
self.configureTabBar()
self.delegate = self
self.selectedIndex = 0;
if let viewController = self.selectedViewController {
if let controller = viewController as? DashboardTabControllerViewController {
controller.rootNavigationItem = self.navigationItem
}
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidLogin), name: UMDidLoginNotifiaction, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidLogout), name: UMDidLogoutNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userAddedCircadianEvents), name: MEMDidUpdateCircadianEvents, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.addOverlay()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.hidden = true
self.navigationController?.navigationBar.barStyle = .Black
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent;
}
func configureTabBar() {
let tabBar: UITabBar = self.tabBar
guard let items = tabBar.items else {
return
}
for tabItem in items {
tabItem.image = tabItem.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
tabItem.selectedImage = tabItem.selectedImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
}
}
//MARK: UITabBarControllerDelegate
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
if let controller = viewController as? DashboardTabControllerViewController {
controller.rootNavigationItem = self.navigationItem
}
}
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
if viewController is UIPageViewController {
return false
}
return true
}
//MARK: Notifications
func userDidLogin() {
Async.main(after: 0.5) {
if self.menu != nil {
self.menu!.hidden = false
} else {
self.userDidLogin()
}
}
}
func userDidLogout() {
self.menu!.hidden = true
}
func userAddedCircadianEvents() {
lastMenuUseAddedEvents = true
}
//MARK: Working with ManageEventMenu
func addMenuToView () {
let addExercisesImage = UIImage(named:"icon-add-exercises")!
let addExercisesItem = PathMenuItem(image: addExercisesImage, highlightedImage: nil, contentImage: nil, contentText: "Exercise")
let addMealImage = UIImage(named:"icon-add-food")!
let addMealItem = PathMenuItem(image: addMealImage, highlightedImage: nil, contentImage: nil, contentText: "Meals")
let addSleepImage = UIImage(named:"icon-add-sleep")!
let addSleepItem = PathMenuItem(image: addSleepImage, highlightedImage: nil, contentImage: nil, contentText: "Sleep")
let items = [addMealItem, addExercisesItem, addSleepItem]
let startItem = PathMenuItem(image: UIImage(named: "button-dashboard-add-data")!,
highlightedImage: UIImage(named: "button-dashboard-add-data"),
contentImage: UIImage(named: "button-dashboard-add-data"),
highlightedContentImage: UIImage(named: "button-dashboard-add-data"))
self.menu = ManageEventMenu(frame: view.bounds, startItem: startItem, items: items)
self.menu!.delegate = self
self.menu!.startPoint = CGPointMake(view.frame.width/2, view.frame.size.height - 26.0)
self.menu!.timeOffset = 0.0
self.menu!.animationDuration = 0.15
self.menu!.hidden = !UserManager.sharedManager.hasAccount()
self.view.window?.rootViewController?.view.addSubview(self.menu!)
}
// MARK :- Add event blur overlay
func addOverlay () {
if self.overlayView == nil {
let overlay = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
overlay.frame = (self.view.window?.rootViewController?.view.bounds)!
overlay.alpha = 0.9
overlay.userInteractionEnabled = true
overlay.hidden = true
self.view.window?.rootViewController?.view.addSubview(overlay)
self.overlayView = overlay
//add title for overlay
let titleLabel = UILabel(frame:CGRectZero)
titleLabel.text = "YOUR CIRCADIAN RHYTHM"
titleLabel.font = ScreenManager.appFontOfSize(16)
titleLabel.textColor = UIColor.colorWithHexString("#ffffff", alpha: 0.6)
titleLabel.textAlignment = .Center
titleLabel.sizeToFit()
titleLabel.frame = CGRectMake(0, 35, CGRectGetWidth(overlay.frame), CGRectGetHeight(titleLabel.frame))
overlay.contentView.addSubview(titleLabel)
self.addMenuToView()
}
}
func hideOverlay() {
self.overlayView?.hidden = true
}
func hideIcons(hide: Bool) {
self.menu?.hideView(hide)
}
// MARK :- ManageEventMenuDelegate implementation
func manageEventMenu(menu: ManageEventMenu, didSelectIndex idx: Int) {
Async.main(after: 0.4) {
self.hideIcons(true)
self.hideOverlay()
let controller = UIStoryboard(name: "AddEvents", bundle: nil).instantiateViewControllerWithIdentifier("AddMealNavViewController") as! UINavigationController
let rootController = controller.viewControllers[0] as! AddEventViewController
switch idx {
case EventType.Meal.rawValue:
rootController.type = .Meal
case EventType.Exercise.rawValue:
rootController.type = .Exercise
case EventType.Sleep.rawValue:
rootController.type = .Sleep
default:
break
}
self.selectedViewController?.presentViewController(controller, animated: true, completion: nil)
}
}
func manageEventMenuWillAnimateOpen(menu: ManageEventMenu) {
lastMenuUseAddedEvents = false
self.overlayView?.hidden = false
hideIcons(false)
}
func manageEventMenuWillAnimateClose(menu: ManageEventMenu) {
}
func manageEventMenuDidFinishAnimationOpen(menu: ManageEventMenu) {
self.menu?.logContentView()
}
func manageEventMenuDidFinishAnimationClose(menu: ManageEventMenu) {
self.hideOverlay()
hideIcons(true)
if lastMenuUseAddedEvents {
initializeDailyProgressVC()
if dailyProgressVC != nil {
Async.background(after: 1.0) {
self.dailyProgressVC?.contentDidUpdate()
}
} else {
log.warning("No DailyProgressViewController available")
}
}
self.menu?.logContentView(false)
}
func initializeDailyProgressVC() {
if dailyProgressVC == nil {
for svc in self.selectedViewController!.childViewControllers {
if let _ = svc as? DashboardTabControllerViewController {
for svc2 in svc.childViewControllers {
if let _ = svc2 as? UITabBarController {
for svc3 in svc2.childViewControllers {
if let dpvc = svc3 as? DailyProgressViewController {
dailyProgressVC = dpvc
break
}
}
break
}
}
break
}
}
log.verbose("Daily progress view controller after init: \(dailyProgressVC)")
}
}
//MARK: Deinit
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| apache-2.0 | 1b61d3968418ea3eb98b6c277e2d99ff | 36.409091 | 168 | 0.619905 | 5.350473 | false | false | false | false |
samwyndham/DictateSRS | Pods/ReactiveKit/Sources/Typealiases.swift | 9 | 1926 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public typealias Signal1<Element> = Signal<Element, NoError>
public typealias SafeSignal<Element> = Signal<Element, NoError>
public typealias Observer1<Element> = (Event<Element, NoError>) -> Void
public typealias SafeObserver<Element> = (Event<Element, NoError>) -> Void
public typealias PublishSubject1<Element> = PublishSubject<Element, NoError>
public typealias SafePublishSubject<Element> = PublishSubject<Element, NoError>
public typealias ReplaySubject1<Element> = ReplaySubject<Element, NoError>
public typealias SafeReplaySubject<Element> = ReplaySubject<Element, NoError>
public typealias ReplayOneSubject1<Element> = ReplayOneSubject<Element, NoError>
public typealias SafeReplayOneSubject<Element> = ReplayOneSubject<Element, NoError>
| mit | b493be7c22a7dd38dea72f2b8f5bd13b | 49.684211 | 83 | 0.774143 | 4.367347 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Core/Core.swift | 1 | 36633 | // Core.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 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
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
// MARK: Row
internal class RowDefaults {
static var cellUpdate = Dictionary<String, (BaseCell, BaseRow) -> Void>()
static var cellSetup = Dictionary<String, (BaseCell, BaseRow) -> Void>()
static var onCellHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>()
static var onCellUnHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>()
static var rowInitialization = Dictionary<String, (BaseRow) -> Void>()
static var rawCellUpdate = Dictionary<String, Any>()
static var rawCellSetup = Dictionary<String, Any>()
static var rawOnCellHighlight = Dictionary<String, Any>()
static var rawOnCellUnHighlight = Dictionary<String, Any>()
static var rawRowInitialization = Dictionary<String, Any>()
}
// MARK: FormCells
public struct CellProvider<Cell: BaseCell> where Cell: CellType {
/// Nibname of the cell that will be created.
public fileprivate (set) var nibName: String?
/// Bundle from which to get the nib file.
public fileprivate (set) var bundle: Bundle!
public init(){}
public init(nibName: String, bundle: Bundle? = nil){
self.nibName = nibName
self.bundle = bundle ?? Bundle(for: Cell.self)
}
/**
Creates the cell with the specified style.
- parameter cellStyle: The style with which the cell will be created.
- returns: the cell
*/
func createCell(_ cellStyle: UITableViewCellStyle) -> Cell {
if let nibName = self.nibName {
return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell
}
return Cell.init(style: cellStyle, reuseIdentifier: nil)
}
}
/**
Enumeration that defines how a controller should be created.
- Callback->VCType: Creates the controller inside the specified block
- NibFile: Loads a controller from a nib file in some bundle
- StoryBoard: Loads the controller from a Storyboard by its storyboard id
*/
public enum ControllerProvider<VCType: UIViewController>{
/**
* Creates the controller inside the specified block
*/
case callback(builder: (() -> VCType))
/**
* Loads a controller from a nib file in some bundle
*/
case nibFile(name: String, bundle: Bundle?)
/**
* Loads the controller from a Storyboard by its storyboard id
*/
case storyBoard(storyboardId: String, storyboardName: String, bundle: Bundle?)
func createController() -> VCType {
switch self {
case .callback(let builder):
return builder()
case .nibFile(let nibName, let bundle):
return VCType.init(nibName: nibName, bundle:bundle ?? Bundle(for: VCType.self))
case .storyBoard(let storyboardId, let storyboardName, let bundle):
let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? Bundle(for: VCType.self))
return sb.instantiateViewController(withIdentifier: storyboardId) as! VCType
}
}
}
/**
* Responsible for the options passed to a selector view controller
*/
public struct DataProvider<T: Equatable> {
public let arrayData: [T]?
public init(arrayData: [T]){
self.arrayData = arrayData
}
}
/**
Defines how a controller should be presented.
- Show?: Shows the controller with `showViewController(...)`.
- PresentModally?: Presents the controller modally.
- SegueName?: Performs the segue with the specified identifier (name).
- SegueClass?: Performs a segue from a segue class.
*/
public enum PresentationMode<VCType: UIViewController> {
/**
* Shows the controller, created by the specified provider, with `showViewController(...)`.
*/
case show(controllerProvider: ControllerProvider<VCType>, completionCallback: ((UIViewController)->())?)
/**
* Presents the controller, created by the specified provider, modally.
*/
case presentModally(controllerProvider: ControllerProvider<VCType>, completionCallback: ((UIViewController)->())?)
/**
* Performs the segue with the specified identifier (name).
*/
case segueName(segueName: String, completionCallback: ((UIViewController)->())?)
/**
* Performs a segue from a segue class.
*/
case segueClass(segueClass: UIStoryboardSegue.Type, completionCallback: ((UIViewController)->())?)
case popover(controllerProvider: ControllerProvider<VCType>, completionCallback: ((UIViewController)->())?)
var completionHandler: ((UIViewController) ->())? {
switch self{
case .show(_, let completionCallback):
return completionCallback
case .presentModally(_, let completionCallback):
return completionCallback
case .segueName(_, let completionCallback):
return completionCallback
case .segueClass(_, let completionCallback):
return completionCallback
case .popover(_, let completionCallback):
return completionCallback
}
}
/**
Present the view controller provided by PresentationMode. Should only be used from custom row implementation.
- parameter viewController: viewController to present if it makes sense (normally provided by createController method)
- parameter row: associated row
- parameter presentingViewController: form view controller
*/
public func presentViewController(_ viewController: VCType!, row: BaseRow, presentingViewController:FormViewController){
switch self {
case .show(_, _):
presentingViewController.show(viewController, sender: row)
case .presentModally(_, _):
presentingViewController.present(viewController, animated: true, completion: nil)
case .segueName(let segueName, _):
presentingViewController.performSegue(withIdentifier: segueName, sender: row)
case .segueClass(let segueClass, _):
let segue = segueClass.init(identifier: row.tag, source: presentingViewController, destination: viewController)
presentingViewController.prepare(for: segue, sender: row)
segue.perform()
case .popover(_, _):
guard let porpoverController = viewController.popoverPresentationController else {
fatalError()
}
porpoverController.sourceView = porpoverController.sourceView ?? presentingViewController.tableView
porpoverController.sourceRect = porpoverController.sourceRect ?? row.baseCell.frame
presentingViewController.present(viewController, animated: true, completion: nil)
}
}
/**
Creates the view controller specified by presentation mode. Should only be used from custom row implementation.
- returns: the created view controller or nil depending on the PresentationMode type.
*/
public func createController() -> VCType? {
switch self {
case .show(let controllerProvider, let completionCallback):
let controller = controllerProvider.createController()
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.completionCallback = callback
}
return controller
case .presentModally(let controllerProvider, let completionCallback):
let controller = controllerProvider.createController()
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.completionCallback = callback
}
return controller
case .popover(let controllerProvider, let completionCallback):
let controller = controllerProvider.createController()
controller.modalPresentationStyle = .popover
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.completionCallback = callback
}
return controller
default:
return nil
}
}
}
/**
* Protocol to be implemented by custom formatters.
*/
public protocol FormatterProtocol {
func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition
}
//MARK: Predicate Machine
enum ConditionType {
case hidden, disabled
}
/**
Enumeration that are used to specify the disbaled and hidden conditions of rows
- Function: A function that calculates the result
- Predicate: A predicate that returns the result
*/
public enum Condition {
/**
* Calculate the condition inside a block
*
* @param Array of tags of the rows this function depends on
* @param Form->Bool The block that calculates the result
*
* @return If the condition is true or false
*/
case function([String], (Form)->Bool)
/**
* Calculate the condition using a NSPredicate
*
* @param NSPredicate The predicate that will be evaluated
*
* @return If the condition is true or false
*/
case predicate(NSPredicate)
}
extension Condition : ExpressibleByBooleanLiteral {
/**
Initialize a condition to return afixed boolean value always
*/
public init(booleanLiteral value: Bool){
self = Condition.function([]) { _ in return value }
}
}
extension Condition : ExpressibleByStringLiteral {
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(stringLiteral value: String){
self = .predicate(NSPredicate(format: value))
}
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(unicodeScalarLiteral value: String) {
self = .predicate(NSPredicate(format: value))
}
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(extendedGraphemeClusterLiteral value: String) {
self = .predicate(NSPredicate(format: value))
}
}
//MARK: Errors
/**
Errors thrown by Eureka
- DuplicatedTag: When a section or row is inserted whose tag dows already exist
*/
public enum EurekaError : Error {
case duplicatedTag(tag: String)
}
//Mark: FormViewController
/**
* A protocol implemented by FormViewController
*/
public protocol FormViewControllerProtocol {
var tableView: UITableView? { get }
func beginEditing<T:Equatable>(_ cell: Cell<T>)
func endEditing<T:Equatable>(_ cell: Cell<T>)
func insertAnimationForRows(_ rows: [BaseRow]) -> UITableViewRowAnimation
func deleteAnimationForRows(_ rows: [BaseRow]) -> UITableViewRowAnimation
func reloadAnimationOldRows(_ oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation
func insertAnimationForSections(_ sections : [Section]) -> UITableViewRowAnimation
func deleteAnimationForSections(_ sections : [Section]) -> UITableViewRowAnimation
func reloadAnimationOldSections(_ oldSections: [Section], newSections:[Section]) -> UITableViewRowAnimation
}
/**
* Navigation options for a form view controller.
*/
public struct RowNavigationOptions : OptionSet {
fileprivate enum NavigationOptions : Int {
case disabled = 0, enabled = 1, stopDisabledRow = 2, skipCanNotBecomeFirstResponderRow = 4
}
public let rawValue: Int
public init(rawValue: Int){ self.rawValue = rawValue}
fileprivate init(_ options:NavigationOptions ){ self.rawValue = options.rawValue }
/// No navigation.
public static let Disabled = RowNavigationOptions(.disabled)
/// Full navigation.
public static let Enabled = RowNavigationOptions(.enabled)
/// Break navigation when next row is disabled.
public static let StopDisabledRow = RowNavigationOptions(.stopDisabledRow)
/// Break navigation when next row cannot become first responder.
public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.skipCanNotBecomeFirstResponderRow)
}
/**
* Defines the configuration for the keyboardType of FieldRows.
*/
public struct KeyboardReturnTypeConfiguration {
/// Used when the next row is available.
public var nextKeyboardType = UIReturnKeyType.next
/// Used if next row is not available.
public var defaultKeyboardType = UIReturnKeyType.default
public init(){}
public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType){
self.nextKeyboardType = nextKeyboardType
self.defaultKeyboardType = defaultKeyboardType
}
}
/**
* Options that define when an inline row should collapse.
*/
public struct InlineRowHideOptions : OptionSet {
fileprivate enum _InlineRowHideOptions : Int {
case never = 0, anotherInlineRowIsShown = 1, firstResponderChanges = 2
}
public let rawValue: Int
public init(rawValue: Int){ self.rawValue = rawValue}
fileprivate init(_ options:_InlineRowHideOptions ){ self.rawValue = options.rawValue }
/// Never collapse automatically. Only when user taps inline row.
public static let Never = InlineRowHideOptions(.never)
/// Collapse qhen another inline row expands. Just one inline row will be expanded at a time.
public static let AnotherInlineRowIsShown = InlineRowHideOptions(.anotherInlineRowIsShown)
/// Collapse when first responder changes.
public static let FirstResponderChanges = InlineRowHideOptions(.firstResponderChanges)
}
/// View controller that shows a form.
open class FormViewController : UIViewController, FormViewControllerProtocol {
@IBOutlet open var tableView: UITableView?
fileprivate lazy var _form : Form = { [weak self] in
let form = Form()
form.delegate = self
return form
}()
open var form : Form {
get { return _form }
set {
_form.delegate = nil
tableView?.endEditing(false)
_form = newValue
_form.delegate = self
if isViewLoaded && tableView?.window != nil {
tableView?.reloadData()
}
}
}
/// Accessory view that is responsible for the navigation between rows
lazy open var navigationAccessoryView : NavigationAccessoryView = {
[unowned self] in
let naview = NavigationAccessoryView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44.0))
naview.tintColor = self.view.tintColor
return naview
}()
/// Defines the behaviour of the navigation between rows
open var navigationOptions : RowNavigationOptions?
fileprivate var tableViewStyle: UITableViewStyle = .grouped
public init(style: UITableViewStyle) {
super.init(nibName: nil, bundle: nil)
tableViewStyle = style
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
if tableView == nil {
tableView = UITableView(frame: view.bounds, style: tableViewStyle)
tableView?.autoresizingMask = UIViewAutoresizing.flexibleWidth.union(.flexibleHeight)
if #available(iOS 9.0, *){
tableView?.cellLayoutMarginsFollowReadableWidth = false
}
}
if tableView?.superview == nil {
view.addSubview(tableView!)
}
if tableView?.delegate == nil {
tableView?.delegate = self
}
if tableView?.dataSource == nil {
tableView?.dataSource = self
}
tableView?.estimatedRowHeight = BaseRow.estimatedRowHeight
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let selectedIndexPaths = tableView?.indexPathsForSelectedRows ?? []
tableView?.reloadRows(at: selectedIndexPaths, with: .none)
selectedIndexPaths.forEach {
tableView?.selectRow(at: $0, animated: false, scrollPosition: .none)
}
let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in
selectedIndexPaths.forEach {
self?.tableView?.deselectRow(at: $0, animated: context.isAnimated)
}
}
let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in
if context.isCancelled {
selectedIndexPaths.forEach {
self?.tableView?.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
}
if let coordinator = transitionCoordinator {
coordinator.animateAlongsideTransition(in: parent?.view, animation: deselectionAnimation, completion: reselection)
}
else {
selectedIndexPaths.forEach {
tableView?.deselectRow(at: $0, animated: false)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let baseRow = sender as? BaseRow
baseRow?.prepareForSegue(segue)
}
/**
Returns the navigation accessory view if it is enabled. Returns nil otherwise.
*/
open func inputAccessoryViewForRow(_ row: BaseRow) -> UIView? {
let options = navigationOptions ?? Form.defaultNavigationOptions
guard options.contains(.Enabled) else { return nil }
guard row.baseCell.cellCanBecomeFirstResponder() else { return nil}
navigationAccessoryView.previousButton.isEnabled = nextRowForRow(row, withDirection: .up) != nil
navigationAccessoryView.doneButton.target = self
navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:))
navigationAccessoryView.previousButton.target = self
navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:))
navigationAccessoryView.nextButton.target = self
navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:))
navigationAccessoryView.nextButton.isEnabled = nextRowForRow(row, withDirection: .down) != nil
return navigationAccessoryView
}
//MARK: FormDelegate
open func rowValueHasBeenChanged(_ row: BaseRow, oldValue: Any?, newValue: Any?) {}
//MARK: FormViewControllerProtocol
/**
Called when a cell becomes first responder
*/
public final func beginEditing<T:Equatable>(_ cell: Cell<T>) {
cell.row.highlightCell()
guard let _ = tableView, (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return }
let row = cell.baseRow
let inlineRow = row?._inlineRow
for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) {
if let inlineRow = row as? BaseInlineRowType {
inlineRow.collapseInlineRow()
}
}
}
/**
Called when a cell resigns first responder
*/
public final func endEditing<T:Equatable>(_ cell: Cell<T>) {
cell.row.unhighlightCell()
}
/**
Returns the animation for the insertion of the given rows.
*/
open func insertAnimationForRows(_ rows: [BaseRow]) -> UITableViewRowAnimation {
return .fade
}
/**
Returns the animation for the deletion of the given rows.
*/
open func deleteAnimationForRows(_ rows: [BaseRow]) -> UITableViewRowAnimation {
return .fade
}
/**
Returns the animation for the reloading of the given rows.
*/
open func reloadAnimationOldRows(_ oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the insertion of the given sections.
*/
open func insertAnimationForSections(_ sections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the deletion of the given sections.
*/
open func deleteAnimationForSections(_ sections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the reloading of the given sections.
*/
open func reloadAnimationOldSections(_ oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
//MARK: TextField and TextView Delegate
open func textInputShouldBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputDidBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) {
if let row = cell.row as? KeyboardReturnHandler {
let nextRow = nextRowForRow(cell.row, withDirection: .down)
if let textField = textInput as? UITextField {
textField.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType))
}
else if let textView = textInput as? UITextView {
textView.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType))
}
}
}
open func textInputShouldEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) {
}
open func textInput<T>(_ textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool {
return true
}
open func textInputShouldClear<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputShouldReturn<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
if let nextRow = nextRowForRow(cell.row, withDirection: .down){
if nextRow.baseCell.cellCanBecomeFirstResponder(){
nextRow.baseCell.cellBecomeFirstResponder()
return true
}
}
tableView?.endEditing(true)
return true
}
//MARK: Private
fileprivate var oldBottomInset : CGFloat?
}
extension FormViewController : UITableViewDelegate {
//MARK: UITableViewDelegate
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return indexPath
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard tableView == self.tableView else { return }
let row = form[indexPath]
// row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds.
if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() {
self.tableView?.endEditing(true)
}
row.didSelect()
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard tableView == self.tableView else { return tableView.rowHeight }
let row = form[indexPath.section][indexPath.row]
return row.baseCell.height?() ?? tableView.rowHeight
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard tableView == self.tableView else { return tableView.rowHeight }
let row = form[indexPath.section][indexPath.row]
return row.baseCell.height?() ?? tableView.estimatedRowHeight
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return form[section].header?.viewForSection(form[section], type: .header)
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return form[section].footer?.viewForSection(form[section], type:.footer)
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let height = form[section].header?.height {
return height()
}
guard let view = form[section].header?.viewForSection(form[section], type: .header) else{
return UITableViewAutomaticDimension
}
guard view.bounds.height != 0 else {
return UITableViewAutomaticDimension
}
return view.bounds.height
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let height = form[section].footer?.height {
return height()
}
guard let view = form[section].footer?.viewForSection(form[section], type: .footer) else{
return UITableViewAutomaticDimension
}
guard view.bounds.height != 0 else {
return UITableViewAutomaticDimension
}
return view.bounds.height
}
}
extension FormViewController : UITableViewDataSource {
//MARK: UITableViewDataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return form.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return form[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
form[indexPath].updateCell()
return form[indexPath].baseCell
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return form[section].header?.title
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return form[section].footer?.title
}
}
extension FormViewController: FormDelegate {
//MARK: FormDelegate
public func sectionsHaveBeenAdded(_ sections: [Section], atIndexes: IndexSet){
tableView?.beginUpdates()
tableView?.insertSections(atIndexes, with: insertAnimationForSections(sections))
tableView?.endUpdates()
}
public func sectionsHaveBeenRemoved(_ sections: [Section], atIndexes: IndexSet){
tableView?.beginUpdates()
tableView?.deleteSections(atIndexes, with: deleteAnimationForSections(sections))
tableView?.endUpdates()
}
public func sectionsHaveBeenReplaced(oldSections:[Section], newSections: [Section], atIndexes: IndexSet){
tableView?.beginUpdates()
tableView?.reloadSections(atIndexes, with: reloadAnimationOldSections(oldSections, newSections: newSections))
tableView?.endUpdates()
}
public func rowsHaveBeenAdded(_ rows: [BaseRow], atIndexPaths: [IndexPath]) {
tableView?.beginUpdates()
tableView?.insertRows(at: atIndexPaths, with: insertAnimationForRows(rows))
tableView?.endUpdates()
}
public func rowsHaveBeenRemoved(_ rows: [BaseRow], atIndexPaths: [IndexPath]) {
tableView?.beginUpdates()
tableView?.deleteRows(at: atIndexPaths, with: deleteAnimationForRows(rows))
tableView?.endUpdates()
}
public func rowsHaveBeenReplaced(oldRows:[BaseRow], newRows: [BaseRow], atIndexPaths: [IndexPath]){
tableView?.beginUpdates()
tableView?.reloadRows(at: atIndexPaths, with: reloadAnimationOldRows(oldRows, newRows: newRows))
tableView?.endUpdates()
}
}
extension FormViewController : UIScrollViewDelegate {
//MARK: UIScrollViewDelegate
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
tableView?.endEditing(true)
}
}
extension FormViewController {
//MARK: KeyBoard Notifications
/**
Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary.
*/
public func keyboardWillShow(_ notification: Notification){
guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return }
let keyBoardInfo = notification.userInfo!
let keyBoardFrame = table.window!.convert(((keyBoardInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue)!, to: table.superview)
let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y
var tableInsets = table.contentInset
var scrollIndicatorInsets = table.scrollIndicatorInsets
oldBottomInset = oldBottomInset ?? tableInsets.bottom
if newBottomInset > oldBottomInset {
tableInsets.bottom = newBottomInset
scrollIndicatorInsets.bottom = tableInsets.bottom
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).intValue)!)
table.contentInset = tableInsets
table.scrollIndicatorInsets = scrollIndicatorInsets
if let selectedRow = table.indexPath(for: cell) {
table.scrollToRow(at: selectedRow, at: .none, animated: false)
}
UIView.commitAnimations()
}
}
/**
Called when the keyboard will disappear. Adjusts insets of the tableView.
*/
public func keyboardWillHide(_ notification: Notification){
guard let table = tableView, let oldBottom = oldBottomInset else { return }
let keyBoardInfo = notification.userInfo!
var tableInsets = table.contentInset
var scrollIndicatorInsets = table.scrollIndicatorInsets
tableInsets.bottom = oldBottom
scrollIndicatorInsets.bottom = tableInsets.bottom
oldBottomInset = nil
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).intValue)!)
table.contentInset = tableInsets
table.scrollIndicatorInsets = scrollIndicatorInsets
UIView.commitAnimations()
}
}
public enum Direction { case up, down }
extension FormViewController {
//MARK: Navigation Methods
func navigationDone(_ sender: UIBarButtonItem) {
tableView?.endEditing(true)
}
func navigationAction(_ sender: UIBarButtonItem) {
navigateToDirection(sender == navigationAccessoryView.previousButton ? .up : .down)
}
public func navigateToDirection(_ direction: Direction){
guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return }
guard let currentIndexPath = tableView?.indexPath(for: currentCell) else { assertionFailure(); return }
guard let nextRow = nextRowForRow(form[currentIndexPath], withDirection: direction) else { return }
if nextRow.baseCell.cellCanBecomeFirstResponder(){
tableView?.scrollToRow(at: nextRow.indexPath()!, at: .none, animated: false)
nextRow.baseCell.cellBecomeFirstResponder(direction)
}
}
fileprivate func nextRowForRow(_ currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? {
let options = navigationOptions ?? Form.defaultNavigationOptions
guard options.contains(.Enabled) else { return nil }
guard let nextRow = direction == .down ? form.nextRowForRow(currentRow) : form.previousRowForRow(currentRow) else { return nil }
if nextRow.isDisabled && options.contains(.StopDisabledRow) {
return nil
}
if !nextRow.baseCell.cellCanBecomeFirstResponder() && !nextRow.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow){
return nil
}
if (!nextRow.isDisabled && nextRow.baseCell.cellCanBecomeFirstResponder()){
return nextRow
}
return nextRowForRow(nextRow, withDirection:direction)
}
}
extension FormViewControllerProtocol {
//MARK: Helpers
func makeRowVisible(_ row: BaseRow){
guard let cell = row.baseCell, let indexPath = row.indexPath(), let tableView = tableView else { return }
if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height){
tableView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
}
}
}
| mit | 398cbb46dd8feba0a3b207b234695852 | 38.263666 | 352 | 0.67057 | 5.323017 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/SCSCustomPaletteProvider.swift | 1 | 4685 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// SCSCustomPaletteProvider.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
import Foundation
import SciChart
enum RenderableSeriesType {
case line
case column
case ohlc
case mountain
case candles
case scatter
case none
}
class SCSCustomPaletteProvider: SCIPaletteProvider {
private let lineSeriesStyle: SCILineSeriesStyle = SCILineSeriesStyle()
private let columnSeriesStyle: SCIColumnSeriesStyle = SCIColumnSeriesStyle()
private let ohlcSeriesStyle: SCIOhlcSeriesStyle = SCIOhlcSeriesStyle()
private let candleStickSeriesStyle: SCICandlestickSeriesStyle = SCICandlestickSeriesStyle()
private let mountainSeriesStyle: SCIMountainSeriesStyle = SCIMountainSeriesStyle()
private let scatterSeriesStyle: SCIScatterSeriesStyle = SCIScatterSeriesStyle()
private let startIndex:Int32 = 152
private let endIndex:Int32 = 158
private var seriesType:RenderableSeriesType = .none
override init() {
super.init()
let ellipsePointMarker = SCIEllipsePointMarker()
ellipsePointMarker.width = 7
ellipsePointMarker.height = 7
ellipsePointMarker.fillStyle = SCISolidBrushStyle.init(color: UIColor.red)
ellipsePointMarker.strokeStyle = SCISolidPenStyle.init(color: UIColor.red, withThickness: 1.0)
lineSeriesStyle.pointMarker = ellipsePointMarker
lineSeriesStyle.strokeStyle = SCISolidPenStyle.init(color: UIColor.red, withThickness: 1.0)
mountainSeriesStyle.areaStyle = SCISolidBrushStyle.init(color: UIColor.red)
mountainSeriesStyle.strokeStyle = SCISolidPenStyle.init(color: UIColor.red, withThickness: 1.0)
let squarePointMarker = SCISquarePointMarker()
squarePointMarker.width = 7
squarePointMarker.height = 7
squarePointMarker.fillStyle = SCISolidBrushStyle.init(color:UIColor.green)
scatterSeriesStyle.pointMarker = squarePointMarker
ohlcSeriesStyle.strokeUpStyle = SCISolidPenStyle.init(colorCode:0xFF6495ED, withThickness:1.0)
ohlcSeriesStyle.strokeDownStyle = SCISolidPenStyle.init(colorCode:0xFF6495ED, withThickness:1.0)
candleStickSeriesStyle.fillUpBrushStyle = SCISolidBrushStyle.init(color:UIColor.green)
candleStickSeriesStyle.fillDownBrushStyle = SCISolidBrushStyle.init(color:UIColor.green)
columnSeriesStyle.fillBrushStyle = SCISolidBrushStyle.init(color:UIColor.purple)
}
override func updateData(_ data: SCIRenderPassDataProtocol!) {
if data.renderableSeries() is SCIFastLineRenderableSeries{
seriesType = .line
}
if data.renderableSeries() is SCIFastColumnRenderableSeries{
seriesType = .column
}
if data.renderableSeries() is SCIXyScatterRenderableSeries{
seriesType = .scatter
}
if data.renderableSeries() is SCIFastCandlestickRenderableSeries{
seriesType = .candles
}
if data.renderableSeries() is SCIFastMountainRenderableSeries{
seriesType = .mountain
}
if data.renderableSeries() is SCIFastOhlcRenderableSeries{
seriesType = .ohlc
}
}
override func styleFor(x: Double, y: Double, index: Int32) -> SCIStyleProtocol! {
let isInRange:Bool = (index >= startIndex) && (index <= endIndex)
if (isInRange){
switch seriesType {
case .line:
return lineSeriesStyle;
case .column:
return columnSeriesStyle;
case .ohlc:
return ohlcSeriesStyle;
case .candles:
return candleStickSeriesStyle;
case .mountain:
return mountainSeriesStyle;
case .scatter:
return scatterSeriesStyle;
case .none:
return nil
}
}
return nil;
}
}
| mit | df84f798c87ad55703e8232d6c2eef56 | 38.677966 | 104 | 0.657411 | 4.777551 | false | false | false | false |
SheldonWangRJT/SpinningCubeHud | SCHud/Classes/Constants.swift | 1 | 599 | //
// Constants.swift
// SCHud
//
// Created by Xiaodan Wang on 8/19/17.
// Copyright © 2017 Xiaodan Wang. All rights reserved.
//
public enum SCViewSize: CGFloat {
case tiny = 0.1
case small = 0.2
case medium = 0.3
case large = 0.4
case huge = 0.5
}
public enum SCCubeTheme {
case blackWhite
case rainbow
///Custom theme needs 6 requried colors for 6 surface and 1 color for the edges
case custom(UIColor, UIColor, UIColor, UIColor, UIColor, UIColor, UIColor)
}
public enum SCBlurEffect {
case none
case extraLight
case light
case dark
}
| mit | 0d5e32ac7eeb577a3b499289e17cc37a | 19.62069 | 83 | 0.662207 | 3.497076 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftDemoKit/SwiftDemoKit/ViewController_KeyChain.swift | 1 | 7959 | //
// ViewController_KeyChain.swift
// SwiftDemoKit
//
// Created by runo on 17/8/8.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
import Security
class ViewController_KeyChain: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*
//方法一:
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
//方法二:个人推荐用这个请求,速度比较快
/*
http://ipof.in/json
http://ipof.in/xml
http://ipof.in/txt
If you want HTTPS you can use the same URLs with https prefix. The advantage being that even if you are on a Wifi you will get the public address.
*/
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ipof.in/txt"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
*/
let url = URL.init(string: "http://ifconfig.me/ip")
do {
let ipaddress = try String.init(contentsOf: url!, encoding: String.Encoding.utf8)
print("ip \(ipaddress)")
}
catch{
print(error)
}
}
}
struct KeychainConfiguration {
static let serviceName = "MyAppService"
static let accessGroup: String? = nil
}
struct KeychainPasswordItem {
enum KeychainError: Error {
case noPassword //这个item没在keychain存密码
case unexpectedPasswordData //解析密码错误
case unexpectedItemData
case unhandledError(status: OSStatus)
}
let service: String
private(set) var account: String
let accessGroup: String?
init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
func readPassword() throws -> String {
var query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
var queryResult: AnyObject?
let status = withUnsafePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer(mutating: $0))
}
//表示根本就没有这个账号存储过
guard status != errSecItemNotFound else {
throw KeychainError.noPassword
}
//有错误,抛出错误
guard status == noErr else {
throw KeychainError.unhandledError(status: status)
}
guard let existingItem = queryResult as? [String: AnyObject],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String.init(data: passwordData, encoding: String.Encoding.utf8)
else {
throw KeychainError.unexpectedPasswordData
}
return password
}
//保存密码,区分是修改还是添加新的
func savePassword(_ password: String) throws {
let encodedPassword = password.data(using: String.Encoding.utf8)!
do{
try _ = readPassword()//首先读取一下,判断是更新密码还是添加密码
//可以读取代表是更新密码
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
//有错误抛出错误
guard status == noErr else {
throw KeychainError.unhandledError(status: status)
}
}catch KeychainError.noPassword {
//表示要新加password
var newItem = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
newItem[kSecValueData as String] = encodedPassword as AnyObject?
let status = SecItemAdd(newItem as CFDictionary, nil)
guard status == noErr else {
throw KeychainError.unhandledError(status: status)
}
}
}
//修改账号
mutating func renameAccount(_ newAccountName: String) throws {
var attributesToUpdate = [String: AnyObject]()
attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: self.account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
guard status == noErr || status == errSecItemNotFound else {
throw KeychainError.unhandledError(status: status)
}
self.account = newAccountName
}
//删除item
func deleteItem() throws {
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
guard status == noErr || status == errSecItemNotFound else {
throw KeychainError.unhandledError(status: status)
}
}
private static func passwordItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainPasswordItem] {
var query = KeychainPasswordItem.keychainQuery(withService: service, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanFalse
var queryResult: AnyObject?
let status = withUnsafePointer(to: &queryResult) { (par) -> OSStatus in
return SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer(mutating: par))
}
//无匹配数据
guard status != errSecItemNotFound else {
return []
}
guard status == noErr else {
throw KeychainError.unhandledError(status: status)
}
//数据类型不对
guard let resultData = queryResult as? [[String : AnyObject]] else {
throw KeychainError.unexpectedItemData
}
var passwordItems = [KeychainPasswordItem]()
for result in resultData {
guard let account = result[kSecAttrAccount as String] as? String else {
throw KeychainError.unexpectedItemData
}
let passwordItem = KeychainPasswordItem.init(service: service, account: account, accessGroup: accessGroup)
passwordItems.append(passwordItem)
}
return passwordItems
}
//组建查询字典
private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String: AnyObject] {
var query = [String: AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}
}
| apache-2.0 | 4176b1c53c83736f322f381769b95c4e | 31.944206 | 155 | 0.623372 | 5.246753 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/WebWrapper/VerificationFlowWebViewController.swift | 1 | 7329 | //
// VerificationFlowWebViewController.swift
// StripeIdentity
//
// Created by Mel Ludowise on 3/3/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import AVKit
@_spi(STP) import StripeCore
import UIKit
import WebKit
@available(iOS 14.3, *)
@available(iOSApplicationExtension, unavailable)
protocol VerificationFlowWebViewControllerDelegate: AnyObject {
/// Invoked when the user has closed the `VerificationFlowWebViewController`.
/// - Parameters:
/// - viewController: The view controller that was closed.
/// - result: The result of the user's verification flow.
/// Value is `.flowCompleted` if the user successfully completed the flow.
/// Value is `.flowCanceled` if the user closed the view controller prior to completing the flow.
func verificationFlowWebViewController(
_ viewController: VerificationFlowWebViewController,
didFinish result: IdentityVerificationSheet.VerificationFlowResult
)
}
/// View controller that wraps the Identity Verification web flow. It starts at the URL
/// `https://verify.stripe.com/start/{{url_token}}`
///
/// If the user proceeds to the URL `https://verify.stripe.com/success` prior to closing the view,
/// then a `.flowCompleted` result is sent to the view controller delegate's `didFinish` method.
///
/// If the user closes the view controller prior to reaching the `/success` page, then a `.flowCanceled`
/// result is sent to the view controller delegate's `didFinish` method.
@available(iOS 14.3, *)
@available(iOSApplicationExtension, unavailable)
final class VerificationFlowWebViewController: UIViewController {
weak var delegate: VerificationFlowWebViewControllerDelegate?
private(set) var verificationWebView: VerificationFlowWebView?
private let startUrl: URL
/// Result to return to the delegate when the ViewController is closed
private var result: IdentityVerificationSheet.VerificationFlowResult = .flowCanceled
init(
startUrl: URL,
delegate: VerificationFlowWebViewControllerDelegate?
) {
self.startUrl = startUrl
super.init(nibName: nil, bundle: nil)
self.delegate = delegate
setupNavbar()
}
/// Instantiates a new `VerificationFlowWebViewController`.
/// - Parameters:
/// - clientSecret: The VerificationSession client secret.
/// - delegate: Optional delegate for the `VerificationFlowWebViewController`
convenience init(
clientSecret: VerificationClientSecret,
delegate: VerificationFlowWebViewControllerDelegate?
) {
self.init(
startUrl: VerifyWebURLHelper.startURL(fromToken: clientSecret.urlToken),
delegate: delegate
)
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
/// Instantiates a new `VerificationFlowWebViewController` inside of a navigation controller.
/// - Parameters:
/// - clientSecret: The VerificationSession client secret.
/// - delegate: Optional delegate for the `VerificationFlowWebViewController`
static func makeInNavigationController(
clientSecret: VerificationClientSecret,
delegate: VerificationFlowWebViewControllerDelegate?
) -> UINavigationController {
let viewController = VerificationFlowWebViewController(
clientSecret: clientSecret,
delegate: delegate
)
let navigationController = UINavigationController(rootViewController: viewController)
return navigationController
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the background color while we wait for the use to grant camera
// permissions, otherwise the view controller is transparent while the
// camera permissions prompt is displayed.
if verificationWebView == nil {
view.backgroundColor = .systemBackground
}
}
override func viewWillAppear(_ animated: Bool) {
// Since `viewWillAppear` can be called multiple times, only setup the webView once.
guard self.verificationWebView == nil else {
return
}
// NOTE(mludowise|RUN_IDPROD-1210): Ask for camera permissions prior to
// instantiating the webView, otherwise the `getUserMedia` returns
// `undefined` in Javascript on iOS 14.6.
requestCameraPermissionsIfNeeded(completion: { [weak self] in
guard let self = self else { return }
self.verificationWebView = VerificationFlowWebView(initialURL: self.startUrl)
// Install view
if self.verificationWebView !== self.view {
self.verificationWebView?.frame = self.view.frame
self.view = self.verificationWebView
}
// Set delegate
self.verificationWebView?.delegate = self
// Load webView
self.verificationWebView?.load()
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
delegate?.verificationFlowWebViewController(self, didFinish: result)
}
}
// MARK: - Private
@available(iOS 14.3, *)
@available(iOSApplicationExtension, unavailable)
extension VerificationFlowWebViewController {
fileprivate func setupNavbar() {
title = STPLocalizedString(
"Verify your identity",
"Displays in the navigation bar title of the Identity Verification Sheet"
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: String.Localized.close,
style: .plain,
target: self,
action: #selector(didTapCloseButton)
)
}
fileprivate func requestCameraPermissionsIfNeeded(completion: @escaping () -> Void) {
// NOTE: We won't do anything different if the user does vs. doesn't
// grant camera access. The web flow already handles both cases.
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { _ in
DispatchQueue.main.async {
completion()
}
}
case .authorized,
.denied,
.restricted:
completion()
@unknown default:
completion()
}
}
@objc
fileprivate func didTapCloseButton() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - VerificationFlowWebViewDelegate
@available(iOS 14.3, *)
@available(iOSApplicationExtension, unavailable)
extension VerificationFlowWebViewController: VerificationFlowWebViewDelegate {
func verificationFlowWebView(_ view: VerificationFlowWebView, didChangeURL url: URL?) {
if url == VerifyWebURLHelper.successURL {
result = .flowCompleted
}
}
func verificationFlowWebViewDidFinishLoading(_ view: VerificationFlowWebView) {}
func verificationFlowWebViewDidClose(_ view: VerificationFlowWebView) {
dismiss(animated: true, completion: nil)
}
func verificationFlowWebView(_ view: VerificationFlowWebView, didOpenURLInNewTarget url: URL) {
UIApplication.shared.open(url)
}
}
| mit | e17aff730b81e9e6f16ab89bf08fc93b | 34.230769 | 113 | 0.674536 | 5.325581 | false | false | false | false |
rohan-jansen/PopKit | PopKit/Classes/PopoKitDismissingAnimator.swift | 1 | 5815 | //
// PopoKitDismissingAnimator.swift
// PopKit_Example
//
// Created by Rohan Jansen on 2017/08/16.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
class PopKitDismissingAnimator: NSObject, UIViewControllerAnimatedTransitioning, TransitionDuration {
var kit: PopKit
var transitionDuration: TimeInterval?
init(with kit: PopKit) {
self.kit = kit
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return kit.transitionSpeed
}
func animateSlide(_ transitionContext: UIViewControllerContextTransitioning, _ controller: PopKitPresentationController, _ finalCenter: CGPoint, _ animationOption: UIView.AnimationOptions) {
let animationDuration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOption, animations: {
controller.presentedViewController.view.center = finalCenter
controller.presentedViewController.view.transform = CGAffineTransform.identity
}) { finished in
transitionContext.completeTransition(finished)
}
}
func animateBounce(_ damping: Float, _ velocity: Float, _ transitionContext: UIViewControllerContextTransitioning, _ controller: PopKitPresentationController, _ finalCenter: CGPoint, _ animationOption: UIView.AnimationOptions) {
let animationDuration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: CGFloat(damping), initialSpringVelocity: CGFloat(velocity), options: animationOption, animations: {
controller.presentedViewController.view.center = finalCenter
}) { finished in
transitionContext.completeTransition(finished)
}
}
fileprivate func animateScale(_ transitionContext: UIViewControllerContextTransitioning, _ controller: PopKitPresentationController, _ scale: (Float), _ animationOption: UIView.AnimationOptions) {
let animationDuration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOption, animations: {
controller.presentedViewController.view.transform = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale))
}) { finished in
transitionContext.completeTransition(finished)
}
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerController = transitionContext.viewController(forKey: .from)!
let toController = transitionContext.viewController(forKey: .to)!
let controller = transitionContext.viewController(forKey: .from)?.presentationController as! PopKitPresentationController
transitionContext.containerView.addSubview(controller.presentedViewController.view)
var finalFrame = controller.frameOfPresentedViewInContainerView
let toControllerViewFrame = toController.view.frame
switch kit.outAnimation {
case .slideFromTop(let animationOption):
finalFrame.origin.y = toControllerViewFrame.size.height * 2
animateSlide(transitionContext, controller, CGPoint(x: containerController.view.center.x, y: finalFrame.origin.y), animationOption)
case .slideFromLeft(let animationOption):
finalFrame.origin.x = toControllerViewFrame.size.width * 2
animateSlide(transitionContext, controller, CGPoint(x: finalFrame.origin.x, y: containerController.view.center.y), animationOption)
case .slideFromRight(let animationOption):
finalFrame.origin.x = -toControllerViewFrame.size.width * 2
animateSlide(transitionContext, controller, CGPoint(x: finalFrame.origin.x, y: containerController.view.center.y), animationOption)
case .slideFromBottom(let animationOption):
finalFrame.origin.y = -toControllerViewFrame.size.height * 2
animateSlide(transitionContext, controller, CGPoint(x: containerController.view.center.x, y: finalFrame.origin.y), animationOption)
case .zoomIn(let scale, let animationOption):
animateScale(transitionContext, controller, scale, animationOption)
case .zoomOut(let scale, let animationOption):
animateScale(transitionContext, controller, scale, animationOption)
case .bounceFromTop(let damping, let velocity, let animationOption):
finalFrame.origin.y = toControllerViewFrame.size.height * 2
animateBounce(damping, velocity, transitionContext, controller, CGPoint(x: containerController.view.center.x, y: finalFrame.origin.y), animationOption)
case .bounceFromLeft(let damping, let velocity, let animationOption):
finalFrame.origin.x = toControllerViewFrame.size.width * 2
animateBounce(damping, velocity, transitionContext, controller, CGPoint(x: finalFrame.origin.x, y: containerController.view.center.y), animationOption)
case .bounceFromRight(let damping, let velocity, let animationOption):
finalFrame.origin.x = -toControllerViewFrame.size.width * 2
animateBounce(damping, velocity, transitionContext, controller, CGPoint(x: finalFrame.origin.x, y: containerController.view.center.y), animationOption)
case .bounceFromBottom(let damping, let velocity, let animationOption):
finalFrame.origin.y = -toControllerViewFrame.size.height * 2
animateBounce(damping, velocity, transitionContext, controller, CGPoint(x: containerController.view.center.x, y: finalFrame.origin.y), animationOption)
}
}
}
| mit | 19d2f22d731ee1b16a6de92d446a840b | 59.5625 | 232 | 0.732026 | 5.479736 | false | false | false | false |
mozilla-mobile/focus-ios | Blockzilla/Menu/Old/PhotonActionSheet.swift | 1 | 12920 | /* 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 UIKit
import SnapKit
// Ported with modifications from Firefox iOS (https://github.com/mozilla-mobile/firefox-ios)
public struct PhotonActionSheetItem {
public enum IconAlignment {
case left
case right
}
public enum TextStyle {
case normal
case subtitle
}
public private(set) var title: String
public private(set) var text: String?
public private(set) var textStyle: TextStyle
public private(set) var iconString: String?
public private(set) var iconURL: URL?
public private(set) var iconAlignment: IconAlignment
public var isEnabled: Bool
public private(set) var accessory: PhotonActionSheetCellAccessoryType
public private(set) var accessoryText: String?
public private(set) var bold: Bool = false
public private(set) var handler: ((PhotonActionSheetItem) -> Void)?
init(title: String, text: String? = nil, textStyle: TextStyle = .normal, iconString: String? = nil, iconAlignment: IconAlignment = .left, isEnabled: Bool = false, accessory: PhotonActionSheetCellAccessoryType = .None, accessoryText: String? = nil, bold: Bool? = false, handler: ((PhotonActionSheetItem) -> Void)? = nil) {
self.title = title
self.iconString = iconString
self.iconAlignment = iconAlignment
self.isEnabled = isEnabled
self.accessory = accessory
self.handler = handler
self.text = text
self.textStyle = textStyle
self.accessoryText = accessoryText
self.bold = bold ?? false
}
}
protocol PhotonActionSheetDelegate: AnyObject {
func photonActionSheetDidDismiss()
func photonActionSheetDidToggleProtection(enabled: Bool)
}
class PhotonActionSheet: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
weak var delegate: PhotonActionSheetDelegate?
private(set) var actions: [[PhotonActionSheetItem]]
private let tintColor = UIColor.grey10
private var tableView = UITableView(frame: .zero, style: .grouped)
private let titleHeaderName = "PhotonActionSheetTitleHeaderView"
lazy var tapRecognizer: UITapGestureRecognizer = {
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(dismiss))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
return tapRecognizer
}()
var photonTransitionDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.transitioningDelegate = photonTransitionDelegate
}
}
init(title: String? = nil, actions: [[PhotonActionSheetItem]]) {
self.actions = actions
super.init(nibName: nil, bundle: nil)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = .clear
view.addGestureRecognizer(tapRecognizer)
view.addSubview(tableView)
view.accessibilityIdentifier = "Action Sheet"
view.isOpaque = false
tableView.isOpaque = false
let width = UIDevice.current.userInterfaceIdiom == .pad ? 400 : 250
tableView.snp.makeConstraints { make in
make.top.bottom.equalTo(self.view)
make.width.equalTo(width)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
tableView.keyboardDismissMode = .onDrag
tableView.register(PhotonActionSheetCell.self, forCellReuseIdentifier: PhotonActionSheetCell.reuseIdentifier)
tableView.register(PhotonActionSheetSeparator.self, forHeaderFooterViewReuseIdentifier: "SeparatorSectionHeader")
tableView.register(PhotonActionSheetTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: titleHeaderName)
tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "EmptyHeader")
tableView.estimatedRowHeight = UIConstants.layout.actionSheetRowHeight
tableView.estimatedSectionFooterHeight = UIConstants.layout.actionSheetHeaderFooterHeight
tableView.estimatedSectionHeaderHeight = UIConstants.layout.actionSheetHeaderFooterHeight
tableView.isScrollEnabled = true
tableView.showsVerticalScrollIndicator = false
tableView.layer.cornerRadius = UIConstants.layout.actionSheetCornerRadius
tableView.separatorStyle = .none
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.accessibilityIdentifier = "Context Menu"
let origin = CGPoint(x: 0, y: 0)
let size = CGSize(width: tableView.frame.width, height: UIConstants.layout.actionSheetPadding)
let footer = UIView(frame: CGRect(origin: origin, size: size))
tableView.tableHeaderView = footer
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.preferredContentSize = self.tableView.contentSize
}
@objc func dismiss(_ gestureRecognizer: UIGestureRecognizer? = nil) {
delegate?.photonActionSheetDidDismiss()
self.dismiss(animated: true, completion: nil)
}
func dismissWithCallback(callback: @escaping () -> Void) {
delegate?.photonActionSheetDidDismiss()
self.dismiss(animated: true) { callback() }
}
@objc func didToggle(enabled: Bool) {
delegate?.photonActionSheetDidToggleProtection(enabled: enabled)
dismiss()
delegate?.photonActionSheetDidDismiss()
}
deinit {
tableView.dataSource = nil
tableView.delegate = nil
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if self.traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass
|| self.traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass {
updateViewConstraints()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if tableView.frame.contains(touch.location(in: self.view)) {
return false
}
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return actions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions[section].count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)
var action = actions[indexPath.section][indexPath.row]
guard let handler = action.handler else {
self.dismiss()
return
}
if action.accessory == .Switch {
action.isEnabled = !action.isEnabled
actions[indexPath.section][indexPath.row] = action
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.reloadData()
delegate?.photonActionSheetDidToggleProtection(enabled: action.isEnabled)
handler(action)
} else {
self.dismissWithCallback {
handler(action)
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PhotonActionSheetCell.reuseIdentifier, for: indexPath) as! PhotonActionSheetCell
let action = actions[indexPath.section][indexPath.row]
cell.tintColor = self.tintColor
cell.accessibilityIdentifier = action.title
if action.accessory == .Switch {
cell.actionSheet = self
}
cell.configure(with: action)
return cell
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.contentView.backgroundColor = .systemGray4
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.contentView.backgroundColor = .clear
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// If we have multiple sections show a separator for each one except the first.
if section > 0 {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: "SeparatorSectionHeader")
}
if let title = title {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: titleHeaderName) as! PhotonActionSheetTitleHeaderView
header.tintColor = self.tintColor
header.configure(with: title)
return header
}
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EmptyHeader")
return view
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EmptyHeader")
return view
}
// A height of at least 1 is required to make sure the default header size isnt used when laying out with AutoLayout
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
// A height of at least 1 is required to make sure the default footer size isnt used when laying out with AutoLayout
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
if title != nil {
return UIConstants.layout.actionSheetTitleHeaderHeight
} else {
return 1
}
default:
return UIConstants.layout.actionSheetSeparatorHeaderHeight
}
}
}
private class PhotonActionSheetTitleHeaderView: UITableViewHeaderFooterView {
static let Padding: CGFloat = 12
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = .footnote12
titleLabel.numberOfLines = 1
titleLabel.textColor = .grey10.withAlphaComponent(0.6)
return titleLabel
}()
lazy var separatorView: UIView = {
let separatorLine = UIView()
separatorLine.backgroundColor = .grey10.withAlphaComponent(0.2)
return separatorLine
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(contentView).offset(PhotonActionSheetTitleHeaderView.Padding)
make.trailing.greaterThanOrEqualTo(contentView)
make.top.equalTo(contentView).offset(UIConstants.layout.actionSheetTablePadding)
}
contentView.addSubview(separatorView)
separatorView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom).offset(UIConstants.layout.actionSheetTablePadding)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(with title: String) {
self.titleLabel.text = title
}
override func prepareForReuse() {
self.titleLabel.text = nil
}
}
private class PhotonActionSheetSeparator: UITableViewHeaderFooterView {
private let separatorLineView = UIView()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
separatorLineView.backgroundColor = .clear
contentView.backgroundColor = .grey50.withAlphaComponent(0.5)
self.contentView.addSubview(separatorLineView)
separatorLineView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.centerY.equalTo(self)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public enum PhotonActionSheetCellAccessoryType {
case Switch
case Text
case None
}
| mpl-2.0 | bffb9e4d0fcadd215cfd0c465c1e6572 | 36.888563 | 325 | 0.687616 | 5.428571 | false | false | false | false |
laszlokorte/reform-swift | ReformExpression/ReformExpression/Boolean.swift | 1 | 5481 | //
// Boolean.swift
// ExpressionEngine
//
// Created by Laszlo Korte on 07.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
func booleanBinaryOperation(_ name: String, lhs: Value, rhs: Value, op: (Bool, Bool)->Bool) -> Result<Value, EvaluationError> {
switch(lhs, rhs) {
case (.boolValue(let left), .boolValue(let right)):
return .success(Value.boolValue(value: op(left, right)))
default:
return .fail(.typeMismatch(message: "\(name) is not defined for given operands."))
}
}
struct BinaryLogicAnd : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
return booleanBinaryOperation("Logic And", lhs: lhs, rhs: rhs, op: {$0 && $1})
}
}
struct BinaryLogicOr : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
return booleanBinaryOperation("Logic Or", lhs: lhs, rhs: rhs, op: {$0 || $1})
}
}
struct UnaryLogicNegation : UnaryOperator {
func apply(_ value: Value) -> Result<Value, EvaluationError> {
switch value {
case (.boolValue(let bool)):
return .success(Value.boolValue(value: !bool))
default:
return .fail(.typeMismatch(message: "Addition is not defined for given operands."))
}
}
}
struct GreaterThanRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
switch(lhs, rhs) {
case (.intValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left > right))
case (.intValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: Double(left) > right))
case (.doubleValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left > Double(right)))
case (.doubleValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: left > right))
default:
return .fail(.typeMismatch(message: "GreaterThanRelation is not defined for given operands."))
}
}
}
struct LessThanRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
switch(lhs, rhs) {
case (.intValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left < right))
case (.intValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: Double(left) < right))
case (.doubleValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left < Double(right)))
case (.doubleValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: left < right))
default:
return .fail(.typeMismatch(message: "LessThanRelation is not defined for given operands."))
}
}
}
struct GreaterThanOrEqualRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
switch(lhs, rhs) {
case (.intValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left >= right))
case (.intValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: Double(left) >= right))
case (.doubleValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left >= Double(right)))
case (.doubleValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: left >= right))
default:
return .fail(.typeMismatch(message: "GreaterThanOrEqualRelation is not defined for given operands."))
}
}
}
struct LessThanOrEqualRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
switch(lhs, rhs) {
case (.intValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left <= right))
case (.intValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: Double(left) <= right))
case (.doubleValue(let left), .intValue(let right)):
return .success(Value.boolValue(value: left <= Double(right)))
case (.doubleValue(let left), .doubleValue(let right)):
return .success(Value.boolValue(value: left <= right))
default:
return .fail(.typeMismatch(message: "LessThanOrEqualRelation is not defined for given operands."))
}
}
}
struct StrictEqualRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
return .success(Value.boolValue(value: lhs == rhs))
}
}
struct StrictNotEqualRelation : BinaryOperator {
func apply(_ lhs: Value, rhs: Value) -> Result<Value, EvaluationError> {
return .success(Value.boolValue(value: lhs != rhs))
}
}
| mit | 38f1fa7b67fbc2d57198e3e5bd61a2a8 | 32.414634 | 127 | 0.578285 | 4.667802 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/mandatory_conditional_compile_out_using_optionals.swift | 28 | 5129 | // RUN: %target-swift-frontend -emit-sil -Onone %s | %FileCheck %s
// This file contains test cases that shows that we can properly conditional
// compile out code in -Onone contexts using transparent. It is important to
// note that all test cases here should have _BOTH_ generic and concrete
// implementations. Users should be able to depend on this in simple transparent
// cases.
//
// The first check, makes sure our silgen codegen is as we expect it. The second
// makes sure we optimize is as expected.
enum MyEnum {
case first
case second
}
@_cdecl("cFuncOriginal")
@inline(never)
func cFuncOriginal() -> () {}
@_cdecl("cFuncRefinement")
@inline(never)
func cFuncRefinement() -> () {}
class Klass {
final var value: MyEnum = .first
}
protocol OriginalProtocol {
var value: Optional<Klass> { get }
}
extension OriginalProtocol {
@_transparent
var value: Optional<Klass> {
cFuncOriginal()
return nil
}
}
protocol RefinementProtocol : OriginalProtocol {
var klass: Klass { get }
var value: Optional<Klass> { get }
}
extension RefinementProtocol {
@_transparent
var value: Optional<Klass> {
cFuncRefinement()
return klass
}
}
struct OriginalProtocolImpl {}
extension OriginalProtocolImpl : OriginalProtocol {}
struct RefinementProtocolImpl {
private var _klass: Klass = Klass()
@_transparent var klass: Klass { return _klass }
}
extension RefinementProtocolImpl : RefinementProtocol {}
@_transparent
func transparentAddressCallee<T : OriginalProtocol>(_ t: T) -> MyEnum {
if let x = t.value {
return x.value
}
return .second
}
// CHECK-LABEL: sil hidden @$s49mandatory_conditional_compile_out_using_optionals24testOriginalProtocolImplAA6MyEnumOyF : $@convention(thin) () -> MyEnum {
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK: [[FUNCTION_REF:%.*]] = function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK-NEXT: apply [[FUNCTION_REF]]()
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK: } // end sil function '$s49mandatory_conditional_compile_out_using_optionals24testOriginalProtocolImplAA6MyEnumOyF'
func testOriginalProtocolImpl() -> MyEnum {
let x = OriginalProtocolImpl()
return transparentAddressCallee(x)
}
// CHECK-LABEL: sil hidden @$s49mandatory_conditional_compile_out_using_optionals26testRefinementProtocolImplAA6MyEnumOyF : $@convention(thin) () -> MyEnum {
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK: [[FUNCTION_REF:%.*]] = function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK-NEXT: apply [[FUNCTION_REF]]()
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK: } // end sil function '$s49mandatory_conditional_compile_out_using_optionals26testRefinementProtocolImplAA6MyEnumOyF'
func testRefinementProtocolImpl() -> MyEnum {
let x = RefinementProtocolImpl()
return transparentAddressCallee(x)
}
@_transparent
func transparentObjectCallee<T : OriginalProtocol>(_ t: T) -> MyEnum where T : AnyObject {
if let x = t.value {
return x.value
}
return .second
}
class OriginalProtocolImplKlass {
}
extension OriginalProtocolImplKlass : OriginalProtocol {
}
class RefinementProtocolImplKlass {
}
extension RefinementProtocolImplKlass : RefinementProtocol {
var klass: Klass {
return Klass()
}
}
// CHECK-LABEL: sil hidden @$s49mandatory_conditional_compile_out_using_optionals29testOriginalProtocolImplKlassAA6MyEnumOyF : $@convention(thin) () -> MyEnum {
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK: [[FUNCTION_REF:%.*]] = function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK-NEXT: apply [[FUNCTION_REF]]()
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK: } // end sil function '$s49mandatory_conditional_compile_out_using_optionals29testOriginalProtocolImplKlassAA6MyEnumOyF'
func testOriginalProtocolImplKlass() -> MyEnum {
let x = OriginalProtocolImplKlass()
return transparentObjectCallee(x)
}
// CHECK-LABEL: sil hidden @$s49mandatory_conditional_compile_out_using_optionals31testRefinementProtocolImplKlassAA6MyEnumOyF : $@convention(thin) () -> MyEnum {
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK: [[FUNCTION_REF:%.*]] = function_ref @$s49mandatory_conditional_compile_out_using_optionals15cFuncRefinementyyF :
// CHECK-NEXT: apply [[FUNCTION_REF]]()
// CHECK-NOT: function_ref @$s49mandatory_conditional_compile_out_using_optionals13cFuncOriginalyyF :
// CHECK: } // end sil function '$s49mandatory_conditional_compile_out_using_optionals31testRefinementProtocolImplKlassAA6MyEnumOyF'
func testRefinementProtocolImplKlass() -> MyEnum {
let x = RefinementProtocolImplKlass()
return transparentObjectCallee(x)
}
| apache-2.0 | 7fc6990cf73822e09a97eb74853d8d80 | 37.276119 | 162 | 0.765061 | 3.833333 | false | true | false | false |
TheBrewery/Hikes | WorldHeritage/Extensions/UIImage+Icons.swift | 1 | 1655 | //
// UIImage+Icons.swift
// World Heritage
//
// Created by James Hildensperger on 3/1/16.
// Copyright © 2016 The Brewery. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
class func imageWithIcon(icon: Ionic, fontSize: CGFloat, color: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.clearColor()) -> UIImage {
return imageWithString(icon.rawValue, font: UIFont.ionicFontOfSize(fontSize), color: color, backgroundColor: backgroundColor)
}
private class func imageWithString(iconString: String, font: UIFont, color: UIColor, backgroundColor: UIColor) -> UIImage {
let size = CGSize(width: font.pointSize, height: font.pointSize)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let textRect = CGRect(origin: CGPointZero, size: size)
//// Retangle Drawing
let path = UIBezierPath(roundedRect: textRect, cornerRadius: font.pointSize/2.0)
backgroundColor.setFill()
path.fill()
color.setFill()
let mutableParagraphStyle = NSMutableParagraphStyle()
mutableParagraphStyle.alignment = NSTextAlignment.Center
let textAttributes = [NSFontAttributeName : font,
NSForegroundColorAttributeName : color,
NSBackgroundColorAttributeName : backgroundColor,
NSParagraphStyleAttributeName: mutableParagraphStyle]
(iconString as NSString).drawInRect(textRect, withAttributes: textAttributes)
//Image returns
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit | 30b72e7cc95aaed672d29223676da553 | 35.755556 | 161 | 0.704353 | 5.318328 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.