lang
stringclasses
10 values
seed
stringlengths
5
2.12k
swift
} movies += firstMovies } /* if movies.count == 1 { movies.append(first) }else{ let last = movies.last movies.append(first)
swift
let (ax,ay,az,t,gx,gy,gz) = mpu6050.getAll() let aX = Double(ax)/AccelRangeSensitivity let aY = Double(ay)/AccelRangeSensitivity let aZ = Double(az)/AccelRangeSensitivity let gX = Double(gx)/GyroRangeSensitivity let gY = Double(gy)/GyroRangeSensitivity let gZ = Double(gz)/GyroRangeSensitivity print(String(format: "aX = %4.1f g, aY = %4.1f g, aZ = %4.1f g, gX = %6.1f °/s, gY = %6.1f °/s, gZ = %6.1f °/s, T = %5.1f °C",
swift
} /// assign the `MKMapView` to `view` when the time comes public override func loadView() { view = MKMapView() } /// Good 'ol viewDidLoad...
swift
/*: ## 5.4 - SQL Formatted String To print SQL formatted string from a date instance you need to use the `.toSQL()` function. */ let sqlString = date3.toSQL() // "2015-11-19T22:20:40.000+01" /*: ## 5.5 - Relative/Colloquial Formatted String Colloquial format allows you to produce human friendly string as result of the difference between a date and a a reference date (typically now). Examples of colloquial formatted strings are `3 mins ago`, `2 days ago` or `just now`.
swift
public init(interactor: Interacting) { super.init(content: NoSymptomsContent(interactor: interactor)) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) }
swift
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b{let f=[]deinit{class b<T where h:A{var f=a<c
swift
// static var instance: protocol<DatabaseManagerProtocol> { get set } } /// Base database manager. /// - attention: Don't use this class directly, subclass it. open class KMPersistanceDatabase: NSObject {
swift
*/ import Foundation @objcMembers public class EmailEnvelope: NSObject, Codable { public var to: [String]? public var cc: [String]? public var bcc: [String]?
swift
.numberOfTouchesRequired(1) .isEnabled(true) .cancelsTouchesInView(false) .build() var applicableSections: [Section] = []
swift
/// Creates and updates the retention configuration with details about retention period (number of days) that AWS Config stores your historical information. The API creates the RetentionConfiguration object and names the object as default. When you have a RetentionConfiguration object named default, calling the API modifies the default object. Currently, AWS Config supports only one retention configuration per region in your account. public func putRetentionConfiguration(_ input: PutRetentionConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutRetentionConfigurationResponse> { return self.client.execute(operation: "PutRetentionConfiguration", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Saves a new query or updates an existing saved query. The QueryName must be unique for a single AWS account and a single AWS Region. You can create upto 300 queries in a single AWS account and a single AWS Region. public func putStoredQuery(_ input: PutStoredQueryRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutStoredQueryResponse> { return self.client.execute(operation: "PutStoredQuery", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) }
swift
enum HttpRequest { case app case api case bangumi
swift
genericSigniture = "" } else if input.isKnownType { genericSigniture = "<OUT: Deserializable>" } else if output.isKnownType { genericSigniture = "<IN: Serializable>" } else { genericSigniture = "<IN: Serializable, OUT: Deserializable>" } print("") print(" public func request\(genericSigniture)(_ endpoint: Endpoint<\(input), \(output)>\(inputSigniture)) -> Observable<Response<\(output)>> {") print(" return observe { self.fetcher.request(endpoint\(inputProvider), callback: $0) }") print(" }") } print("}")
swift
let loadedDictionary: [DictionaryEntry] = try DictionaryDecoder().load("TestDictionary") XCTAssertEqual(loadedDictionary.count, 2) } func testUnknownFile_expectsThrows() { XCTAssertThrowsError(try DictionaryDecoder().load("This-file-does-not-exists")) } }
swift
extractLabel?.text = nil case .relatedPages: isSaveButtonHidden = false descriptionLabel.text = article.capitalizedWikidataDescriptionOrSnippet extractLabel?.text = nil adjustMargins(for: index - 1, count: count - 1) // related pages start at 1 due to the source article at 0 case .mainPage: isSaveButtonHidden = true titleFontFamily = .georgia
swift
alertAndSheetReducer .pullback( state: \.alertAndActionSheet, action: /RootAction.alertAndActionSheet, environment: { _ in .init() } ), animationsReducer .pullback( state: \.animation,
swift
import Foundation import VISPER_Redux /// Feature represents a distinct funtionality of your application. /// It will be provided to all FeatureObservers after addition to configure and connect it to your application and your remaining /// features. Have look at LogicFeature and LogicFeatureObserver for an example. public protocol Feature { }
swift
window?.rootViewController = main window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
swift
public static func verifyTransaction( signedTx: Transaction, inputIndex: UInt32, utxo: TransactionOutput, blockTimeStamp: UInt32 = UInt32(NSTimeIntervalSince1970)) throws -> Bool { // Sanity check: transaction and its input should be consistent. guard inputIndex < signedTx.inputs.count else { throw ScriptMachineError.exception("Transaction and valid inputIndex are required for script verification.") } let context = ScriptExecutionContext(transaction: signedTx, utxoToVerify: utxo, inputIndex: inputIndex)! context.blockTimeStamp = blockTimeStamp let txInput: TransactionInput = signedTx.inputs[Int(inputIndex)] guard let unlockScript = Script(data: txInput.signatureScript), let lockScript = Script(data: utxo.lockingScript) else { throw ScriptMachineError.error("Both lock script and sig script must be valid.") }
swift
public final class BlockEndState: ATNState { public var startState: BlockStartState? override public func getStateType() -> Int { return ATNState.BLOCK_END
swift
text.isSecureTextEntry = true return text }() var passwordRequirement:UILabel={ let label = UILabel() label.Label(textColor: .Light, textAlignment: .center, fontSize: 15, font: .AppleSDGothicNeo_Regular) label.text = "Password req: uppercase and lowercase letter (A, z), numeric character (0-9), special character, and length between 6-12" return label }() var loadmore:UIButton={
swift
} } /// Handles a 'TLSUserEvent.handshakeCompleted' event and configures the pipeline to handle gRPC /// requests. private func handleHandshakeCompletedEvent( _ event: TLSUserEvent,
swift
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed import Distributed import FakeDistributedActorSystems @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem struct NotCodable {}
swift
// // Created by KangJungu on 25/03/2019. // Copyright © 2019 June. All rights reserved. // import RxSwift import ReactorKit
swift
// MARK: - Properties public var value: Type { didSet { removeNilObserverCallbacks() notifyCallbacks(value: oldValue, option: .old) notifyCallbacks(value: value, option: .new) } } // MARK: - Object Lifecycle public init(_ value: Type) {
swift
static let defaultHeight:CGFloat = 60.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActivityIndicator() } override init(frame aRect: CGRect) { super.init(frame: aRect) setupActivityIndicator() } override func layoutSubviews() {
swift
case .Float: let ret = math_vv_by_vForce(mfarray, vvcosf) ret.mfdata._mftype = .Float return ret case .Double: let ret = math_vv_by_vForce(mfarray, vvcos) ret.mfdata._mftype = .Double return ret } } /** Calculate the arccos for all elements - parameters: - mfarray: mfarray
swift
// p2q2 and q1 are colinear if orientation4 == 0 && onSegment(p: p2, q: q1, r: q2) { return true } return false
swift
// // Created by sagesse on 16/03/2017. // Copyright © 2017 SAGESSE. All rights reserved. // import UIKit
swift
refreshView.leftArrowStick.frame.height) } private func startLoading() { refreshView.airplane.center = CGPointMake(refreshView.frame.width / 2, 50) let airplaneAnimation = CAKeyframeAnimation.animationWith( AnimationType.PositionY,
swift
import UIKit extension Reactive where Base: UIResponder { /// Asks UIKit to make this object the first responder in its window. public var becomeFirstResponder: BindingTarget<()> { return makeBindingTarget { base, _ in base.becomeFirstResponder() } } /// Notifies this object that it has been asked to relinquish its status as first responder in its window. public var resignFirstResponder: BindingTarget<()> { return makeBindingTarget { base, _ in base.resignFirstResponder() } } }
swift
import XCTest import MKColorPicker class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() {
swift
// Test case found by fuzzing func a<T { var d = [ 1 class A { { { } } func a } ( (e : A.a
swift
/// done on this offset. /// /// - Remark: The implementation of this violates the API contract of `ManagedBufferPointer` by /// using its element pointer past the call to `withUnsafeMutablePointerToElements`. Based on /// the implementation of `ManagedBufferPointer` this is safe to do so long as the buffer /// itself lives past the usage of the pointer. In theory the stdlib could break this but that /// seems rather unlikely as that would mean it would have to yield a pointer to temporary /// storage, and that's contrary to the purpose of `ManagedBufferPointer`. This hack can be /// removed if [SR-13876][] is fixed. /// /// [SR-13876]: https://bugs.swift.org/browse/SR-13876 @inlinable subscript(_unsafeElementAt offset: Int) -> Element { _read {
swift
return supportedPermissionList } private func write(keys: KeysDictionary) { guard let data = try? JSONEncoder().encode(keys) else { return }
swift
// RUN: %FileCheck -check-prefix CHECK-WMO %s <%t/stderr_WMO_batch // RUN: %FileCheck -check-prefix CHECK-WMO %s <%t/stderr_batch_WMO // CHECK-WMO: warning: ignoring '-enable-batch-mode' because '-whole-module-optimization' was also specified // // RUN: %swiftppc_driver -index-file -enable-batch-mode %S/../Inputs/empty.swift -### 2>%t/stderr_index_batch | %FileCheck %s // RUN: %swiftppc_driver -enable-batch-mode -index-file %S/../Inputs/empty.swift -### 2>%t/stderr_batch_index | %FileCheck %s // RUN: %FileCheck -check-prefix CHECK-INDEX %s <%t/stderr_index_batch
swift
bootstrapCompleted: false, quizCard: [], currentIndex: 0, points: 0, currentQuizCard: nil, playerSelection: 0, gameSessionCompleted: false, isPlaying: false,
swift
if autoHide && CGFloat((activity?.alpha)!) >= 1.0 { if afterDelay { activity?.hide(true, afterDelay: 1.0) }else { activity?.hide(true) } } } func hideIndicator() { activity?.hide(true) }
swift
return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) }
swift
final class TweakFloatingPanel: UIViewController { private lazy var pan = _pan() private lazy var panIndicator = _panIndicator() private lazy var nameLabel = _nameLabel() private lazy var floatButton = _floatButton()
swift
[ 0xfffd, 0xfffd, 0xfffd, 0x0041 ], [ 0x41, 0xed, 0xa0, 0x80, 0x41 ])) // U+DB40 expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ], [ 0xed, 0xac, 0xa0 ])) // U+DBFF expectTrue(checkDecodeUTF8( [], [ 0xfffd, 0xfffd, 0xfffd ],
swift
} else { formData = MultipartFormData() } // Make sure all fields for files are set to null, or the server won't look // for the files in the rest of the form data let fieldsForFiles = Set(files.map { $0.fieldName }).sorted() var fields = self.requestBodyCreator.requestBody(for: operation, sendOperationIdentifiers: shouldSendOperationID) var variables = fields["variables"] as? GraphQLMap ?? GraphQLMap() for fieldName in fieldsForFiles { if let value = variables[fieldName],
swift
/* See LICENSE folder for this sample’s licensing information. Abstract: A view controller that demonstrates how to customize a `UIToolbar`. */
swift
} self.loginController.dismiss(animated: true) } // MARK: - VIPER /// Initialize the the view controller /// /// - Parameter presenter: The module's presenter
swift
public let id: Id public let status: Status public let sourceAccountId: KinAccount.Id public let destAccountId: KinAccount.Id public let amount: Kin public let fee: Quark public let memo: KinMemo public let timestamp: TimeInterval public let extra: Addendum? = nil
swift
super.init(name: name, pixels: [], anchorX: tile.anchorX, anchorY: tile.anchorY) } override func getWidth() -> Int { return Int.max } override func getHeight() -> Int {
swift
return } pushProperties.displayCount += 1 let pushProgress = pushProperties.pushProgress // print("第\(pushProperties.displayCount)次push的进度:\(pushProgress)") let fromVC = coordinator.viewController(forKey: .from) let toVC = coordinator.viewController(forKey: .to) updateNavigationBar(fromVC: fromVC, toVC: toVC, progress: pushProgress) } }
swift
// // Created by Mohan on 7/18/16. // Copyright © 2016 Comcast Cable Communications Management, LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at //
swift
// First, the MediaZoomAnimationController is non-interactive. We use it whenever we're going to // show the Media detail pager. // // We can get there several ways: // From conversation settings, this can be a push or a pop from the tileView. // From conversationView/MessageDetails this can be a modal present or a pop from the tile view. // // The other animation controller, the MediaDismissAnimationController is used when we're going to // stop showing the media pager. This can be a pop to the tile view, or a modal dismiss. protocol MediaPresentationContextProvider {
swift
Spacer() Text("\(player.copperProduction.intValue!)") .frame(width: 50) } } } } } }.onAppear() { _ = LCObject.fetch(dataStore.players, completion: { (result) in
swift
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selectionMenus.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = " \(selectionMenus[indexPath.row])" cell.textLabel?.font = .systemFont(ofSize: 17) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
swift
func testSlider() { let expectation = XCTestExpectation() let view = SliderTestView(spy: { expectation.fulfill() }) TestUtils.present(view: view) wait(for: [expectation], timeout: 1) } func testStepper() { let expectation = XCTestExpectation() let view = StepperTestView(spy: {
swift
// AlphaWalletTests // // Created by Vladyslav Shepitko on 11.05.2022. // @testable import AlphaWallet import PromiseKit
swift
// Created by Alejandro Alonso // Copyright © 2018 Alejandro Alonso. All rights reserved. // class TypeChecker: Diagnoser { var file: File var scopeVars = [String: Variable]() init(file: File) {
swift
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
swift
return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { Grade.resignFirstResponder() Nickname.resignFirstResponder() spot.resignFirstResponder() Born.resignFirstResponder()
swift
// // Servicable.swift // Requestable // // Created by Andrew Kochulab on 4/8/18. // Copyright © 2018. All rights reserved. // import Foundation public protocol Servicable { }
swift
case fullName = "full_name" case owner case stars = "stargazers_count" } init(id: Int, name: String, fullName: String, owner: Owner, stars: Int) { self.id = id self.name = name
swift
// Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a{typealias d:d func a
swift
// A boolean value indicating whether the map should try to display the user's location self.mapView.showsUserLocation = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK - Location Delegate Methods func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // Get last location of locations that have been passed in (most current)
swift
header = HeaderMessage() points = Point32Message[]() channels = ChannelFloat32Message[]() } public required init?(map: Map) { super.init(map: map) } public override func mapping(map: Map) { header <- map["header"] points <- map["points"] channels <- map["channels"] } }
swift
import Foundation /** Displayed when the app is sent to the background */ final class BackgoundViewController: UIViewController {
swift
// // Created by Stanislav Novacek on 05/04/2018. // Copyright © 2018 Stanislav Novacek. All rights reserved. // import Foundation import os.log
swift
} /// Expands the container out of its safe area. public enum ContainerIgnoresSafeArea { case disable /// equivalent to `ignoresSafeArea(_ regions: SafeAreaRegions = .all, edges: Edge.Set = .all)` case all /// set custom regions and edges of safe area case custom(SafeAreaRegions, Edge.Set) }
swift
name: "Server", dependencies: [ .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "3.0.0")), .package(url: "https://github.com/vapor/jwt.git", .upToNextMajor(from: "3.0.0-rc")), .package(url: "https://github.com/vapor/leaf.git", .upToNextMajor(from: "3.0.0-rc")), .package(url: "https://github.com/vapor/console.git", .upToNextMajor(from: "3.0.0")), .package(url: "https://github.com/vapor/websocket", .upToNextMajor(from: "1.0.0")), .package(url: "https://github.com/vapor/validation.git", .upToNextMajor(from: "2.0.0")), .package(url: "https://github.com/vapor-community/clibressl.git", .upToNextMajor(from: "1.0.0")), .package(url: "https://github.com/vapor-community/copenssl.git", .upToNextMajor(from: "1.0.0-rc")), .package(url: "https://github.com/OpenKitten/MongoKitten.git", .upToNextMajor(from: "4.0.0")),
swift
// The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Simple QR Reader", platforms: [ .iOS(.v13) ], products: [ .library(
swift
// // Created by Dariusz Grzeszczak on 06/08/2021. // import Foundation struct EmptyState: StoreState { var factory: ViewModelFactory = CompositeViewModelFactory() }
swift
// 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,
swift
func trackScoredPoint(scoringPlayer: ScoringPLayer, game: Game) -> IO<Never, Game> { return IO.invoke { trackScorePointFor(scoringPlayer: scoringPlayer, game: game) } }
swift
return uids } private func updatePriceItems(items: [Item], map: [String: WalletCoinPriceService.Item]) { for item in items { for assetItem in item.assetItems { assetItem.priceItem = assetItem.price.flatMap { map[$0.platformCoin.coin.uid] }
swift
var poster: String { model?.poster ?? "" } /// Title for the film as a String. var title: String { model?.title ?? "" } /// Plot details for the film as a String. var plot: String { model?.plot ?? "No details"
swift
// MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. }
swift
view.backgroundColor = ColorUtil.backgroundColor return view }() public override init(frame: CGRect) {
swift
// // ---------------------------------------------------------------------------- class IntegerOperatorsTests: ObjectMapperTests { // Do nothing } // ----------------------------------------------------------------------------
swift
// Name.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation /** Model for testing model name same as property name */ open class Name: JSONEncodable { public var name: Int32
swift
return VertexBuffer(device: device, vertices: vertices(for: rect)) } func texture(of image: XImage) -> MTLTexture? { guard let cgImage: CGImage = image.cgImage else { return nil }
swift
self.destination = destination } func undo() { do { try self.destination.remove_card(self.card) } catch { fatalError("CardMove undo unsuccesful") } self.source.put_card(self.card) destination.display_cards() }
swift
if isEmpty { return nil } else { return array.removeFirst() } }
swift
completion: { [weak self] _ in self?.animated(then: then) } ) } func animated(then: @escaping Completion) { assert(Thread.isMainThread) if isUpdatingAnnotations {
swift
func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } }
swift
// // AnimationFrames.swift // Swift Radio // // Created by Matthew Fecher on 7/2/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit class AnimationFrames { class func createFrames() -> [UIImage] {
swift
init( networkingService: Networking, cache: CacheWrapper<String, [Beer]> = CacheWrapper(base: Cache<String, [Beer]>(maximumEntryCount: 15)) ) { self.networkingService = networkingService self.cache = cache } func fetchBeers(name: String?, page: Int?, then handler: @escaping CompletionBlock) { let endpoint = API.beerList(name: name, at: page) let cacheKey = endpoint.url.absoluteString
swift
self.daysSinceLastExposure = summary.daysSinceLastExposure self.matchedKeyCount = summary.matchedKeyCount self.maximumRiskScore = summary.maximumRiskScore self.maximumRiskScoreFullRange = (summary.metadata?["maximumRiskScoreFullRange"] as? NSNumber)?.intValue ?? 0 if let attenuationDurations = summary.metadata?["attenuationDurations"] as? [NSNumber] { self.configuredAttenuationDurations = attenuationDurations.map { Double($0.floatValue) }
swift
func proc(_ odds: Int) -> Bool { let random = arc4random_uniform(UInt32(self)) return odds > Int(random) } }
swift
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.
swift
dictionary["mutual_friend_count"] = mutualFriendCount } if let measurementPreference = measurementPreference { dictionary["measurement_preference"] = measurementPreference } if let email = email { dictionary["email"] = email } return dictionary } /** Failable initializer. */
swift
import FMCore /** MedicationRequest Administration Location Codes URL: http://terminology.hl7.org/CodeSystem/medicationrequest-admin-location ValueSet: http://hl7.org/fhir/ValueSet/medicationrequest-admin-location */ public enum MedicationRequestAdministrationLocationCodes: String, FHIRPrimitiveType { /// Includes requests for medications to be administered or consumed in an inpatient or acute care setting
swift
#else /** * Splits a string into an array of string components. * * - parameter by: The character to split on. * - parameter maxSplits: The maximum number of splits to perform. If 0, all possible splits are made. * * - returns: An array of string components. */ func split(by by: Character, maxSplits: Int = 0) -> [String] { var s = [String]() var numSplits = 0
swift
// When let feature = sut.getItems(with: criteria) let items = try feature.wait() // Then XCTAssertEqual(items.map { $0.id }, [givenItem.id])
swift
.bind(host: "127.0.0.1", port: 0) .wait()) // Make a client socket to mess with the server. Setting SO_LINGER forces RST instead of FIN. let clientSocket = try assertNoThrowWithValue(Socket(protocolFamily: AF_INET, type: Posix.SOCK_STREAM)) XCTAssertNoThrow(try clientSocket.setOption(level: SOL_SOCKET, name: SO_LINGER, value: linger(l_onoff: 1, l_linger: 0))) XCTAssertNoThrow(try clientSocket.connect(to: serverChannel.localAddress!)) XCTAssertNoThrow(try clientSocket.close()) // Trigger accept() in the server serverChannel.read() // Wait for the server to have something let result = try assertNoThrowWithValue(serverPromise.futureResult.wait())
swift
case sixMinuteWalkTestDistance case stairAscentSpeed case stairDescentSpeed case heartRate case bodyTemperature case basalBodyTemperature case bloodPressureSystolic case bloodPressureDiastolic case respiratoryRate case restingHeartRate case walkingHeartRateAverage case heartRateVariabilitySDNN case oxygenSaturation case peripheralPerfusionIndex
swift
/*: ![Make School Banner](./swift_banner.png) # Object-Oriented Programming: An Introduction In this tutorial, we're going to learn about _Object-Oriented Programming_ in Swift. What is that? It's a _programming paradigm_ based on the concept of "objects" – things that contain data, and methods that perform operations on those data.
swift
// The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Quick import Nimble
swift
func breakWithError(error: ErrorType); var error:ErrorType? {get} var force:Bool {get set} var status:OperationStatus {get set} var stage:OperationStage {get set} var data:NSData? {get set} var results:[AnyObject]? {get set} var convertedObject:AnyObject? {get set}
swift
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1) let section = NSCollectionLayoutSection(group: group) section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) section.interGroupSpacing = 10 let headerFooterSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(40)
swift
myTokenCodes <- map["myTokenCodes"] removedTokenCodes <- map["removedTokenCodes"] } init(myTokenCodes: [TokenCode], removedTokenCodes: [TokenCode]) { self.myTokenCodes = myTokenCodes self.removedTokenCodes = removedTokenCodes }
swift
containerView.label2.snp.makeConstraints { $0.top.equalTo(containerView.label1.snp.bottom).offset(Design.smallPadding) $0.trailing.equalToSuperview().inset(Design.largestPadding) $0.bottom.equalToSuperview().inset(Design.nomalPadding) }
swift
self.measure() { // Put the code you want to measure the time of here. } } }
swift
/// A protocol used to represent the data for a location message. public protocol LocationItem { /// The location. var location: CLLocation { get } /// The size of the location item. var size: CGSize { get }
swift
case conector case haveMultipleURNService case id case maintenance case oauth2 case saml case sendRequestorAuthZ case subscriberIdData case whitelistDomains case wsAPIKey case wsMaintenance case wsMaintenanceCountry case wsNameSpace case wsURL }
swift
import Foundation struct Feed: Codable { let feedId: Int let clubName: String let clubId: Int?