repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BasqueVoIPMafia/cordova-plugin-iosrtc
refs/heads/master
src/PluginRTCTypes.swift
mit
3
struct PluginRTCTypes { static let signalingStates = [ RTCSignalingState.stable.rawValue: "stable", RTCSignalingState.haveLocalOffer.rawValue: "have-local-offer", RTCSignalingState.haveLocalPrAnswer.rawValue: "have-local-pranswer", RTCSignalingState.haveRemoteOffer.rawValue: "have-remote-offer", RTCSignalingState.haveRemotePrAnswer.rawValue: "have-remote-pranswer", RTCSignalingState.closed.rawValue: "closed" ] static let iceGatheringStates = [ RTCIceGatheringState.new.rawValue: "new", RTCIceGatheringState.gathering.rawValue: "gathering", RTCIceGatheringState.complete.rawValue: "complete" ] static let iceConnectionStates = [ RTCIceConnectionState.new.rawValue: "new", RTCIceConnectionState.checking.rawValue: "checking", RTCIceConnectionState.connected.rawValue: "connected", RTCIceConnectionState.completed.rawValue: "completed", RTCIceConnectionState.failed.rawValue: "failed", RTCIceConnectionState.disconnected.rawValue: "disconnected", RTCIceConnectionState.closed.rawValue: "closed" ] static let dataChannelStates = [ RTCDataChannelState.connecting.rawValue: "connecting", RTCDataChannelState.open.rawValue: "open", RTCDataChannelState.closing.rawValue: "closing", RTCDataChannelState.closed.rawValue: "closed" ] static let mediaStreamTrackStates = [ RTCMediaStreamTrackState.live.rawValue: "live", RTCMediaStreamTrackState.ended.rawValue: "ended" ] }
16323e85605ce131b90d2f480c5c77a9
38.410256
72
0.738452
false
false
false
false
NinjaIshere/GKGraphKit
refs/heads/master
GKGraphKit/GKManagedEntity.swift
agpl-3.0
1
/** * Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program located at the root of the software package * in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. * * GKManagedEntity * * Represents an Entity Model Object in the persistent layer. */ import CoreData @objc(GKManagedEntity) internal class GKManagedEntity: GKManagedNode { @NSManaged internal var actionSubjectSet: NSSet @NSManaged internal var actionObjectSet: NSSet @NSManaged internal var bondSubjectSet: NSSet @NSManaged internal var bondObjectSet: NSSet /** * entityDescription * Class method returning an NSEntityDescription Object for this Model Object. * @return NSEntityDescription! */ class func entityDescription() -> NSEntityDescription! { let graph: GKGraph = GKGraph() return NSEntityDescription.entityForName(GKGraphUtility.entityDescriptionName, inManagedObjectContext: graph.managedObjectContext) } /** * init * Initializes the Model Object with e a given type. * @param type: String! */ convenience internal init(type: String!) { let graph: GKGraph = GKGraph() let entitiDescription: NSEntityDescription! = NSEntityDescription.entityForName(GKGraphUtility.entityDescriptionName, inManagedObjectContext: graph.managedObjectContext) self.init(entity: entitiDescription, managedObjectContext: graph.managedObjectContext) nodeClass = "GKEntity" self.type = type actionSubjectSet = NSSet() actionObjectSet = NSSet() bondSubjectSet = NSSet() bondObjectSet = NSSet() } /** * properties[ ] * Allows for Dictionary style coding, which maps to the internal properties Dictionary. * @param name: String! * get Returns the property name value. * set Value for the property name. */ override internal subscript(name: String) -> AnyObject? { get { for node in propertySet { let property: GKEntityProperty = node as GKEntityProperty if name == property.name { return property.value } } return nil } set(value) { for node in propertySet { let property: GKEntityProperty = node as GKEntityProperty if name == property.name { if nil == value { propertySet.removeObject(property) managedObjectContext!.deleteObject(property) } else { property.value = value! } return } } if nil != value { var property: GKEntityProperty = GKEntityProperty(name: name, value: value, managedObjectContext: managedObjectContext) property.node = self propertySet.addObject(property) } } } /** * addGroup * Adds a Group name to the list of Groups if it does not exist. * @param name: String! * @return Bool of the result, true if added, false otherwise. */ override internal func addGroup(name: String!) -> Bool { if !hasGroup(name) { var group: GKEntityGroup = GKEntityGroup(name: name, managedObjectContext: managedObjectContext!) group.node = self groupSet.addObject(group) return true } return false } /** * hasGroup * Checks whether the Node is a part of the Group name passed or not. * @param name: String! * @return Bool of the result, true if is a part, false otherwise. */ override internal func hasGroup(name: String!) -> Bool { for node in groupSet { let group: GKEntityGroup = node as GKEntityGroup if name == group.name { return true } } return false } /** * removeGroup * Removes a Group name from the list of Groups if it exists. * @param name: String! * @return Bool of the result, true if exists, false otherwise. */ override internal func removeGroup(name: String!) -> Bool { for node in groupSet { let group: GKEntityGroup = node as GKEntityGroup if name == group.name { groupSet.removeObject(group) managedObjectContext!.deleteObject(group) return true } } return false } /** * delete * Marks the Model Object to be deleted from the Graph. */ internal func delete() { var nodes: NSMutableSet = actionSubjectSet as NSMutableSet for node in nodes { nodes.removeObject(node) } nodes = actionObjectSet as NSMutableSet for node in nodes { nodes.removeObject(node) } nodes = propertySet as NSMutableSet for node in nodes { nodes.removeObject(node) managedObjectContext!.deleteObject(node as GKEntityProperty) } nodes = groupSet as NSMutableSet for node in nodes { nodes.removeObject(node) managedObjectContext!.deleteObject(node as GKEntityGroup) } managedObjectContext!.deleteObject(self) } } /** * An extension used to handle the many-to-many relationship with Actions. */ extension GKManagedEntity { /** * addActionSubjectSetObject * Adds the Action to the actionSubjectSet for the Entity. * @param value: GKManagedAction */ func addActionSubjectSetObject(value: GKManagedAction) { let nodes: NSMutableSet = actionSubjectSet as NSMutableSet nodes.addObject(value) } /** * removeActionSubjectSetObject * Removes the Action to the actionSubjectSet for the Entity. * @param value: GKManagedAction */ func removeActionSubjectSetObject(value: GKManagedAction) { let nodes: NSMutableSet = actionSubjectSet as NSMutableSet nodes.removeObject(value) } /** * addActionObjectSetObject * Adds the Action to the actionObjectSet for the Entity. * @param value: GKManagedAction */ func addActionObjectSetObject(value: GKManagedAction) { let nodes: NSMutableSet = actionObjectSet as NSMutableSet nodes.addObject(value) } /** * removeActionObjectSetObject * Removes the Action to the actionObjectSet for the Entity. * @param value: GKManagedAction */ func removeActionObjectSetObject(value: GKManagedAction) { let nodes: NSMutableSet = actionObjectSet as NSMutableSet nodes.removeObject(value) } } /** * An extension used to handle the many-to-many relationship with Bonds. */ extension GKManagedEntity { /** * addBondSubjectSetObject * Adds the Bond to the bondSubjectSet for the Entity. * @param value: GKManagedBond */ func addBondSubjectSetObject(value: GKManagedBond) { let nodes: NSMutableSet = bondSubjectSet as NSMutableSet nodes.addObject(value) } /** * removeBondSubjectSetObject * Removes the Bond to the bondSubjectSet for the Entity. * @param value: GKManagedBond */ func removeBondSubjectSetObject(value: GKManagedBond) { let nodes: NSMutableSet = bondSubjectSet as NSMutableSet nodes.removeObject(value) } /** * addBondObjectSetObject * Adds the Bond to the bondObjectSet for the Entity. * @param value: GKManagedBond */ func addBondObjectSetObject(value: GKManagedBond) { let nodes: NSMutableSet = bondObjectSet as NSMutableSet nodes.addObject(value) } /** * removeBondObjectSetObject * Removes the Bond to the bondObjectSet for the Entity. * @param value: GKManagedBond */ func removeBondObjectSetObject(value: GKManagedBond) { let nodes: NSMutableSet = bondObjectSet as NSMutableSet nodes.removeObject(value) } }
03e7c058fbb800126a42b7d95a9a8200
32.162879
177
0.636052
false
false
false
false
apple/swift-nio-http2
refs/heads/main
IntegrationTests/tests_01_allocation_counters/test_01_resources/test_1k_requests.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOEmbedded import NIOHPACK import NIOHTTP2 struct ServerOnly1KRequestsBenchmark { private let concurrentStreams: Int private let channel: EmbeddedChannel // This offset is preserved across runs. var streamID = HTTP2StreamID(1) // A manually constructed data frame. private var dataFrame: ByteBuffer = { var buffer = ByteBuffer(repeating: 0xff, count: 1024 + 9) // UInt24 length, is 1024 bytes. buffer.setInteger(UInt8(0), at: buffer.readerIndex) buffer.setInteger(UInt16(1024), at: buffer.readerIndex + 1) // Type buffer.setInteger(UInt8(0x00), at: buffer.readerIndex + 3) // Flags, turn on end-stream. buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 4) // 4 byte stream identifier, set to zero for now as we update it later. buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5) return buffer }() // A manually constructed headers frame. private var headersFrame: ByteBuffer = { var headers = HPACKHeaders() headers.add(name: ":method", value: "GET", indexing: .indexable) headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable) headers.add(name: ":path", value: "/", indexing: .indexable) headers.add(name: ":scheme", value: "https", indexing: .indexable) headers.add(name: "user-agent", value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", indexing: .nonIndexable) headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable) var hpackEncoder = HPACKEncoder(allocator: .init()) var buffer = ByteBuffer() buffer.writeRepeatingByte(0, count: 9) buffer.moveReaderIndex(forwardBy: 9) try! hpackEncoder.encode(headers: headers, to: &buffer) let encodedLength = buffer.readableBytes buffer.moveReaderIndex(to: buffer.readerIndex - 9) // UInt24 length buffer.setInteger(UInt8(0), at: buffer.readerIndex) buffer.setInteger(UInt16(encodedLength), at: buffer.readerIndex + 1) // Type buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 3) // Flags, turn on END_HEADERs. buffer.setInteger(UInt8(0x04), at: buffer.readerIndex + 4) // 4 byte stream identifier, set to zero for now as we update it later. buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5) return buffer }() private let emptySettings: ByteBuffer = { var buffer = ByteBuffer() buffer.reserveCapacity(9) // UInt24 length, is 0 bytes. buffer.writeInteger(UInt8(0)) buffer.writeInteger(UInt16(0)) // Type buffer.writeInteger(UInt8(0x04)) // Flags, none. buffer.writeInteger(UInt8(0x00)) // 4 byte stream identifier, set to zero. buffer.writeInteger(UInt32(0)) return buffer }() private var settingsACK: ByteBuffer { // Copy the empty SETTINGS and add the ACK flag var settingsCopy = self.emptySettings settingsCopy.setInteger(UInt8(0x01), at: settingsCopy.readerIndex + 4) return settingsCopy } init(concurrentStreams: Int) throws { self.concurrentStreams = concurrentStreams self.channel = EmbeddedChannel() _ = try self.channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in return streamChannel.pipeline.addHandler(TestServer()) }.wait() try self.channel.connect(to: .init(unixDomainSocketPath: "/fake"), promise: nil) // Gotta do the handshake here. var initialBytes = ByteBuffer(string: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") initialBytes.writeImmutableBuffer(self.emptySettings) initialBytes.writeImmutableBuffer(self.settingsACK) try self.channel.writeInbound(initialBytes) while try self.channel.readOutbound(as: ByteBuffer.self) != nil { } } func tearDown() { _ = try! self.channel.finish() } mutating func run() throws -> Int { var bodyByteCount = 0 var completedIterations = 0 while completedIterations < 1_000 { bodyByteCount &+= try self.sendInterleavedRequests(self.concurrentStreams) completedIterations += self.concurrentStreams } return bodyByteCount } private mutating func sendInterleavedRequests(_ interleavedRequests: Int) throws -> Int { var streamID = self.streamID for _ in 0 ..< interleavedRequests { self.headersFrame.setInteger(UInt32(Int32(streamID)), at: self.headersFrame.readerIndex + 5) try self.channel.writeInbound(self.headersFrame) streamID = streamID.advanced(by: 2) } streamID = self.streamID for _ in 0 ..< interleavedRequests { self.dataFrame.setInteger(UInt32(Int32(streamID)), at: self.dataFrame.readerIndex + 5) try self.channel.writeInbound(self.dataFrame) streamID = streamID.advanced(by: 2) } self.channel.embeddedEventLoop.run() self.streamID = streamID var count = 0 while let data = try self.channel.readOutbound(as: ByteBuffer.self) { count &+= data.readableBytes self.channel.embeddedEventLoop.run() } return count } } fileprivate class TestServer: ChannelInboundHandler { public typealias InboundIn = HTTP2Frame.FramePayload public typealias OutboundOut = HTTP2Frame.FramePayload public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let payload = self.unwrapInboundIn(data) switch payload { case .headers(let headers) where headers.endStream: self.sendResponse(context: context) case .data(let data) where data.endStream: self.sendResponse(context: context) default: () } } private func sendResponse(context: ChannelHandlerContext) { let responseHeaders = HPACKHeaders([(":status", "200"), ("server", "test-benchmark")]) let response = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: false)) let responseData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(ByteBuffer()), endStream: true)) context.write(self.wrapOutboundOut(response), promise: nil) context.writeAndFlush(self.wrapOutboundOut(responseData), promise: nil) } } func run(identifier: String) { var interleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 100) measure(identifier: identifier + "_interleaved") { return try! interleaved.run() } interleaved.tearDown() var noninterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 1) measure(identifier: identifier + "_noninterleaved") { return try! noninterleaved.run() } noninterleaved.tearDown() }
4cfe4907f1383eaa75910ecc254f8073
34.296296
145
0.641396
false
false
false
false
rokuz/omim
refs/heads/master
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewStatus/BaseRoutePreviewStatus.swift
apache-2.0
1
@objc(MWMBaseRoutePreviewStatus) final class BaseRoutePreviewStatus: SolidTouchView { @IBOutlet private weak var errorBox: UIView! @IBOutlet private weak var resultsBox: UIView! @IBOutlet private weak var heightBox: UIView! @IBOutlet private weak var manageRouteBox: UIView! @IBOutlet weak var manageRouteBoxBackground: UIView! { didSet { iPhoneSpecific { manageRouteBoxBackground.backgroundColor = UIColor.blackOpaque() } } } @IBOutlet private weak var taxiBox: UIView! @IBOutlet private weak var errorLabel: UILabel! @IBOutlet private weak var resultLabel: UILabel! @IBOutlet private weak var arriveLabel: UILabel? @IBOutlet private weak var heightProfileImage: UIImageView! @IBOutlet private weak var heightProfileElevationHeight: UILabel? @IBOutlet private weak var manageRouteButtonRegular: UIButton! { didSet { configManageRouteButton(manageRouteButtonRegular) } } @IBOutlet private weak var manageRouteButtonCompact: UIButton? { didSet { configManageRouteButton(manageRouteButtonCompact!) } } @IBOutlet private var errorBoxBottom: NSLayoutConstraint! @IBOutlet private var resultsBoxBottom: NSLayoutConstraint! @IBOutlet private var heightBoxBottom: NSLayoutConstraint! @IBOutlet private var taxiBoxBottom: NSLayoutConstraint! @IBOutlet private var manageRouteBoxBottom: NSLayoutConstraint! @IBOutlet private var heightBoxBottomManageRouteBoxTop: NSLayoutConstraint! private var hiddenConstraint: NSLayoutConstraint! @objc weak var ownerView: UIView! weak var navigationInfo: MWMNavigationDashboardEntity? var elevation: NSAttributedString? { didSet { guard let elevation = elevation else { return } alternative(iPhone: { self.updateResultsLabel() }, iPad: { self.heightProfileElevationHeight?.attributedText = elevation })() } } private var isVisible = false { didSet { alternative(iPhone: { guard self.isVisible != oldValue else { return } if self.isVisible { self.addView() } DispatchQueue.main.async { guard let sv = self.superview else { return } sv.animateConstraints(animations: { self.hiddenConstraint.isActive = !self.isVisible }, completion: { if !self.isVisible { self.removeFromSuperview() } }) } }, iPad: { self.isHidden = !self.isVisible })() } } private func addView() { guard superview != ownerView else { return } ownerView.addSubview(self) addConstraints() } private func addConstraints() { var lAnchor = ownerView.leadingAnchor var tAnchor = ownerView.trailingAnchor var bAnchor = ownerView.bottomAnchor if #available(iOS 11.0, *) { let layoutGuide = ownerView.safeAreaLayoutGuide lAnchor = layoutGuide.leadingAnchor tAnchor = layoutGuide.trailingAnchor bAnchor = layoutGuide.bottomAnchor } leadingAnchor.constraint(equalTo: lAnchor).isActive = true trailingAnchor.constraint(equalTo: tAnchor).isActive = true hiddenConstraint = topAnchor.constraint(equalTo: bAnchor) hiddenConstraint.priority = UILayoutPriority.defaultHigh hiddenConstraint.isActive = true let visibleConstraint = bottomAnchor.constraint(equalTo: bAnchor) visibleConstraint.priority = UILayoutPriority.defaultLow visibleConstraint.isActive = true ownerView.layoutIfNeeded() } private func updateHeight() { DispatchQueue.main.async { self.animateConstraints(animations: { self.errorBoxBottom.isActive = !self.errorBox.isHidden self.resultsBoxBottom.isActive = !self.resultsBox.isHidden self.heightBoxBottom.isActive = !self.heightBox.isHidden self.heightBoxBottomManageRouteBoxTop.isActive = !self.heightBox.isHidden self.taxiBoxBottom.isActive = !self.taxiBox.isHidden self.manageRouteBoxBottom.isActive = !self.manageRouteBox.isHidden }) } } private func configManageRouteButton(_ button: UIButton) { button.titleLabel?.font = UIFont.medium14() button.setTitle(L("planning_route_manage_route"), for: .normal) button.tintColor = UIColor.blackSecondaryText() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateManageRouteVisibility() updateHeight() } private func updateManageRouteVisibility() { let isCompact = traitCollection.verticalSizeClass == .compact manageRouteBox.isHidden = isCompact || resultsBox.isHidden manageRouteButtonCompact?.isHidden = !isCompact } @objc func hide() { isVisible = false } @objc func showError(message: String) { isVisible = true errorBox.isHidden = false resultsBox.isHidden = true heightBox.isHidden = true taxiBox.isHidden = true manageRouteBox.isHidden = true errorLabel.text = message updateHeight() } @objc func showReady() { isVisible = true errorBox.isHidden = true if MWMRouter.isTaxi() { taxiBox.isHidden = false resultsBox.isHidden = true heightBox.isHidden = true } else { taxiBox.isHidden = true resultsBox.isHidden = false self.elevation = nil if MWMRouter.hasRouteAltitude() { heightBox.isHidden = false MWMRouter.routeAltitudeImage(for: heightProfileImage.frame.size, completion: { image, elevation in self.heightProfileImage.image = image guard let elevation = elevation else { return } let attributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.linkBlue(), .font: UIFont.medium14(), ] self.elevation = NSAttributedString(string: "▲▼ \(elevation)", attributes: attributes) }) } else { heightBox.isHidden = true } } updateManageRouteVisibility() updateHeight() } private func updateResultsLabel() { guard let info = navigationInfo else { return } resultLabel.attributedText = alternative(iPhone: { let result = info.estimate.mutableCopy() as! NSMutableAttributedString if let elevation = self.elevation { result.append(info.estimateDot) result.append(elevation) } return result.copy() as? NSAttributedString }, iPad: { info.estimate })() } @objc func onNavigationInfoUpdated(_ info: MWMNavigationDashboardEntity) { navigationInfo = info updateResultsLabel() arriveLabel?.text = String(coreFormat: L("routing_arrive"), arguments: [info.arrival]) } override var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } }
b73ad4e1affd0e3c72248abc2d62781a
32.848624
125
0.676514
false
false
false
false
shridharmalimca/LocationTracking
refs/heads/master
LocationTracking/LocationTracking/CoreDataService.swift
apache-2.0
3
import CoreData protocol CoreDataServiceProtocol:class { var errorHandler: (Error) -> Void {get set} var persistentContainer: NSPersistentContainer {get} var mainContext: NSManagedObjectContext {get} var backgroundContext: NSManagedObjectContext {get} func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) } final class CoreDataService: CoreDataServiceProtocol { static let shared = CoreDataService() var errorHandler: (Error) -> Void = {_ in } lazy var persistentContainer: NSPersistentContainer = { let container = PersistentContainer(name: "LocationTracking") if let fileLocation = container.persistentStoreDescriptions[0].url?.absoluteString { print("Core Database file location : \n\t \(fileLocation).") } container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in if let error = error { self?.errorHandler(error) } }) return container }() lazy var mainContext: NSManagedObjectContext = { return self.persistentContainer.viewContext }() lazy var backgroundContext: NSManagedObjectContext = { return self.persistentContainer.newBackgroundContext() }() func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { self.mainContext.perform { block(self.mainContext) } } func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { self.persistentContainer.performBackgroundTask(block) } func saveContext() { let backgrounndContext = backgroundContext if backgrounndContext.hasChanges { do { try backgrounndContext.save() } catch let error as NSError { fatalError("Unresolved error \(error), \(error.userInfo)") } } } }
fe3e22d7dab996b75586f238bcebde98
33.262295
99
0.646411
false
false
false
false
haranicle/AlcatrazTour
refs/heads/master
AlcatrazTour/PluginTableViewController.swift
mit
1
// // PluginListMainViewController // AlcatrazTour // // Copyright (c) 2015年 haranicle. All rights reserved. // import UIKit import Realm let PluginCellReuseIdentifier = "Cell" enum Modes:Int { case Popularity = 0 case Stars = 1 case Update = 2 case New = 3 func toIcon() -> String { switch self { case Modes.Popularity: return "\u{f004}" case Modes.Stars: return "\u{f005}" case Modes.Update: return "\u{f021}" case Modes.New: return "\u{f135}" default: return "" } } func toString() -> String { switch self { case Modes.Popularity: return "Popularity" case Modes.Stars: return "Stars" case Modes.Update: return "Update" case Modes.New: return "New" default: return "" } } func propertyName() -> String { switch self { case Modes.Popularity: return "score" case Modes.Stars: return "starGazersCount" case Modes.Update: return "updatedAt" case Modes.New: return "createdAt" default: return "" } } } class PluginTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate { @IBOutlet weak var settingsButton: UIBarButtonItem! var githubClient = GithubClient() var currentMode = Modes.Popularity let segments = [Modes.Popularity, Modes.Stars, Modes.Update, Modes.New] override func viewDidLoad() { super.viewDidLoad() registerTableViewCellNib(self.tableView) // settings button let settingsAttributes = [NSFontAttributeName:UIFont(name: "FontAwesome", size: 24)!] settingsButton.setTitleTextAttributes(settingsAttributes, forState: UIControlState.Normal) settingsButton.title = "\u{f013}" // notification center NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: nil) // segmented control let attributes = [NSFontAttributeName:UIFont(name: "FontAwesome", size: 10)!] segmentedControl.setTitleTextAttributes(attributes, forState: UIControlState.Normal) // search controller configureSearchController() // hide search bar if githubClient.isSignedIn() { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) } for i in 0 ..< segments.count { let mode = segments[i] segmentedControl.setTitle("\(mode.toIcon()) \(mode.toString())", forSegmentAtIndex: i) } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewWillAppear(animated: Bool) { navigationController?.toolbarHidden = true } func onApplicationDidBecomeActive(notification:NSNotification) { if !githubClient.isSignedIn() { showSignInAlert() } } // MARK: - Search Controller let searchResultTableViewController = UITableViewController() var searchController:UISearchController? func configureSearchController() { searchController = UISearchController(searchResultsController: searchResultTableViewController) searchController!.searchResultsUpdater = self searchController!.delegate = self searchController!.searchBar.sizeToFit() tableView.tableHeaderView = searchController!.searchBar searchResultTableViewController.tableView.delegate = self searchResultTableViewController.tableView.dataSource = self registerTableViewCellNib(searchResultTableViewController.tableView) searchResultTableViewController.tableView.tableHeaderView = nil // https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html // Search is now just presenting a view controller. As such, normal view controller // presentation semantics apply. Namely that presentation will walk up the view controller // hierarchy until it finds the root view controller or one that defines a presentation context. definesPresentationContext = true // know where you want UISearchController to be displayed } // MARK: - UISearchResultsUpdating func updateSearchResultsForSearchController(searchController: UISearchController) { let searchText = searchController.searchBar.text // TODO: Must be tested here!! searchResults = Plugin.objectsWhere("name contains[c] '\(searchText)' OR note contains[c] '\(searchText)'").sortedResultsUsingProperty(currentMode.propertyName(), ascending: false) searchResultTableViewController.tableView.reloadData() } // MARK: - Realm var searchResults:RLMResults? var popularityResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Popularity.propertyName(), ascending: false) var starsResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Stars.propertyName(), ascending: false) var updateResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Update.propertyName(), ascending: false) var newResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.New.propertyName(), ascending: false) func currentResult()->RLMResults { if searchController!.active { return searchResults! } switch currentMode { case Modes.Popularity: return popularityResults case Modes.Stars: return starsResults case Modes.Update: return updateResults case Modes.New: return newResults } } // MARK: - UI Parts @IBOutlet weak var segmentedControl: UISegmentedControl! // MARK: - Action @IBAction func onSegmentChanged(sender: UISegmentedControl) { currentMode = Modes(rawValue: sender.selectedSegmentIndex)! tableView.reloadData() tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) } @IBAction func onRefreshPushed(sender: AnyObject) { if !githubClient.isSignedIn() { showSignInAlert() return } if !tableView.decelerating { self.reloadAllPlugins() } } // MARK: - Sign in var signInAlert:UIAlertController? func showSignInAlert() { signInAlert = UIAlertController(title: "Sign in", message: "Please, sign in github to get repository data.", preferredStyle: UIAlertControllerStyle.Alert) signInAlert!.addAction(UIAlertAction(title: "Sign in", style: UIAlertActionStyle.Default, handler: {[weak self] action in self?.signIn() self?.signInAlert?.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(signInAlert!, animated: true, completion: nil) } func signIn() { githubClient.requestOAuth({[weak self] in self?.signInAlert?.dismissViewControllerAnimated(true, completion: nil) self?.reloadAllPlugins() }, onFailed: {[weak self] error in // login failed. quit app. let errorAlert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert) errorAlert.addAction(UIAlertAction(title: "Quit app", style: UIAlertActionStyle.Default, handler:{action in exit(0)} )) self?.presentViewController(errorAlert, animated: true, completion: nil) }) } // MARK: - Reload data func reloadAllPlugins() { autoreleasepool{ self.githubClient.reloadAllPlugins({[weak self] (error:NSError?) in if let err = error { self?.showErrorAlert(err) } self?.tableView.reloadData() }) } } // MARK: - Table View Data Source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Int(currentResult().count) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let plugin = currentResult()[UInt(indexPath.row)] as! Plugin let cell = tableView.dequeueReusableCellWithIdentifier(PluginCellReuseIdentifier) as! PluginTableViewCell configureCell(cell, plugin: plugin, indexPath: indexPath) return cell } // MARK: - TableView Delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let selectedPlugin = currentResult()[UInt(indexPath.row)] as! Plugin let webViewController = PluginDetailWebViewController(plugin: selectedPlugin) navigationController?.pushViewController(webViewController, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } // MARK: - UISearchControllerDelegate func didDismissSearchController(searchController: UISearchController) { tableView.reloadData() } // MARK: - Cell func configureCell(cell:PluginTableViewCell, plugin:Plugin, indexPath:NSIndexPath) { cell.rankingLabel.text = "\(indexPath.row + 1)" cell.titleLabel.text = plugin.name cell.noteLabel.text = plugin.note cell.avaterImageView.sd_setImageWithURL(NSURL(string: plugin.avaterUrl)) cell.statusLabel.text = "\(Modes.Popularity.toIcon()) \(plugin.scoreAsString()) \(Modes.Stars.toIcon()) \(plugin.starGazersCount) \(Modes.Update.toIcon()) \(plugin.updatedAtAsString()) \(Modes.New.toIcon()) \(plugin.createdAtAsString())" } func registerTableViewCellNib(tableView:UITableView) { let nib = UINib(nibName: "PluginTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: PluginCellReuseIdentifier) } // MARK: - Error func showErrorAlert(error:NSError) { let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } // MARK: - Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "settings" { let settingsNavigationController = segue.destinationViewController as! UINavigationController let settingTableViewController = settingsNavigationController.childViewControllers[0] as! SettingsTableViewController settingTableViewController.githubClient = githubClient } } }
56b7dc6d2209efe98e97fb2a763440fa
38.197917
245
0.670712
false
false
false
false
JonahStarling/GlanceiOS
refs/heads/master
Glance/Friend.swift
mit
1
// // Friend.swift // Glance // // Created by Jonah Starling on 4/14/16. // Copyright © 2016 In The Belly. All rights reserved. // import Foundation class Friend { var friendType: String var userName: String var userId: String var userHandle: String var userPic: String // Default Initializer init() { self.friendType = "" self.userName = "User" self.userId = "" self.userHandle = "@User" self.userPic = "" } // Full Initializer init(friendType: String, userName: String, userId: String, userHandle: String, userPic: String) { self.friendType = friendType if (userName == "") { self.userName = userHandle } else { self.userName = userName } self.userId = userId self.userHandle = "@"+userHandle self.userPic = userPic } // Get Functions func getFriendType() -> String { return self.friendType } func getUserName() -> String { return self.userName } func getUserId() -> String { return self.userId } func getUserHandle() -> String { return self.userHandle } func getUserPic() -> String { return self.userPic } // Set Functions func setFriendType(friendType: String) { self.friendType = friendType } func setUserName(userName: String) { self.userName = userName } func setUserId(userId: String) { self.userId = userId } func setUserHandle(userHandle: String) { self.userHandle = userHandle } func setUserPic(userPic: String) { self.userPic = userPic } }
034f4d01a8969358391f85c7abdfc87e
29
101
0.621775
false
false
false
false
dongdongSwift/guoke
refs/heads/master
gouke/果壳/Protocol.swift
mit
1
// // Protocol.swift // 果壳 // // Created by qianfeng on 2016/10/25. // Copyright © 2016年 张冬. All rights reserved. // import UIKit import MJRefresh enum BarButtonPosition { case left case right } protocol addRefreshProtocol:NSObjectProtocol { func addRefresh(header:(()->())?,footer:(()->())?) } protocol NavigationProtocol:NSObjectProtocol { func addTitle(title:String) func addBarButton(title:String?,imageName:String?,bgImageName:String?,postion:BarButtonPosition,select:Selector) } extension addRefreshProtocol where Self:UITableViewController{ func addRefresh(header:(()->())?=nil,footer:(()->())?=nil){ if header != nil{ tableView.mj_header=MJRefreshNormalHeader(refreshingBlock: header) } if footer != nil{ tableView.mj_footer=MJRefreshAutoNormalFooter(refreshingBlock: footer) } } } extension NavigationProtocol where Self:UIViewController{ func addTitle(title:String){ let label=UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 44)) label.text=title label.font=UIFont.boldSystemFontOfSize(20) label.textColor=UIColor.whiteColor() label.textAlignment = .Center navigationItem.titleView=label } func addBarButton(title:String?=nil,imageName:String?=nil,bgImageName:String?=nil,postion:BarButtonPosition,select:Selector){ let button=UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 44)) if title != nil{ button.setTitle(title, forState: .Normal) } if imageName != nil { button.setImage(UIImage(named: imageName!), forState: .Normal) } if bgImageName != nil{ button.setBackgroundImage(UIImage(named:bgImageName!) , forState: .Normal) } button.setTitleColor(UIColor.blackColor(), forState: .Normal) button.setTitleColor(UIColor.grayColor(), forState: .Highlighted) button.addTarget(self, action: select, forControlEvents: .TouchUpInside) let barButtonItem=UIBarButtonItem(customView: button) if postion == .left { if navigationItem.leftBarButtonItems != nil{ navigationItem.leftBarButtonItems=navigationItem.leftBarButtonItems!+[barButtonItem] }else{ navigationItem.leftBarButtonItems=[barButtonItem] } }else{ if navigationItem.rightBarButtonItems != nil{ navigationItem.rightBarButtonItems=navigationItem.rightBarButtonItems!+[barButtonItem] }else{ navigationItem.rightBarButtonItems=[barButtonItem] } } } }
a3e2790d40ea7ba4ce18d9817eefab74
34.328947
129
0.652142
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/AnimationResource/TransitionFirstPushViewController.swift
mit
1
// // TransitionFirstPushViewController.swift // SwiftCodeFragments // // Created by zhangmingwei on 2017/2/6. // Copyright © 2017年 SpeedX. All rights reserved. // 转场动画最简单的方法 第一页 push方式 import UIKit class TransitionFirstPushViewController: UIViewController,UIViewControllerTransitioningDelegate,UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.lightGray } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.pushAction() } // 转场动画开始 func pushAction() -> Void { let vc = TransitionSecondPushViewController() self.navigationController?.delegate = self self.navigationController?.pushViewController(vc, animated: true) } // push 动画 func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .pop: let animation = TransitionAnimation() animation.isIn = false return animation case .push: let animation = TransitionAnimation() animation.isIn = true return animation default: return nil } } }
4bbfe4eadcddf9859eea0cc32f51650e
31.170213
246
0.640873
false
false
false
false
iamrajhans/SplashiOS
refs/heads/master
SplashDemo/SplashDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // SplashDemo // // Created by Nishu on 16/10/16. // Copyright © 2016 com.drone. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let notifytypes : UIUserNotificationType = UIUserNotificationType.Alert let notifySettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notifytypes, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notifySettings) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "nishu.SplashDemo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SplashDemo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
8e64ab9b422678df6b4f4789d8aba528
54.547826
291
0.722605
false
false
false
false
Vostro162/VaporTelegram
refs/heads/master
Sources/App/MethodsAble.swift
mit
1
import Foundation /* * * The Bot API supports basic formatting for messages. You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages. * Telegram clients will render them accordingly. You can use either markdown-style or HTML-style formatting. * */ public enum ParseMode: String { case markdown = "markdown" case html = "html" } /* * Type of action to broadcast. Choose one, depending on what the user is about to receive: * typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_audio or upload_audio for audio files, upload_document for general files, * find_location for location data, record_video_note or upload_video_note for video notes. * */ public enum ChatAction: String { case typing = "typing" case uploadPhoto = "upload_photo" case recordVideo = "record_video" case uploadVideo = "upload_video" case recordAudio = "record_audio" case uploadAudio = "upload_audio" case uploadDocument = "upload_document" case findLocation = "find_location" } public protocol MethodsAble { //func setWebhook(url: URL, certificate: InputFile, maxConnections: Int, ) /* * * -------------------------------------------------- Send -------------------------------------------------- * */ // Use this method to send text messages. On success, the sent Message is returned. func sendMessage(chatId: ChatId, text: String, disableWebPagePreview: Bool, disableNotification: Bool, parseMode: ParseMode?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send photos. On success, the sent Message is returned. func sendPhoto(chatId: ChatId, photo: InputFile, fileName: String, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message func sendPhoto(chatId: ChatId, photo: URL, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. * On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. * For sending voice messages, use the sendVoice method instead. */ func sendAudio(chatId: ChatId, audio: InputFile, fileName: String, disableNotification: Bool, caption: String?, duration: Int?, performer: String?, title: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message func sendAudio(chatId: ChatId, audio: URL, disableNotification: Bool, caption: String?, duration: Int?, performer: String?, title: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. func sendDocument(chatId: ChatId, document: InputFile, fileName: String, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message func sendDocument(chatId: ChatId, document: URL, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send .webp stickers. On success, the sent Message is returned func sendSticker(chatId: ChatId, sticker: InputFile, fileName: String, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message func sendSticker(chatId: ChatId, sticker: URL, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). * On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. * */ func sendVideo(chatId: ChatId, video: InputFile, fileName: String, disableNotification: Bool, replyToMessageId: MessageId?, duration: Int?, width: Int?, height: Int?, caption: String?, replyMarkup: ReplyMarkup?) throws -> Message func sendVideo(chatId: ChatId, video: URL, disableNotification: Bool, replyToMessageId: MessageId?, duration: Int?, width: Int?, height: Int?, caption: String?, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. * For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). * On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. * */ func sendVoice(chatId: ChatId, voice: InputFile, fileName: String, disableNotification: Bool, caption: String?, duration: Int?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message func sendVoice(chatId: ChatId, voice: URL, disableNotification: Bool, caption: String?, duration: Int?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send point on the map. On success, the sent Message is returned. func sendLocation(chatId: ChatId, latitude: Float, longitude: Float, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send information about a venue. On success, the sent Message is returned. func sendVenue(chatId: ChatId, latitude: Float, longitude: Float, title: String, address: String, disableNotification: Bool, foursquareId: FoursquareId?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message // Use this method to send phone contacts. On success, the sent Message is returned. func sendContact(chatId: ChatId, phoneNumber: String, firstName: String, lastName: String, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method when you need to tell the user that something is happening on the bot's side. * The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. * * Example: * The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, * the bot may use sendChatAction with action = upload_photo. * The user will see a “sending photo” status for the bot. * */ func sendChatAction(chatId: ChatId, action: ChatAction) throws -> Bool /* * * -------------------------------------------------- Get-------------------------------------------------- * */ // A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object. func getMe() throws -> User // Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. func getUserProfilePhotos(userId: UserId, offset: Int, limit: Int) throws -> UserProfilePhotos /* * Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. * On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. * It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. * * Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. */ func getFile(fileId: FileId) throws -> File /* * * Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). * Returns a Chat object on success. * */ func getChat(chatId: ChatId) throws -> Chat /* * * Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. * If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. * */ func getChatAdministrators(chatId: ChatId) throws -> [ChatMember] // Use this method to get the number of members in a chat. Returns Int on success. func getChatMembersCount(chatId: ChatId) throws -> Int // Use this method to get information about a member of a chat. Returns a ChatMember object on success. func getChatMember(chatId: ChatId, userId: UserId) throws -> ChatMember /* * * -------------------------------------------------- Manage -------------------------------------------------- * */ /* * * Use this method to kick a user from a group, a supergroup or a channel. * In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc. , * unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. * */ func kickChatMember(chatId: ChatId, userId: UserId) throws -> Bool // Use this method to forward messages of any kind. On success, the sent Message is returned. func forwardMessage(chatId: ChatId, fromChatId: ChatId, messageId: MessageId, disableNotification: Bool) throws -> Message // Use this method for your bot to leave a group, supergroup or channel. Returns True on success. func leaveChat(chatId: ChatId, userId: UserId) throws -> Bool /* * * Use this method to unban a previously kicked user in a supergroup or channel. * The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success. * */ func unbanChatMember(chatId: ChatId, userId: UserId) throws -> Bool /* * * Use this method to send answers to callback queries sent from inline keyboards. * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. * * Alternatively, the user can be redirected to the specified Game URL. * For this option to work, you must first create a game for your bot via @Botfather and accept the terms. * Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. * */ func answerCallbackQuery(callbackQueryId: CallbackQueryId, showAlert: Bool, text: String?, url: URL?, cacheTime: Int?) throws -> Bool /* * * -------------------------------------------------- Edit -------------------------------------------------- * */ /* * Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. * */ func editMessageText(chatId: ChatId, messageId: MessageId, text: String, disableWebPagePreview: Bool, parseMode: ParseMode?, replyMarkup: ReplyMarkup?) throws -> Message func editMessageText(inlineMessageId: InlineMessageId, text: String, disableWebPagePreview: Bool, parseMode: ParseMode?, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. * */ func editMessageCaption(chatId: ChatId, messageId: MessageId, caption: String, replyMarkup: ReplyMarkup?) throws -> Message func editMessageCaption(inlineMessageId: InlineMessageId, caption: String, replyMarkup: ReplyMarkup?) throws -> Message /* * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. * */ func editMessageReplyMarkup(chatId: ChatId, messageId: MessageId, replyMarkup: ReplyMarkup?) throws -> Message func editMessageReplyMarkup(inlineMessageId: InlineMessageId, replyMarkup: ReplyMarkup?) throws -> Message /* * * Use this method to delete a message, including service messages, with the following limitations: * - A message can only be deleted if it was sent less than 48 hours ago. * - Bots can delete outgoing messages in groups and supergroups. * - Bots granted can_post_messages permissions can delete outgoing messages in channels. * - If the bot is an administrator of a group, it can delete any message there. * - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. * Returns True on success. * */ func deleteMessage(chatId: ChatId, messageId: MessageId) throws -> Bool /* * * -------------------------------------------------- Inline -------------------------------------------------- * */ func inlineQuery(id: String, from: User, query: String, offset: String, location: Location?) throws -> Bool //func answerInlineQuery(inlineQueryId: String, results: }
b6e9c2ebfc66b285bd0b800e07f32b0e
56.491935
242
0.687754
false
false
false
false
jdfergason/swift-toml
refs/heads/master
Sources/Toml/Grammar.swift
apache-2.0
1
/* * Copyright 2016-2018 JD Fergason * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation class Grammar { var grammar = [String: [Evaluator]]() init() { grammar["comment"] = commentEvaluators() grammar["string"] = stringEvaluators() grammar["literalString"] = literalStringEvaluators() grammar["multilineString"] = multiLineStringEvaluators() grammar["multilineLiteralString"] = multiLineStringLiteralEvaluators() grammar["tableName"] = tableNameEvaluators() grammar["tableArray"] = tableArrayEvaluators() grammar["value"] = valueEvaluators() grammar["array"] = arrayEvaluators() grammar["inlineTable"] = inlineTableEvaluators() grammar["root"] = rootEvaluators() } private func commentEvaluators() -> [Evaluator] { return [ Evaluator(regex: "[\r\n]", generator: { _ in nil }, pop: true), // to enable saving comments in the tokenizer use the following line // Evaluator(regex: ".*", generator: { (r: String) in .Comment(r.trim()) }, pop: true) Evaluator(regex: ".*", generator: { _ in nil }, pop: true) ] } private func stringEvaluators() -> [Evaluator] { return [ Evaluator(regex: "\"", generator: { _ in nil }, pop: true), Evaluator(regex: "([\\u0020-\\u0021\\u0023-\\u005B\\u005D-\\uFFFF]|\\\\\"|\\\\)+", generator: { (r: String) in .Identifier(try r.replaceEscapeSequences()) }) ] } private func literalStringEvaluators() -> [Evaluator] { return [ Evaluator(regex: "'", generator: { _ in nil }, pop: true), Evaluator(regex: "([\\u0020-\\u0026\\u0028-\\uFFFF])+", generator: { (r: String) in .Identifier(r) }) ] } private func multiLineStringEvaluators() -> [Evaluator] { let validUnicodeChars = "\\u0020-\\u0021\\u0023-\\uFFFF" return [ Evaluator(regex: "\"\"\"", generator: { _ in nil }, pop: true), // Note: Does not allow multi-line strings that end with double qoutes. // This is a common limitation of a variety of parsers I have tested Evaluator(regex: "([\n" + validUnicodeChars + "]\"?\"?)*[\n" + validUnicodeChars + "]+", generator: { (r: String) in .Identifier(try r.trim().stripLineContinuation().replaceEscapeSequences()) }, multiline: true) ] } private func multiLineStringLiteralEvaluators() -> [Evaluator] { let validUnicodeChars = "\n\\u0020-\\u0026\\u0028-\\uFFFF" return [ Evaluator(regex: "'''", generator: { _ in nil }, pop: true), Evaluator(regex: "([" + validUnicodeChars + "]'?'?)*[" + validUnicodeChars + "]+", generator: { (r: String) in .Identifier(r.trim()) }, multiline: true) ] } private func tableNameEvaluators() -> [Evaluator] { let tableErrorStr = "Invalid table name declaration" return [ Evaluator(regex: "\"", generator: { _ in nil }, push: ["string"]), Evaluator(regex: "'", generator: { _ in nil }, push: ["literalString"]), Evaluator(regex: "\\.", generator: { _ in .TableSep }), // opening [ are prohibited directly within a table declaration Evaluator(regex: "\\[", generator: { _ in throw TomlError.SyntaxError(tableErrorStr) }), // hashes are prohibited directly within a table declaration Evaluator(regex: "#", generator: { _ in throw TomlError.SyntaxError(tableErrorStr) }), Evaluator(regex: "[A-Za-z0-9_-]+", generator: { (r: String) in .Identifier(r) }), Evaluator(regex: "\\]\\]", generator: { _ in .TableArrayEnd }, pop: true), Evaluator(regex: "\\]", generator: { _ in .TableEnd }, pop: true), ] } private func tableArrayEvaluators() -> [Evaluator] { let tableErrorStr = "Invalid table name declaration" return [ Evaluator(regex: "\"", generator: { _ in nil }, push: ["string"]), Evaluator(regex: "'", generator: { _ in nil }, push: ["literalString"]), Evaluator(regex: "\\.", generator: { _ in .TableSep }), // opening [ are prohibited directly within a table declaration Evaluator(regex: "\\[", generator: { _ in throw TomlError.SyntaxError(tableErrorStr) }), // hashes are prohibited directly within a table declaration Evaluator(regex: "#", generator: { _ in throw TomlError.SyntaxError(tableErrorStr) }), Evaluator(regex: "[A-Za-z0-9_-]+", generator: { (r: String) in .Identifier(r) }), Evaluator(regex: "\\]\\]", generator: { _ in .TableArrayEnd }, pop: true), ] } private func dateValueEvaluators() -> [Evaluator] { let dateTimeStr = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}" return [ // Dates, RFC 3339 w/ fractional seconds and time offset Evaluator(regex: dateTimeStr + ".\\d+(Z|z|[-\\+]\\d{2}:\\d{2})", generator: { (r: String) in if let date = Date(rfc3339String: r) { return Token.DateTime(date) } else { throw TomlError.InvalidDateFormat("####-##-##T##:##:##.###+/-##:## (\(r))") } }, pop: true), // RFC 3339 w/o fractional seconds and time offset Evaluator(regex: dateTimeStr + "(Z|z|[-\\+]\\d{2}:\\d{2})", generator: { (r: String) in if let date = Date(rfc3339String: r, fractionalSeconds: false) { return Token.DateTime(date) } else { throw TomlError.InvalidDateFormat("####-##-##T##:##:##+/-##:## (\(r))") } }, pop: true), // Dates, RFC 3339 w/ fractional seconds and w/o time offset Evaluator(regex: dateTimeStr + ".\\d+", generator: { (r: String) in if let date = Date(rfc3339String: r, localTime: true) { return Token.DateTime(date) } else { throw TomlError.InvalidDateFormat("####-##-##T##:##:##.### (\(r))") } }, pop: true), // Dates, RFC 3339 w/o fractional seconds and w/o time offset Evaluator(regex: dateTimeStr, generator: { (r: String) in if let date = Date(rfc3339String: r, fractionalSeconds: false, localTime: true) { return Token.DateTime(date) } else { throw TomlError.InvalidDateFormat("####-##-##T##:##:## (\(r))") } }, pop: true), // Date only Evaluator(regex: "\\d{4}-\\d{2}-\\d{2}", generator: { (r: String) in if let date = Date(rfc3339String: r + "T00:00:00.0", localTime: true) { return Token.DateTime(date) } else { throw TomlError.InvalidDateFormat("####-##-## (\(r))") } }, pop: true) ] } private func stringValueEvaluators() -> [Evaluator] { return [ // Multi-line string values (must come before single-line test) // Special case, empty multi-line string Evaluator(regex: "\"\"\"\"\"\"", generator: {_ in .Identifier("") }, pop: true), Evaluator(regex: "\"\"\"", generator: { _ in nil }, push: ["multilineString"], pop: true), // Multi-line literal string values (must come before single-line test) Evaluator(regex: "'''", generator: { _ in nil }, push: ["multilineLiteralString"], pop: true), // Special case, empty multi-line string literal Evaluator(regex: "''''''", generator: { _ in .Identifier("") }, push: ["multilineLiteralString"], pop: true), // empty single line strings Evaluator(regex: "\"\"", generator: { _ in .Identifier("") }, pop: true), Evaluator(regex: "''", generator: { _ in .Identifier("") }, pop: true), // String values Evaluator(regex: "\"", generator: { _ in nil }, push: ["string"], pop: true), // Literal string values Evaluator(regex: "'", generator: { _ in nil }, push: ["literalString"], pop: true), ] } private func doubleValueEvaluators() -> [Evaluator] { let generator: TokenGenerator = { (val: String) in .DoubleNumber(Double(val)!) } return [ // Double values with exponent Evaluator(regex: "[-\\+]?[0-9]+(\\.[0-9]+)?[eE][-\\+]?[0-9]+", generator: generator, pop:true), // Double values no exponent Evaluator(regex: "[-\\+]?[0-9]+\\.[0-9]+", generator: generator, pop: true), ] } private func intValueEvaluators() -> [Evaluator] { return [ // Integer values Evaluator(regex: "[-\\+]?[0-9]+", generator: { (r: String) in .IntegerNumber(Int(r)!) }, pop: true), ] } private func booleanValueEvaluators() -> [Evaluator] { return [ // Boolean values Evaluator(regex: "true", generator: { (r: String) in .Boolean(true) }, pop: true), Evaluator(regex: "false", generator: { (r: String) in .Boolean(false) }, pop: true), ] } private func whitespaceValueEvaluators() -> [Evaluator] { return [ // Ignore white-space Evaluator(regex: "[ \t]", generator: { _ in nil }), ] } private func arrayValueEvaluators() -> [Evaluator] { return [ // Arrays Evaluator(regex: "\\[", generator: { _ in .ArrayBegin }, push: ["array", "array"], pop: true), ] } private func inlineTableValueEvaluators() -> [Evaluator] { return [ // Inline tables Evaluator(regex: "\\{", generator: { _ in .InlineTableBegin }, push: ["inlineTable"], pop: true), ] } private func valueEvaluators() -> [Evaluator] { let typeEvaluators = stringValueEvaluators() + dateValueEvaluators() + doubleValueEvaluators() + intValueEvaluators() + booleanValueEvaluators() return whitespaceValueEvaluators() + arrayValueEvaluators() + inlineTableValueEvaluators() + typeEvaluators } private func arrayEvaluators() -> [Evaluator] { return [ // Ignore white-space Evaluator(regex: "[ \n\t]", generator: { _ in nil }), // Comments Evaluator(regex: "#", generator: { _ in nil }, push: ["comment"]), // Arrays Evaluator(regex: "\\[", generator: { _ in .ArrayBegin }, push: ["array"]), Evaluator(regex: "\\]", generator: { _ in .ArrayEnd }, pop: true), Evaluator(regex: ",", generator: { _ in nil }, push: ["array"]), ] + valueEvaluators() } private func stringKeyEvaluator() -> [Evaluator] { let validUnicodeChars = "\\u0020-\\u0021\\u0023-\\u005B\\u005D-\\uFFFF" return [ // bare key Evaluator(regex: "[a-zA-Z0-9_-]+[ \t]*=", generator: { (r: String) in .Key(String(r[..<r.index(r.endIndex, offsetBy:-1)]).trim()) }, push: ["value"]), // string key Evaluator(regex: "\"([" + validUnicodeChars + "]|\\\\\"|\\\\)+\"[ \t]*=", generator: { (r: String) in .Key(try trimStringIdentifier(r, "\"").replaceEscapeSequences()) }, push: ["value"]), // literal string key Evaluator(regex: "'([\\u0020-\\u0026\\u0028-\\uFFFF])+'[ \t]*=", generator: { (r: String) in .Key(trimStringIdentifier(r, "'")) }, push: ["value"]), ] } private func inlineTableEvaluators() -> [Evaluator] { return [ // Ignore white-space and commas Evaluator(regex: "[ \t,]", generator: { _ in nil }), // inline-table Evaluator(regex: "\\{", generator: { _ in .InlineTableBegin }, push: ["inlineTable"]), Evaluator(regex: "\\}", generator: { _ in .InlineTableEnd }, pop: true), ] + stringKeyEvaluator() } private func rootEvaluators() -> [Evaluator] { return [ // Ignore white-space Evaluator(regex: "[ \t\r\n]", generator: { _ in nil }), // Comments Evaluator(regex: "#", generator: { _ in nil }, push: ["comment"]), ] + stringKeyEvaluator() + [ // Array of tables (must come before table) Evaluator(regex: "\\[\\[", generator: { _ in .TableArrayBegin }, push: ["tableArray"]), // Tables Evaluator(regex: "\\[", generator: { _ in .TableBegin }, push: ["tableName"]), ] } }
587f05c42255923f2a4576ba5bcdceda
43.74026
100
0.519884
false
false
false
false
onevcat/Rainbow
refs/heads/master
Sources/Color.swift
mit
1
// // Color.swift // Rainbow // // Created by Wei Wang on 15/12/22. // // Copyright (c) 2018 Wei Wang <onevcat@gmail.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. public typealias RGB = (UInt8, UInt8, UInt8) public enum ColorType: ModeCode { case named(Color) case bit8(UInt8) case bit24(RGB) @available(*, deprecated, message: "For backward compatibility.") var namedColor: Color? { switch self { case .named(let color): return color default: return nil } } public var value: [UInt8] { switch self { case .named(let color): return color.value case .bit8(let color): return [ControlCode.setColor, ControlCode.set8Bit, color] case .bit24(let rgb): return [ControlCode.setColor, ControlCode.set24Bit, rgb.0, rgb.1, rgb.2] } } public var toBackgroundColor: BackgroundColorType { switch self { case .named(let color): return .named(color.toBackgroundColor) case .bit8(let color): return .bit8(color) case .bit24(let rgb): return .bit24(rgb) } } } extension ColorType: Equatable { public static func == (lhs: ColorType, rhs: ColorType) -> Bool { switch (lhs, rhs) { case (.named(let color1), .named(let color2)): return color1 == color2 case (.bit8(let color1), .bit8(let color2)): return color1 == color2 case (.bit24(let color1), .bit24(let color2)): return color1 == color2 default: return false } } } public typealias Color = NamedColor /// Valid named text colors to use in `Rainbow`. public enum NamedColor: UInt8, ModeCode, CaseIterable { case black = 30 case red case green case yellow case blue case magenta case cyan case white case `default` = 39 case lightBlack = 90 case lightRed case lightGreen case lightYellow case lightBlue case lightMagenta case lightCyan case lightWhite public var value: [UInt8] { return [rawValue] } public var toBackgroundColor: NamedBackgroundColor { return NamedBackgroundColor(rawValue: rawValue + 10)! } }
aa2dc05798ccae501d6f0524bfc564c7
31.474747
102
0.673717
false
false
false
false
fespinoza/linked-ideas-osx
refs/heads/master
Playground-macOS.playground/Pages/Hello World.xcplaygroundpage/Contents.swift
mit
1
import Cocoa NSImage.init(contentsOfFile: "tutorial-00.jpg") //NSImage.init(byReferencingFile: "tutorial-00") // images on macos let fileURL = Bundle.main.url(forResource: "tutorial-00", withExtension: "jpg") let image = NSImage.init(contentsOf: fileURL!) let imageView = NSImageView(frame: CGRect(x: 0, y: 0, width: 800, height: 600)) imageView.image = image imageView.frame import PlaygroundSupport PlaygroundPage.current.liveView = imageView
fd8d91d41bd7f6cd21803cf7fee2137f
24.111111
79
0.763274
false
false
false
false
OscarSwanros/swift
refs/heads/master
tools/SwiftSyntax/SourcePresence.swift
apache-2.0
10
//===---------------- SourcePresence.swift - Source Presence --------------===// // // 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 // //===----------------------------------------------------------------------===// import Foundation /// An indicator of whether a Syntax node was found or written in the source. /// /// A `missing` node does not mean, necessarily, that the source item is /// considered "implicit", but rather that it was not found in the source. public enum SourcePresence: String, Codable { /// The syntax was authored by a human and found, or was generated. case present = "Present" /// The syntax was expected or optional, but not found in the source. case missing = "Missing" }
d92ce582dc3b12e03d82adab76d1f584
39.56
80
0.647929
false
false
false
false
kaishin/ImageScout
refs/heads/master
Tests/ImageScoutTests/ScoutTests.swift
mit
1
import XCTest import ImageScout private final class BundleToken {} private let expectationTimeOut: TimeInterval = 5 class ImageScoutTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func url(forResource name: String, extension ext: String) -> URL { let bundle = Bundle(for: BundleToken.self) return bundle.url(forResource: name, withExtension: ext)! } func testScoutingJPEG() { let scout = ImageScout() let expectation = self.expectation(description: "Scout JPEG images") let imagePath = url(forResource: "scout", extension: "jpg") scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in expectation.fulfill() XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375") XCTAssertEqual(type, ScoutedImageType.jpeg, "Image type should be JPEG") XCTAssertNil(error, "Error should be nil") } waitForExpectations(timeout: expectationTimeOut, handler: .none) } func testScoutingPNG() { let scout = ImageScout() let expectation = self.expectation(description: "Scount PNG images") let imagePath = url(forResource: "scout", extension: "png") scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in expectation.fulfill() XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375") XCTAssertEqual(type, ScoutedImageType.png, "Image type should be PNG") XCTAssertNil(error, "Error should be nil") } waitForExpectations(timeout: expectationTimeOut, handler: .none) } func testScoutingGIF() { let scout = ImageScout() let expectation = self.expectation(description: "Scout GIF images") let imagePath = url(forResource: "scout", extension: "gif") scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in expectation.fulfill() XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375") XCTAssertEqual(type, ScoutedImageType.gif, "Image type should be GIF") XCTAssertNil(error, "Error should be nil") } waitForExpectations(timeout: expectationTimeOut, handler: nil) } func testScoutingUnsupported() { let scout = ImageScout() let expectation = self.expectation(description: "Ignore unsupported formats") let imagePath = url(forResource: "scout", extension: "bmp") scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in expectation.fulfill() XCTAssertEqual(size, CGSize.zero, "Image size should be 0 by 0") XCTAssertEqual(type, ScoutedImageType.unsupported ,"Image type should be Unsupported") XCTAssertNotNil(error, "Error should not be nil") XCTAssertEqual(error!.code, 102, "Error should describe failure reason") } waitForExpectations(timeout: expectationTimeOut, handler: nil) } }
391c645ef72e1f1e190aa9198c31329b
34.609756
94
0.694178
false
true
false
false
whitepixelstudios/Material
refs/heads/master
Sources/iOS/FABMenu.swift
bsd-3-clause
1
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * 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 CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(FABMenuItemTitleLabelPosition) public enum FABMenuItemTitleLabelPosition: Int { case left case right } @objc(FABMenuDirection) public enum FABMenuDirection: Int { case up case down case left case right } open class FABMenuItem: View { /// A reference to the titleLabel. open let titleLabel = UILabel() /// The titleLabel side. open var titleLabelPosition = FABMenuItemTitleLabelPosition.left /// A reference to the fabButton. open let fabButton = FABButton() open override func prepare() { super.prepare() backgroundColor = nil prepareFABButton() prepareTitleLabel() } /// A reference to the titleLabel text. open var title: String? { get { return titleLabel.text } set(value) { titleLabel.text = value layoutSubviews() } } open override func layoutSubviews() { super.layoutSubviews() guard let t = title, 0 < t.utf16.count else { titleLabel.removeFromSuperview() return } if nil == titleLabel.superview { addSubview(titleLabel) } } } extension FABMenuItem { /// Shows the titleLabel. open func showTitleLabel() { let interimSpace = InterimSpacePresetToValue(preset: .interimSpace6) titleLabel.sizeToFit() titleLabel.frame.size.width += 1.5 * interimSpace titleLabel.frame.size.height += interimSpace / 2 titleLabel.frame.origin.y = (bounds.height - titleLabel.bounds.height) / 2 switch titleLabelPosition { case .left: titleLabel.frame.origin.x = -titleLabel.bounds.width - interimSpace case .right: titleLabel.frame.origin.x = frame.bounds.width + interimSpace } titleLabel.alpha = 0 titleLabel.isHidden = false UIView.animate(withDuration: 0.25, animations: { [weak self] in guard let s = self else { return } s.titleLabel.alpha = 1 }) } /// Hides the titleLabel. open func hideTitleLabel() { titleLabel.isHidden = true } } extension FABMenuItem { /// Prepares the fabButton. fileprivate func prepareFABButton() { layout(fabButton).edges() } /// Prepares the titleLabel. fileprivate func prepareTitleLabel() { titleLabel.font = RobotoFont.regular(with: 14) titleLabel.textAlignment = .center titleLabel.backgroundColor = .white titleLabel.depthPreset = fabButton.depthPreset titleLabel.cornerRadiusPreset = .cornerRadius1 } } @objc(FABMenuDelegate) public protocol FABMenuDelegate { /** A delegation method that is execited when the fabMenu will open. - Parameter fabMenu: A FABMenu. */ @objc optional func fabMenuWillOpen(fabMenu: FABMenu) /** A delegation method that is execited when the fabMenu did open. - Parameter fabMenu: A FABMenu. */ @objc optional func fabMenuDidOpen(fabMenu: FABMenu) /** A delegation method that is execited when the fabMenu will close. - Parameter fabMenu: A FABMenu. */ @objc optional func fabMenuWillClose(fabMenu: FABMenu) /** A delegation method that is execited when the fabMenu did close. - Parameter fabMenu: A FABMenu. */ @objc optional func fabMenuDidClose(fabMenu: FABMenu) /** A delegation method that is executed when the user taps while the menu is opened. - Parameter fabMenu: A FABMenu. - Parameter tappedAt point: A CGPoint. - Parameter isOutside: A boolean indicating whether the tap was outside the menu button area. */ @objc optional func fabMenu(fabMenu: FABMenu, tappedAt point: CGPoint, isOutside: Bool) } @objc(FABMenu) open class FABMenu: View { /// A flag to avoid the double tap. fileprivate var shouldAvoidHitTest = false /// A reference to the SpringAnimation object. internal let spring = SpringAnimation() open var fabMenuDirection: FABMenuDirection { get { switch spring.springDirection { case .up: return .up case .down: return .down case .left: return .left case .right: return .right } } set(value) { switch value { case .up: spring.springDirection = .up case .down: spring.springDirection = .down case .left: spring.springDirection = .left case .right: spring.springDirection = .right } layoutSubviews() } } /// A reference to the base FABButton. open var fabButton: FABButton? { didSet { oldValue?.removeFromSuperview() guard let v = fabButton else { return } addSubview(v) v.addTarget(self, action: #selector(handleFABButton(button:)), for: .touchUpInside) } } /// An open handler for the FABButton. open var handleFABButtonCallback: ((UIButton) -> Void)? /// An internal handler for the open function. internal var handleOpenCallback: (() -> Void)? /// An internal handler for the close function. internal var handleCloseCallback: (() -> Void)? /// An internal handler for the completion function. internal var handleCompletionCallback: ((UIView) -> Void)? /// Size of FABMenuItems. open var fabMenuItemSize: CGSize { get { return spring.itemSize } set(value) { spring.itemSize = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset: InterimSpacePreset { get { return spring.interimSpacePreset } set(value) { spring.interimSpacePreset = value } } /// The space between views. open var interimSpace: InterimSpace { get { return spring.interimSpace } set(value) { spring.interimSpace = value } } /// A boolean indicating if the menu is open or not. open var isOpened: Bool { get { return spring.isOpened } set(value) { spring.isOpened = value } } /// A boolean indicating if the menu is enabled. open var isEnabled: Bool { get { return spring.isEnabled } set(value) { spring.isEnabled = value } } /// An optional delegation handler. open weak var delegate: FABMenuDelegate? /// A reference to the FABMenuItems open var fabMenuItems: [FABMenuItem] { get { return spring.views as! [FABMenuItem] } set(value) { for v in spring.views { v.removeFromSuperview() } for v in value { addSubview(v) } spring.views = value } } open override func layoutSubviews() { super.layoutSubviews() fabButton?.frame.size = bounds.size spring.baseSize = bounds.size } open override func prepare() { super.prepare() backgroundColor = nil interimSpacePreset = .interimSpace6 } } extension FABMenu { /** Open the Menu component with animation options. - Parameter duration: The time for each view's animation. - Parameter delay: A delay time for each view's animation. - Parameter usingSpringWithDamping: A damping ratio for the animation. - Parameter initialSpringVelocity: The initial velocity for the animation. - Parameter options: Options to pass to the animation. - Parameter animations: An animation block to execute on each view's animation. - Parameter completion: A completion block to execute on each view's animation. */ open func open(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) { open(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion) } /** Open the Menu component with animation options. - Parameter isTriggeredByUserInteraction: A boolean indicating whether the state was changed by a user interaction, true if yes, false otherwise. - Parameter duration: The time for each view's animation. - Parameter delay: A delay time for each view's animation. - Parameter usingSpringWithDamping: A damping ratio for the animation. - Parameter initialSpringVelocity: The initial velocity for the animation. - Parameter options: Options to pass to the animation. - Parameter animations: An animation block to execute on each view's animation. - Parameter completion: A completion block to execute on each view's animation. */ open func open(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) { handleOpenCallback?() if isTriggeredByUserInteraction { delegate?.fabMenuWillOpen?(fabMenu: self) } spring.expand(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in guard let s = self else { return } (view as? FABMenuItem)?.showTitleLabel() if isTriggeredByUserInteraction && view == s.fabMenuItems.last { s.delegate?.fabMenuDidOpen?(fabMenu: s) } completion?(view) s.handleCompletionCallback?(view) } } /** Close the Menu component with animation options. - Parameter duration: The time for each view's animation. - Parameter delay: A delay time for each view's animation. - Parameter usingSpringWithDamping: A damping ratio for the animation. - Parameter initialSpringVelocity: The initial velocity for the animation. - Parameter options: Options to pass to the animation. - Parameter animations: An animation block to execute on each view's animation. - Parameter completion: A completion block to execute on each view's animation. */ open func close(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) { close(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion) } /** Close the Menu component with animation options. - Parameter isTriggeredByUserInteraction: A boolean indicating whether the state was changed by a user interaction, true if yes, false otherwise. - Parameter duration: The time for each view's animation. - Parameter delay: A delay time for each view's animation. - Parameter usingSpringWithDamping: A damping ratio for the animation. - Parameter initialSpringVelocity: The initial velocity for the animation. - Parameter options: Options to pass to the animation. - Parameter animations: An animation block to execute on each view's animation. - Parameter completion: A completion block to execute on each view's animation. */ open func close(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) { handleCloseCallback?() if isTriggeredByUserInteraction { delegate?.fabMenuWillClose?(fabMenu: self) } spring.contract(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in guard let s = self else { return } (view as? FABMenuItem)?.hideTitleLabel() if isTriggeredByUserInteraction && view == s.fabMenuItems.last { s.delegate?.fabMenuDidClose?(fabMenu: s) } completion?(view) s.handleCompletionCallback?(view) } } } extension FABMenu { /** Handles the hit test for the Menu and views outside of the Menu bounds. - Parameter _ point: A CGPoint. - Parameter with event: An optional UIEvent. - Returns: An optional UIView. */ open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard isOpened, isEnabled else { return super.hitTest(point, with: event) } for v in subviews { let p = v.convert(point, from: self) if v.bounds.contains(p) { if !shouldAvoidHitTest { delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: false) } shouldAvoidHitTest = !shouldAvoidHitTest return v.hitTest(p, with: event) } } delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: true) close(isTriggeredByUserInteraction: true) return super.hitTest(point, with: event) } } extension FABMenu { /** Handler to toggle the FABMenu opened or closed. - Parameter button: A UIButton. */ @objc fileprivate func handleFABButton(button: UIButton) { guard nil == handleFABButtonCallback else { handleFABButtonCallback?(button) return } guard isOpened else { open(isTriggeredByUserInteraction: true) return } close(isTriggeredByUserInteraction: true) } }
7fa468d7336ee9ef44677cb53a0088a7
34.395833
304
0.630077
false
false
false
false
RxSwiftCommunity/RxAlamofire
refs/heads/main
Examples/RxAlamofireDemo-iOS/MasterViewController.swift
mit
1
import Alamofire import RxAlamofire import RxSwift import UIKit enum APIError: Error { case invalidInput case badResponse func toNSError() -> NSError { let domain = "com.github.rxswiftcommunity.rxalamofire" switch self { case .invalidInput: return NSError(domain: domain, code: -1, userInfo: [NSLocalizedDescriptionKey: "Input should be a valid number"]) case .badResponse: return NSError(domain: domain, code: -2, userInfo: [NSLocalizedDescriptionKey: "Bad response"]) } } } class MasterViewController: UIViewController, UITextFieldDelegate { let disposeBag = DisposeBag() let exchangeRateEndpoint = "https://api.exchangeratesapi.io/latest?base=EUR&symbols=USD" @IBOutlet var fromTextField: UITextField! @IBOutlet var toTextField: UITextField! @IBOutlet var convertBtn: UIButton! @IBOutlet var dummyDataBtn: UIButton! @IBOutlet var dummyDataTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() } // MARK: - UI Actions @IBAction func convertPressed(_ sender: UIButton) { fromTextField.resignFirstResponder() guard let fromText = fromTextField.text, let fromValue = Double(fromText) else { displayError(APIError.invalidInput.toNSError()) return } requestJSON(.get, exchangeRateEndpoint) .debug() .flatMap { (_, json) -> Observable<Double> in guard let body = json as? [String: Any], let rates = body["rates"] as? [String: Any], let rate = rates["USD"] as? Double else { return .error(APIError.badResponse.toNSError()) } return .just(rate) } .subscribe(onNext: { [weak self] rate in self?.toTextField.text = "\(rate * fromValue)" }, onError: { [weak self] e in self?.displayError(e as NSError) }) .disposed(by: disposeBag) } func exampleUsages() { let stringURL = "" // MARK: NSURLSession simple and fast let session = URLSession.shared _ = session.rx .json(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } _ = session .rx.json(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } _ = session .rx.data(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } // MARK: With Alamofire engine _ = json(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } _ = request(.get, stringURL) .flatMap { request in request.validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) .rx.json() } .observeOn(MainScheduler.instance) .subscribe { print($0) } // progress _ = request(.get, stringURL) .flatMap { $0 .validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) .rx.progress() } .observeOn(MainScheduler.instance) .subscribe { print($0) } // just fire upload and display progress if let urlRequest = try? urlRequest(.get, stringURL) { _ = upload(Data(), urlRequest: urlRequest) .flatMap { $0 .validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) .rx.progress() } .observeOn(MainScheduler.instance) .subscribe { print($0) } } // progress and final result // uploading files with progress showing is processing intensive operation anyway, so // this doesn't add much overhead _ = request(.get, stringURL) .flatMap { request -> Observable<(Data?, RxProgress)> in let validatedRequest = request .validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) let dataPart = validatedRequest .rx.data() .map { d -> Data? in d } .startWith(nil as Data?) let progressPart = validatedRequest.rx.progress() return Observable.combineLatest(dataPart, progressPart) { ($0, $1) } } .observeOn(MainScheduler.instance) .subscribe { print($0) } // MARK: Alamofire manager // same methods with any alamofire manager let manager = Session.default // simple case _ = manager.rx.json(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } // NSURLHTTPResponse + JSON _ = manager.rx.responseJSON(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } // NSURLHTTPResponse + String _ = manager.rx.responseString(.get, stringURL) .observeOn(MainScheduler.instance) .subscribe { print($0) } // NSURLHTTPResponse + Validation + String _ = manager.rx.request(.get, stringURL) .flatMap { $0 .validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) .rx.string() } .observeOn(MainScheduler.instance) .subscribe { print($0) } // NSURLHTTPResponse + Validation + NSURLHTTPResponse + String _ = manager.rx.request(.get, stringURL) .flatMap { $0 .validate(statusCode: 200..<300) .validate(contentType: ["text/json"]) .rx.responseString() } .observeOn(MainScheduler.instance) .subscribe { print($0) } // NSURLHTTPResponse + Validation + NSURLHTTPResponse + String + Progress _ = manager.rx.request(.get, stringURL) .flatMap { request -> Observable<(String?, RxProgress)> in let validatedRequest = request .validate(statusCode: 200..<300) .validate(contentType: ["text/something"]) let stringPart = validatedRequest .rx.string() .map { d -> String? in d } .startWith(nil as String?) let progressPart = validatedRequest.rx.progress() return Observable.combineLatest(stringPart, progressPart) { ($0, $1) } } .observeOn(MainScheduler.instance) .subscribe { print($0) } } @IBAction func getDummyDataPressed(_ sender: UIButton) { let dummyPostURLString = "http://jsonplaceholder.typicode.com/posts/1" let dummyCommentsURLString = "http://jsonplaceholder.typicode.com/posts/1/comments" let postObservable = json(.get, dummyPostURLString) let commentsObservable = json(.get, dummyCommentsURLString) dummyDataTextView.text = "Loading..." Observable.zip(postObservable, commentsObservable) { postJSON, commentsJSON in (postJSON, commentsJSON) } .observeOn(MainScheduler.instance) .subscribe(onNext: { postJSON, commentsJSON in let postInfo = NSMutableString() if let postDict = postJSON as? [String: AnyObject], let commentsArray = commentsJSON as? [[String: AnyObject]], let postTitle = postDict["title"] as? String, let postBody = postDict["body"] as? String { postInfo.append("Title: ") postInfo.append(postTitle) postInfo.append("\n\n") postInfo.append(postBody) postInfo.append("\n\n\nComments:\n") for comment in commentsArray { if let email = comment["email"] as? String, let body = comment["body"] as? String { postInfo.append(email) postInfo.append(": ") postInfo.append(body) postInfo.append("\n\n") } } } self.dummyDataTextView.text = String(postInfo) }, onError: { e in self.dummyDataTextView.text = "An Error Occurred" self.displayError(e as NSError) }).disposed(by: disposeBag) } // MARK: - Utils func displayError(_ error: NSError?) { if let e = error { let alertController = UIAlertController(title: "Error", message: e.localizedDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { _ in // do nothing... } alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } } }
97927e897bc26400f791963b1cd9f91f
30.783465
119
0.621578
false
false
false
false
madhusamuel/PlacesExplorer
refs/heads/master
PlacesExplorer/Networking/URLConstructor.swift
epl-1.0
1
// // URLConstructor.swift // PlacesExplorer // // Created by Madhu Samuel on 5/11/2015. // Copyright © 2015 Madhu. All rights reserved. // import Foundation class URLConstructor { var endPoint: String! var webservice: String! var clientId: String! var clientSecret: String! var dataURLString: String! //Example: https://api.foursquare.com/v2/venues/search?client_id=45OD3KD2OAX3IDGYPJ3FVXQX5VYIGWV5JDQGM1MDBGJEWFJF&client_secret=E3G1JPJWTJF4XISJA5C5DYVKQLEXSOQGBLPWPLADBZFBTO2R&v=20130815&ll=-37.8136,144.9631 var urlString: String { get { var interURLString = endPoint + webservice if let localClientId = clientId { interURLString = interURLString + "?" + "client_id=" + localClientId + "&" + "client_secret=" + clientSecret } if let localDataURLString = dataURLString { if let localClientId = clientId { interURLString = interURLString + "&" + dataURLString } else { interURLString = interURLString + "?" + dataURLString } } return interURLString } } var url: NSURL { get { return NSURL(string: urlString)! } } }
a6956c01855afcaf0a32b67e9c63ecf1
27.723404
212
0.573017
false
false
false
false
zyuanming/EffectDesignerX
refs/heads/master
EffectDesignerX/Model/BindingModel.swift
mit
1
// // BindingEmitterCellModel.swift // EffectDesignerX // // Created by Zhang Yuanming on 11/30/16. // Copyright © 2016 Zhang Yuanming. All rights reserved. // import Foundation class BindingModel: NSObject { dynamic var emitterShape: String = "" dynamic var emitterMode: String = "" dynamic var renderMode: String = "" dynamic var preservesDepth: CGFloat = 0 dynamic var width: CGFloat = 0 dynamic var height: CGFloat = 0 dynamic var birthRate: CGFloat = 0 dynamic var lifetime: CGFloat = 0 dynamic var lifetimeRange: CGFloat = 0 dynamic var velocity: CGFloat = 0 dynamic var velocityRange: CGFloat = 0 dynamic var emissionLatitude: CGFloat = 0 dynamic var emissionLongitude: CGFloat = 0 dynamic var emissionRange: CGFloat = 0 dynamic var xAcceleration: CGFloat = 0 dynamic var yAcceleration: CGFloat = 0 dynamic var zAcceleration: CGFloat = 0 dynamic var contents: String = "" dynamic var contentsRect: String = "" dynamic var name: String = "" dynamic var color: NSColor = NSColor.white dynamic var redRange: CGFloat = 0 dynamic var redSpeed: CGFloat = 0 dynamic var greenRange: CGFloat = 0 dynamic var greenSpeed: CGFloat = 0 dynamic var blueRange: CGFloat = 0 dynamic var blueSpeed: CGFloat = 0 dynamic var alpha: CGFloat = 0 dynamic var alphaRange: CGFloat = 0 dynamic var alphaSpeed: CGFloat = 0 dynamic var scale: CGFloat = 0 dynamic var scaleRange: CGFloat = 0 dynamic var scaleSpeed: CGFloat = 0 dynamic var spin: CGFloat = 0 dynamic var spinRange: CGFloat = 0 dynamic var contentsImage: NSImage? func update(from effectModel: EmitterCellModel) { self.birthRate = effectModel.birthRate self.lifetime = effectModel.lifetime self.lifetimeRange = effectModel.lifetimeRange self.velocity = effectModel.velocity self.velocityRange = effectModel.velocityRange self.emissionRange = effectModel.emissionRange self.emissionLongitude = effectModel.emissionLongitude self.emissionLatitude = effectModel.emissionLatitude self.xAcceleration = effectModel.xAcceleration self.yAcceleration = effectModel.yAcceleration self.zAcceleration = effectModel.zAcceleration self.contents = effectModel.contents self.contentsRect = effectModel.contentsRect self.name = effectModel.name self.color = effectModel.color self.redRange = effectModel.redRange self.redSpeed = effectModel.redSpeed self.greenRange = effectModel.greenRange self.greenSpeed = effectModel.greenSpeed self.blueRange = effectModel.blueRange self.blueSpeed = effectModel.blueSpeed self.alpha = effectModel.alpha self.alphaRange = effectModel.alphaRange self.alphaSpeed = effectModel.alphaSpeed self.scale = effectModel.scale self.scaleRange = effectModel.scaleRange self.scaleSpeed = effectModel.scaleSpeed self.spin = effectModel.spin self.spinRange = effectModel.spinRange self.contentsImage = effectModel.contentsImage } func allPropertyNames() -> [String] { return Mirror(reflecting: self).children.flatMap({ $0.label }) } }
f06d31d16590eae27765a0e6140e5934
36.954023
70
0.699576
false
false
false
false
ianyh/Highball
refs/heads/master
Highball/AccountsService.swift
mit
1
// // AccountsService.swift // Highball // // Created by Ian Ynda-Hummel on 12/16/14. // Copyright (c) 2014 ianynda. All rights reserved. // import OAuthSwift import RealmSwift import SwiftyJSON import TMTumblrSDK import UIKit public struct AccountsService { private static let lastAccountNameKey = "HILastAccountKey" public private(set) static var account: Account! public static func accounts() -> [Account] { guard let realm = try? Realm() else { return [] } return realm.objects(AccountObject).map { $0 } } public static func lastAccount() -> Account? { let userDefaults = NSUserDefaults.standardUserDefaults() guard let accountName = userDefaults.stringForKey(lastAccountNameKey) else { return nil } guard let realm = try? Realm() else { return nil } guard let account = realm.objectForPrimaryKey(AccountObject.self, key: accountName) else { return nil } return account } public static func start(fromViewController viewController: UIViewController, completion: (Account) -> ()) { if let lastAccount = lastAccount() { loginToAccount(lastAccount, completion: completion) return } guard let firstAccount = accounts().first else { authenticateNewAccount(fromViewController: viewController) { account in if let account = account { self.loginToAccount(account, completion: completion) } else { self.start(fromViewController: viewController, completion: completion) } } return } loginToAccount(firstAccount, completion: completion) } public static func loginToAccount(account: Account, completion: (Account) -> ()) { self.account = account TMAPIClient.sharedInstance().OAuthToken = account.token TMAPIClient.sharedInstance().OAuthTokenSecret = account.tokenSecret dispatch_async(dispatch_get_main_queue()) { completion(account) } } public static func authenticateNewAccount(fromViewController viewController: UIViewController, completion: (account: Account?) -> ()) { let oauth = OAuth1Swift( consumerKey: TMAPIClient.sharedInstance().OAuthConsumerKey, consumerSecret: TMAPIClient.sharedInstance().OAuthConsumerSecret, requestTokenUrl: "https://www.tumblr.com/oauth/request_token", authorizeUrl: "https://www.tumblr.com/oauth/authorize", accessTokenUrl: "https://www.tumblr.com/oauth/access_token" ) let currentAccount: Account? = account account = nil TMAPIClient.sharedInstance().OAuthToken = nil TMAPIClient.sharedInstance().OAuthTokenSecret = nil oauth.authorize_url_handler = SafariURLHandler(viewController: viewController) oauth.authorizeWithCallbackURL( NSURL(string: "highball://oauth-callback")!, success: { (credential, response, parameters) in TMAPIClient.sharedInstance().OAuthToken = credential.oauth_token TMAPIClient.sharedInstance().OAuthTokenSecret = credential.oauth_token_secret TMAPIClient.sharedInstance().userInfo { response, error in var account: Account? defer { completion(account: account) } if let error = error { print(error) return } let json = JSON(response) guard let blogsJSON = json["user"]["blogs"].array else { return } let blogs = blogsJSON.map { blogJSON -> UserBlogObject in let blog = UserBlogObject() blog.name = blogJSON["name"].stringValue blog.url = blogJSON["url"].stringValue blog.title = blogJSON["title"].stringValue blog.isPrimary = blogJSON["primary"].boolValue return blog } let accountObject = AccountObject() accountObject.name = json["name"].stringValue accountObject.token = TMAPIClient.sharedInstance().OAuthToken accountObject.tokenSecret = TMAPIClient.sharedInstance().OAuthTokenSecret accountObject.blogObjects.appendContentsOf(blogs) guard let realm = try? Realm() else { return } do { try realm.write { realm.add(accountObject, update: true) } } catch { print(error) return } account = accountObject self.account = currentAccount TMAPIClient.sharedInstance().OAuthToken = currentAccount?.token TMAPIClient.sharedInstance().OAuthTokenSecret = currentAccount?.tokenSecret } }, failure: { (error) in print(error) } ) } public static func deleteAccount(account: Account, fromViewController viewController: UIViewController, completion: (changedAccount: Bool) -> ()) { if self.account == account { self.account = nil start(fromViewController: viewController) { _ in completion(changedAccount: true) } } dispatch_async(dispatch_get_main_queue()) { completion(changedAccount: false) } } }
fc928ec2b14e915c261a53ae4af0c429
26.16185
148
0.709087
false
false
false
false
drmohundro/Quick
refs/heads/master
Quick/QuickTests/FunctionalTests.swift
mit
2
// // FunctionalTests.swift // QuickTests // // Created by Brian Ivan Gesiak on 6/5/14. // Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved. // import Quick import Nimble var dinosaursExtinct = false var mankindExtinct = false class FunctionalSharedExamples: QuickSharedExampleGroups { override class func sharedExampleGroups() { sharedExamples("something living after dinosaurs are extinct") { it("no longer deals with dinosaurs") { expect(dinosaursExtinct).to(beTruthy()) } } sharedExamples("an optimistic person") { (sharedExampleContext: SharedExampleContext) in var person: Person! beforeEach { person = sharedExampleContext()["person"] as Person } it("is happy") { expect(person.isHappy).to(beTruthy()) } it("is a dreamer") { expect(person.hopes).to(contain("winning the lottery")) } } } } class PersonSpec: QuickSpec { override func spec() { describe("Person") { var person: Person! = nil beforeSuite { assert(!dinosaursExtinct, "nothing goes extinct twice") dinosaursExtinct = true } afterSuite { assert(!mankindExtinct, "tests shouldn't run after the apocalypse") mankindExtinct = true } beforeEach { person = Person() } afterEach { person = nil } itBehavesLike("something living after dinosaurs are extinct") itBehavesLike("an optimistic person") { ["person": person] } it("gets hungry") { person!.eatChineseFood() expect{person.isHungry}.toEventually(beTruthy()) } it("will never be satisfied") { expect{person.isSatisfied}.toEventuallyNot(beTruthy()) } it("🔥🔥それでも俺たちは🔥🔥") { expect{person.isSatisfied}.toEventuallyNot(beTruthy()) } pending("but one day") { it("will never want for anything") { expect{person.isSatisfied}.toEventually(beTruthy()) } } it("does not live with dinosaurs") { expect(dinosaursExtinct).to(beTruthy()) expect(mankindExtinct).notTo(beTruthy()) } describe("greeting") { context("when the person is unhappy") { beforeEach { person.isHappy = false } it("is lukewarm") { expect(person.greeting).to(equal("Oh, hi.")) expect(person.greeting).notTo(equal("Hello!")) } } context("when the person is happy") { beforeEach { person!.isHappy = true } it("is enthusiastic") { expect(person.greeting).to(equal("Hello!")) expect(person.greeting).notTo(equal("Oh, hi.")) } } } } } } class PoetSpec: QuickSpec { override func spec() { describe("Poet") { // FIXME: Radar worthy? `var poet: Poet?` results in build error: // "Could not find member 'greeting'" var poet: Person! = nil beforeEach { poet = Poet() } describe("greeting") { context("when the poet is unhappy") { beforeEach { poet.isHappy = false } it("is dramatic") { expect(poet.greeting).to(equal("Woe is me!")) } } context("when the poet is happy") { beforeEach { poet.isHappy = true } it("is joyous") { expect(poet.greeting).to(equal("Oh, joyous day!")) } } } } } }
a0ed80ab3389e5ed029a767f5f319df8
30.282443
96
0.487555
false
false
false
false
imex94/KCLTech-iOS-2015
refs/heads/master
session102/Challenge1.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Naive Prime function func naivePrime(number: Int) -> Bool { for i in 2...Int(sqrt(Double(number))) { if (number % i == 0) { return false } } return true } naivePrime(5) // Extended Prime function func isPrime(number: Int) -> Bool { let until = sqrt(Double(number)) guard number >= 2 else { return false } guard until >= 2 else { return true } for i in 2...Int(until) { if (number % i == 0) { return false } } return true } isPrime(2) // Alternative Prime functin func altPrime(number: Int) -> Bool { switch number { case let n where n < 2: return false case 2, 3: return true default: break } for i in 2...Int(sqrt(Double(number))) { if (number % i == 0) { return false } } return true } altPrime(5)
e247360f4d9d33aaccd4803110c90af3
14.716418
52
0.510921
false
false
false
false
nekrich/GlobalMessageService-iOS
refs/heads/master
Source/Core/CoreData/GMSInboxAlphaName+Extension.swift
apache-2.0
1
// // GMSInboxAlphaName+Extension.swift // GlobalMessageService // // Created by Vitalii Budnik on 2/25/16. // Copyright © 2016 Global Message Services Worldwide. All rights reserved. // import Foundation import CoreData extension GMSInboxAlphaName: NSManagedObjectSearchable { // swiftlint:disable line_length /** Search and creates (if needed) `GMSInboxFetchedDate` object for passed date - parameter alphaName: `String` with Alpha name - parameter managedObjectContext: `NSManagedObjectContext` in what to search. (optional. Default value: `GlobalMessageServiceCoreDataHelper.managedObjectContext`) - returns: `self` if found, or successfully created, `nil` otherwise */ internal static func getInboxAlphaName( alphaName name: String?, inManagedObjectContext managedObjectContext: NSManagedObjectContext? = GlobalMessageServiceCoreDataHelper.managedObjectContext) -> GMSInboxAlphaName? // swiftlint:disable:this opnening_brace { // swiftlint:enable line_length let aplhaNameString = name ?? unknownAlphaNameString let predicate = NSPredicate(format: "title == %@", aplhaNameString) guard let aplhaName = GMSInboxAlphaName.findObject( withPredicate: predicate, inManagedObjectContext: managedObjectContext) as? GMSInboxAlphaName else // swiftlint:disable:this opnening_brace { return .None } aplhaName.title = aplhaNameString return aplhaName } /** Unlocalized default string for unknown alpha-name in remote push-notification */ internal static var unknownAlphaNameString: String { return "_UNKNOWN_ALPHA_NAME_" } }
bec1d82212dfd4b1ac332e19d9d9fc20
30.54717
131
0.73445
false
false
false
false
tardieu/swift
refs/heads/master
test/SILGen/witness_same_type.swift
apache-2.0
1
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s protocol Fooable { associatedtype Bar func foo<T: Fooable where T.Bar == Self.Bar>(x x: T) -> Self.Bar } struct X {} // Ensure that the protocol witness for requirements with same-type constraints // is set correctly. <rdar://problem/16369105> // CHECK-LABEL: sil hidden [transparent] [thunk] @_T017witness_same_type3FooVAA7FooableAaaDP3foo3BarQzqd__1x_tAaDRd__AGQyd__AHRSlFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X struct Foo: Fooable { typealias Bar = X func foo<T: Fooable where T.Bar == X>(x x: T) -> X { return X() } } // rdar://problem/19049566 // CHECK-LABEL: sil [transparent] [thunk] @_T017witness_same_type14LazySequenceOfVyxq_Gs0E0AAsADRz8Iterator_7ElementQZRs_r0_lsADP04makeG0AEQzyFTW : $@convention(witness_method) <τ_0_0, τ_0_1 where τ_0_0 : Sequence, τ_0_1 == τ_0_0.Iterator.Element> (@in_guaranteed LazySequenceOf<τ_0_0, τ_0_1>) -> @out AnyIterator<τ_0_1> public struct LazySequenceOf<SS : Sequence, A where SS.Iterator.Element == A> : Sequence { public func makeIterator() -> AnyIterator<A> { var opt: AnyIterator<A>? return opt! } public subscript(i : Int) -> A { get { var opt: A? return opt! } } }
a62a46412e1b830b322336862919aec8
39.823529
320
0.680836
false
false
false
false